diff --git a/app/src/main/rust/gfn/Cargo.lock b/app/src/main/rust/gfn/Cargo.lock index 426f71047..63439a495 100644 --- a/app/src/main/rust/gfn/Cargo.lock +++ b/app/src/main/rust/gfn/Cargo.lock @@ -983,8 +983,6 @@ dependencies = [ [[package]] name = "mtu" version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6915088ba81d679b0a07ecc674f31d66af5e7edaeb0c34782669be38cdf67b5" dependencies = [ "bindgen", "cfg_aliases", diff --git a/app/src/main/rust/gfn/Cargo.toml b/app/src/main/rust/gfn/Cargo.toml index 663a48214..b5c9fce77 100644 --- a/app/src/main/rust/gfn/Cargo.toml +++ b/app/src/main/rust/gfn/Cargo.toml @@ -21,6 +21,8 @@ opennow-streamer-platform = { path = "../../../../../external/opennow/native/ope opennow-streamer-protocol = { path = "../../../../../external/opennow/native/opennow-streamer/crates/opennow-streamer-protocol" } [patch.crates-io] +# DroidDeck: mtu 0.3.0 with a versioned Android target for bindgen (vendor/mtu/build.rs). +mtu = { path = "../../../../../external/opennow/native/opennow-streamer/vendor/mtu" } str0m = { path = "../../../../../external/opennow/native/opennow-streamer/vendor/str0m" } audiopus_sys = { path = "../../../../../external/opennow/native/opennow-streamer/vendor/audiopus-sys" } diff --git a/external/opennow/CHANGES.md b/external/opennow/CHANGES.md index 0cb6f022b..a72bce2bb 100644 --- a/external/opennow/CHANGES.md +++ b/external/opennow/CHANGES.md @@ -22,3 +22,8 @@ Windows, macOS and Linux. backends; recording, replay and the microphone report "not available". - `Cargo.toml`: SDL2, openh264, the recording muxers and the Windows crate are desktop-only; Android adds `ndk`, `ndk-sys`, `jni`, `log`. +- `opennow-streamer/vendor/mtu` (new, DroidDeck): mozilla's `mtu` 0.3.0 (MIT/Apache-2.0) + with one change in `build.rs`: on Android, bindgen gets a versioned target + (`--target=29`), since the NDK headers reject an unversioned triple and + cargo-ndk's bindgen arguments do not carry the API level. Patched in from + `opennow-streamer/Cargo.toml` and DroidDeck's `app/src/main/rust/gfn/Cargo.toml`. diff --git a/external/opennow/native/opennow-streamer/Cargo.toml b/external/opennow/native/opennow-streamer/Cargo.toml index eecf4c256..c2237ab77 100644 --- a/external/opennow/native/opennow-streamer/Cargo.toml +++ b/external/opennow/native/opennow-streamer/Cargo.toml @@ -59,6 +59,8 @@ codegen-units = 1 strip = true [patch.crates-io] +# DroidDeck: mtu 0.3.0 with a versioned Android target for bindgen (vendor/mtu/build.rs). +mtu = { path = "vendor/mtu" } str0m = { path = "vendor/str0m" } # Always compile the vendored Opus sources for the distributable streamer. audiopus_sys = { path = "vendor/audiopus-sys" } diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/.cargo-ok b/external/opennow/native/opennow-streamer/vendor/mtu/.cargo-ok new file mode 100644 index 000000000..5f8b79583 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/.cargo-ok @@ -0,0 +1 @@ +{"v":1} \ No newline at end of file diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/.clippy.toml b/external/opennow/native/opennow-streamer/vendor/mtu/.clippy.toml new file mode 100644 index 000000000..5539ef094 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/.clippy.toml @@ -0,0 +1 @@ +disallowed-methods = [] diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/Cargo.lock b/external/opennow/native/opennow-streamer/vendor/mtu/Cargo.lock new file mode 100644 index 000000000..76cf88e77 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/Cargo.lock @@ -0,0 +1,401 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2135563fb5c609d2b2b87c1e8ce7bc41b0b45430fa9661f457981503dd5bf0" +dependencies = [ + "memchr", +] + +[[package]] +name = "bindgen" +version = "0.72.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f72209734318d0b619a5e0f5129918b848c416e122a3c4ce054e03cb87b726f" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn", +] + +[[package]] +name = "bitflags" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "clang-sys" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "either" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "libc" +version = "0.2.176" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174" + +[[package]] +name = "libloading" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" +dependencies = [ + "cfg-if", + "windows-targets", +] + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mozbuild" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "903970ae2f248d7275214cf8f387f8ba0c4ea7e3d87a320e85493db60ce28616" + +[[package]] +name = "mtu" +version = "0.3.0" +dependencies = [ + "bindgen", + "cfg_aliases", + "libc", + "mozbuild", + "static_assertions", + "windows", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +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", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[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_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[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_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[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_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/Cargo.toml b/external/opennow/native/opennow-streamer/vendor/mtu/Cargo.toml new file mode 100644 index 000000000..51f41b92f --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/Cargo.toml @@ -0,0 +1,179 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.81.0" +name = "mtu" +version = "0.3.0" +authors = ["The Neqo Authors "] +build = "build.rs" +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Obtain the local network interface MTU towards a given IP address." +homepage = "https://github.com/mozilla/neqo/" +readme = "README.md" +keywords = [ + "mozilla", + "interface", + "mtu", +] +categories = [ + "network-programming", + "web-programming", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/mozilla/neqo/" + +[package.metadata.cargo-machete] +ignored = [ + "bindgen", + "cfg_aliases", +] + +[badges.maintenance] +branch = "main" +status = "actively-developed" + +[features] +gecko = ["dep:mozbuild"] + +[lib] +name = "mtu" +path = "src/lib.rs" +bench = false + +[dependencies.libc] +version = "0.2" +default-features = false + +[dependencies.static_assertions] +version = "1.1" +default-features = false + +[build-dependencies.bindgen] +version = "0.72" +features = ["runtime"] +default-features = false + +[build-dependencies.cfg_aliases] +version = "0.2" +default-features = false + +[build-dependencies.mozbuild] +version = "0.1" +optional = true +default-features = false + +[target."cfg(windows)".dependencies.windows] +version = ">=0.60,<0.63" +features = [ + "Win32_Foundation", + "Win32_NetworkManagement_IpHelper", + "Win32_NetworkManagement_Ndis", + "Win32_Networking_WinSock", +] +default-features = false + +[lints.clippy] +allow_attributes = "warn" +allow_attributes_without_reason = "warn" +cfg_not_test = "warn" +clone_on_ref_ptr = "warn" +create_dir = "warn" +dbg_macro = "warn" +empty_drop = "warn" +empty_enum_variants_with_brackets = "warn" +field_scoped_visibility_modifiers = "warn" +filetype_is_file = "warn" +float_cmp_const = "warn" +fn_to_numeric_cast_any = "warn" +get_unwrap = "warn" +if_then_some_else_none = "warn" +infinite_loop = "warn" +iter_over_hash_type = "warn" +large_include_file = "warn" +let_underscore_must_use = "warn" +let_underscore_untyped = "warn" +literal_string_with_formatting_args = "allow" +lossy_float_literal = "warn" +map_with_unused_argument_over_ranges = "warn" +mem_forget = "warn" +missing_asserts_for_indexing = "warn" +mixed_read_write_in_expression = "warn" +module_name_repetitions = "warn" +multiple_crate_versions = "allow" +multiple_inherent_impl = "warn" +mutex_atomic = "warn" +mutex_integer = "warn" +needless_raw_strings = "warn" +non_ascii_literal = "warn" +non_zero_suggestions = "warn" +partial_pub_fields = "warn" +pathbuf_init_then_push = "warn" +precedence_bits = "warn" +pub_without_shorthand = "warn" +rc_buffer = "warn" +rc_mutex = "warn" +redundant_test_prefix = "warn" +redundant_type_annotations = "warn" +ref_patterns = "warn" +renamed_function_params = "warn" +rest_pat_in_fully_bound_structs = "warn" +return_and_then = "warn" +self_named_module_files = "warn" +semicolon_inside_block = "warn" +string_lit_chars_any = "warn" +suspicious_xor_used_as_pow = "warn" +try_err = "warn" +unnecessary_safety_comment = "warn" +unnecessary_safety_doc = "warn" +unnecessary_self_imports = "warn" +unneeded_field_pattern = "warn" +unused_result_ok = "warn" +unused_trait_names = "warn" +unwrap_in_result = "warn" +unwrap_used = "warn" +verbose_file_reads = "warn" + +[lints.clippy.cargo] +level = "warn" +priority = -1 + +[lints.clippy.nursery] +level = "warn" +priority = -1 + +[lints.clippy.pedantic] +level = "warn" +priority = -1 + +[lints.rust] +absolute_paths_not_starting_with_crate = "warn" +explicit_outlives_requirements = "warn" +macro_use_extern_crate = "warn" +missing_abi = "warn" +non_ascii_idents = "warn" +redundant_lifetimes = "warn" +trivial_numeric_casts = "warn" +unit_bindings = "warn" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" +unused_qualifications = "warn" + +[lints.rust.unexpected_cfgs] +level = "warn" +priority = 0 +check-cfg = ["cfg(coverage,coverage_nightly,fuzzing)"] diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/LICENSE-APACHE b/external/opennow/native/opennow-streamer/vendor/mtu/LICENSE-APACHE new file mode 100644 index 000000000..16fe87b06 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/LICENSE-MIT b/external/opennow/native/opennow-streamer/vendor/mtu/LICENSE-MIT new file mode 100644 index 000000000..b4850c952 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2019 Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/README.md b/external/opennow/native/opennow-streamer/vendor/mtu/README.md new file mode 100644 index 000000000..33ff57f87 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/README.md @@ -0,0 +1,48 @@ +[![Coverage Status](https://codecov.io/gh/mozilla/mtu/branch/main/graph/badge.svg)](https://codecov.io/gh/mozilla/mtu) +[![Average time to resolve an issue](https://isitmaintained.com/badge/resolution/mozilla/mtu.svg)](https://isitmaintained.com/project/mozilla/mtu "Average time to resolve an issue") +[![Percentage of issues still open](https://isitmaintained.com/badge/open/mozilla/mtu.svg)](https://isitmaintained.com/project/mozilla/mtu "Percentage of issues still open") +![Maintenance](https://img.shields.io/badge/maintenance-activly--developed-brightgreen.svg) + +# mtu + +A crate to return the name and maximum transmission unit (MTU) of the local network interface +towards a given destination `SocketAddr`, optionally from a given local `SocketAddr`. + +## Usage + +This crate exports a single function `interface_and_mtu` that returns the name and +[maximum transmission unit (MTU)](https://en.wikipedia.org/wiki/Maximum_transmission_unit) +of the outgoing network interface towards a remote destination identified by an `IpAddr`. + +## Example + +```rust +let destination = IpAddr::V4(Ipv4Addr::LOCALHOST); +let (name, mtu): (String, usize) = mtu::interface_and_mtu(destination).unwrap(); +println!("MTU towards {destination} is {mtu} on {name}"); +``` + +## Supported Platforms + +* Linux +* Android +* macOS +* Windows +* FreeBSD +* NetBSD +* OpenBSD +* Solaris + +## Notes + +The returned MTU may exceed the maximum IP packet size of 65,535 bytes on some platforms for +some remote destinations. (For example, loopback destinations on Windows.) + +The returned interface name is obtained from the operating system. + +## Contributing + +We're happy to receive PRs that improve this crate. Please take a look at our [community +guidelines](CODE_OF_CONDUCT.md) beforehand. + +License: MIT OR Apache-2.0 diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/SECURITY.md b/external/opennow/native/opennow-streamer/vendor/mtu/SECURITY.md new file mode 100644 index 000000000..547ca587e --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/SECURITY.md @@ -0,0 +1,31 @@ +# Security Policy + +This document describes how security vulnerabilities in this project should be reported. + +## Supported Versions + +Support for `mtu` is based on the Firefox version in which it has landed. +Versions of `mtu` in [current versions of Firefox](https://whattrainisitnow.com/calendar/) are actively supported. + +The version of `mtu` that is active can be found in the Firefox repositories: + +- [release](https://hg.mozilla.org/mozilla-unified/file/release/third_party/rust/mtu-transport/Cargo.toml), +- [beta](https://hg.mozilla.org/mozilla-unified/file/beta/third_party/rust/mtu-transport/Cargo.toml), and +- [trunk/central](https://hg.mozilla.org/mozilla-unified/file/central/third_party/rust/mtu-transport/Cargo.toml), +- [ESR 115](https://hg.mozilla.org/mozilla-unified/file/esr115/third_party/rust/mtu-transport/Cargo.toml). + +The listed version in these files corresponds to [tags](https://github.com/mozilla/mtu/tags) on this repository. +Releases do not always correspond to a branch. + +We welcome reports of security vulnerabilities in any of these released versions or the latest code on the `main` branch. + +## Reporting a Vulnerability + +To report a security problem with `mtu`, create a bug in Mozilla's Bugzilla instance in the [Core :: Networking](https://bugzilla.mozilla.org/enter_bug.cgi?product=Core&component=Networking) component. + +**IMPORTANT: For security issues, please make sure that you check the box labelled "Many users could be harmed by this security problem".** +We advise that you check this option for anything that involves anything security-relevant, including memory safety, crashes, race conditions, and handling of confidential information. + +Review Mozilla's [guides on bug reporting](https://bugzilla.mozilla.org/page.cgi?id=bug-writing.html) before you open a bug. + +Mozilla operates a [bug bounty program](https://www.mozilla.org/en-US/security/bug-bounty/), for which this project is eligible. diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/build.rs b/external/opennow/native/opennow-streamer/vendor/mtu/build.rs new file mode 100644 index 000000000..5defacc91 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/build.rs @@ -0,0 +1,112 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![expect(clippy::unwrap_used, reason = "OK in build scripts.")] + +use std::env; + +const BINDINGS: &str = "bindings.rs"; + +#[cfg(feature = "gecko")] +fn clang_args() -> Vec { + use mozbuild::{config::BINDGEN_SYSTEM_FLAGS, TOPOBJDIR}; + + let mut flags: Vec = BINDGEN_SYSTEM_FLAGS.iter().map(|s| s.to_string()).collect(); + + flags.push(String::from("-include")); + flags.push( + TOPOBJDIR + .join("dist") + .join("include") + .join("mozilla-config.h") + .to_str() + .unwrap() + .to_string(), + ); + flags +} + +#[cfg(not(feature = "gecko"))] +fn clang_args() -> Vec { + // DroidDeck: the NDK's headers reject an unversioned Android triple, and cargo-ndk's + // BINDGEN_EXTRA_CLANG_ARGS do not carry the API level, so pass a versioned target. + if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") { + let target = env::var("TARGET").unwrap_or_default(); + let api = env::var("DROIDDECK_ANDROID_API").unwrap_or_else(|_| "29".to_owned()); + return vec![format!("--target={target}{api}")]; + } + Vec::new() +} + +fn bindgen() { + let target_os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS was not set"); + + // Platforms currently not supported. + // + // See . + if matches!(target_os.as_str(), "ios" | "tvos" | "visionos") { + return; + } + + if target_os == "windows" { + return; + } + + let bindings = if matches!(target_os.as_str(), "linux" | "android") { + bindgen::Builder::default() + .header_contents("rtnetlink.h", "#include ") + // Only generate bindings for the following types + .allowlist_type("rtattr|rtmsg|ifinfomsg|nlmsghdr") + } else { + bindgen::Builder::default() + .header_contents( + "route.h", + "#include \n#include \n#include \n#include ", + ) + // Only generate bindings for the following types and items + .allowlist_type("rt_msghdr|rt_metrics|if_data") + .allowlist_item("RTAX_MAX|RTM_GET|RTM_VERSION|RTA_DST|RTA_IFP") + }; + + let bindings = bindings + .clang_args(clang_args()) + // Tell cargo to invalidate the built crate whenever any of the + // included header files changed. + .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) + // Constants should be generated as &CStr instead of &[u8]. + .generate_cstr(true) + // Always emit explicit padding fields. + .explicit_padding(true) + // Default trait should be derived when possible + .derive_default(true) + // Finish the builder and generate the bindings. + .generate() + // Unwrap the Result and panic on failure. + .expect("Unable to generate bindings"); + + // Write the bindings to the $OUT_DIR/$BINDINGS file. + let out_path = std::path::PathBuf::from(env::var("OUT_DIR").unwrap()).join(BINDINGS); + bindings + .write_to_file(out_path.clone()) + .expect("Couldn't write bindings!"); + println!("cargo:rustc-env=BINDINGS={}", out_path.display()); +} + +fn main() { + // Setup cfg aliases + cfg_aliases::cfg_aliases! { + bsd: { + any( + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris" + ) + } + } + + bindgen(); +} diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/src/bsd.rs b/external/opennow/native/opennow-streamer/vendor/mtu/src/bsd.rs new file mode 100644 index 000000000..494cc61cd --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/src/bsd.rs @@ -0,0 +1,398 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::{ + ffi::CStr, + io::{Error, ErrorKind, Read as _, Result, Write as _}, + marker::PhantomData, + net::IpAddr, + num::TryFromIntError, + ops::Deref, + ptr, slice, +}; + +use libc::{ + freeifaddrs, getifaddrs, getpid, if_indextoname, ifaddrs, in6_addr, in_addr, sockaddr, + sockaddr_dl, sockaddr_in, sockaddr_in6, sockaddr_storage, AF_UNSPEC, PF_ROUTE, +}; +use static_assertions::{const_assert, const_assert_eq}; + +#[allow( + clippy::allow_attributes, + clippy::allow_attributes_without_reason, + non_camel_case_types, + non_snake_case, + clippy::struct_field_names, + clippy::too_many_lines, + clippy::cognitive_complexity, + dead_code, // RTA_IFP is only used on NetBSD and Solaris + reason = "Bindgen-generated code" +)] +mod bindings { + include!(env!("BINDINGS")); +} + +#[cfg(any(target_os = "netbsd", target_os = "solaris"))] +use crate::bsd::bindings::RTA_IFP; +use crate::{ + aligned_by, + bsd::bindings::{if_data, rt_msghdr, RTAX_MAX, RTA_DST}, + default_err, + routesocket::RouteSocket, + unlikely_err, +}; + +#[cfg(target_os = "macos")] +const ALIGN: usize = size_of::(); + +#[cfg(bsd)] +// See https://github.com/freebsd/freebsd-src/blob/524a425d30fce3d5e47614db796046830b1f6a83/sys/net/route.h#L362-L371 +// See https://github.com/NetBSD/src/blob/4b50954e98313db58d189dd87b4541929efccb09/sys/net/route.h#L329-L331 +// See https://github.com/Arquivotheca/Solaris-8/blob/2ad1d32f9eeed787c5adb07eb32544276e2e2444/osnet_volume/usr/src/cmd/cmd-inet/usr.sbin/route.c#L238-L239 +const ALIGN: usize = size_of::(); + +#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))] +asserted_const_with_type!(RTM_ADDRS, i32, RTA_DST, u32); + +#[cfg(any(target_os = "netbsd", target_os = "solaris"))] +asserted_const_with_type!(RTM_ADDRS, i32, RTA_DST | RTA_IFP, u32); + +#[cfg(not(target_os = "solaris"))] +type AddressFamily = u8; + +#[cfg(target_os = "solaris")] +type AddressFamily = u16; + +asserted_const_with_type!(AF_INET, AddressFamily, libc::AF_INET, i32); +asserted_const_with_type!(AF_INET6, AddressFamily, libc::AF_INET6, i32); +asserted_const_with_type!(AF_LINK, AddressFamily, libc::AF_LINK, i32); +asserted_const_with_type!(RTM_VERSION, u8, bindings::RTM_VERSION, u32); +asserted_const_with_type!(RTM_GET, u8, bindings::RTM_GET, u32); + +const_assert!(size_of::() + ALIGN <= u8::MAX as usize); +const_assert!(size_of::() + ALIGN <= u8::MAX as usize); +const_assert!(size_of::() <= u8::MAX as usize); + +struct IfAddrs(*mut ifaddrs); + +impl Default for IfAddrs { + fn default() -> Self { + Self(ptr::null_mut()) + } +} + +impl IfAddrs { + fn new() -> Result { + let mut ifap = Self::default(); + // getifaddrs allocates memory for the linked list of interfaces that is freed by + // `IfAddrs::drop`. + if unsafe { getifaddrs(ptr::from_mut(&mut ifap.0)) } != 0 { + return Err(Error::last_os_error()); + } + Ok(ifap) + } + + const fn iter(&self) -> IfAddrPtr<'_> { + IfAddrPtr { + ptr: self.0, + _ref: PhantomData, + } + } +} + +impl Drop for IfAddrs { + fn drop(&mut self) { + if !self.0.is_null() { + // Free the memory allocated by `getifaddrs`. + unsafe { + freeifaddrs(self.0); + } + } + } +} + +struct IfAddrPtr<'a> { + ptr: *mut ifaddrs, + _ref: PhantomData<&'a ifaddrs>, +} + +impl IfAddrPtr<'_> { + fn addr(&self) -> sockaddr { + unsafe { *self.ifa_addr } + } + + fn name(&self) -> String { + unsafe { CStr::from_ptr(self.ifa_name).to_string_lossy().to_string() } + } + + fn data(&self) -> Option { + if self.ifa_data.is_null() { + None + } else { + Some(unsafe { self.ifa_data.cast::().read() }) + } + } +} + +impl Deref for IfAddrPtr<'_> { + type Target = ifaddrs; + + fn deref(&self) -> &Self::Target { + unsafe { self.ptr.as_ref().expect("can deref") } + } +} + +impl Iterator for IfAddrPtr<'_> { + type Item = Self; + + fn next(&mut self) -> Option { + ptr::NonNull::new(self.ptr).map(|p| { + self.ptr = unsafe { p.as_ref().ifa_next }; + IfAddrPtr { + ptr: p.as_ptr(), + _ref: PhantomData, + } + }) + } +} + +fn if_name_mtu(idx: u32) -> Result<(String, Option)> { + let mut name = [0; libc::IF_NAMESIZE]; + // if_indextoname writes into the provided buffer. + if unsafe { if_indextoname(idx, name.as_mut_ptr()).is_null() } { + return Err(Error::last_os_error()); + } + // Convert to Rust string. + let name = unsafe { + CStr::from_ptr(name.as_ptr()) + .to_str() + .map_err(Error::other)? + }; + let mtu = IfAddrs::new()? + .iter() + .find(|ifa| ifa.addr().sa_family == AF_LINK && ifa.name() == name) + .and_then(|ifa| ifa.data()) + .and_then(|ifa_data| usize::try_from(ifa_data.ifi_mtu).ok()); + Ok((name.to_string(), mtu)) +} + +#[repr(C)] +union SockaddrStorage { + sin: sockaddr_in, + sin6: sockaddr_in6, +} + +fn sockaddr_len(af: AddressFamily) -> Result { + let sa_len = match af { + AF_INET => size_of::(), + AF_INET6 => size_of::(), + _ => { + return Err(Error::new( + ErrorKind::InvalidInput, + format!("Unsupported address family {af:?}"), + )) + } + }; + Ok(aligned_by(sa_len, ALIGN)) +} + +impl From for SockaddrStorage { + fn from(ip: IpAddr) -> Self { + match ip { + IpAddr::V4(ip) => SockaddrStorage { + sin: sockaddr_in { + #[cfg(not(target_os = "solaris"))] + #[expect( + clippy::cast_possible_truncation, + reason = "`sockaddr_in` len is <= u8::MAX per `const_assert!` above." + )] + sin_len: size_of::() as u8, + sin_family: AF_INET, + sin_addr: in_addr { + s_addr: u32::from_ne_bytes(ip.octets()), + }, + sin_port: 0, + sin_zero: [0; 8], + }, + }, + IpAddr::V6(ip) => SockaddrStorage { + sin6: sockaddr_in6 { + #[cfg(not(target_os = "solaris"))] + #[expect( + clippy::cast_possible_truncation, + reason = "`sockaddr_in6` len is <= u8::MAX per `const_assert!` above." + )] + sin6_len: size_of::() as u8, + sin6_family: AF_INET6, + sin6_addr: in6_addr { + s6_addr: ip.octets(), + }, + sin6_port: 0, + sin6_flowinfo: 0, + sin6_scope_id: 0, + #[cfg(target_os = "solaris")] + __sin6_src_id: 0, + }, + }, + } + } +} + +#[repr(C)] +struct RouteMessage { + rtm: rt_msghdr, + sa: SockaddrStorage, +} + +#[cfg(target_os = "openbsd")] +fn getrtable() -> u16 { + extern "C" { + fn getrtable() -> libc::c_int; + } + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "`getrtable` returns a `c_int`." + )] + unsafe { + getrtable() as u16 + } +} + +impl RouteMessage { + fn new(remote: IpAddr, seq: i32) -> Result { + let sa = SockaddrStorage::from(remote); + let sa_len = sockaddr_len(match remote { + IpAddr::V4(_) => AF_INET, + IpAddr::V6(_) => AF_INET6, + })?; + Ok(Self { + rtm: rt_msghdr { + #[expect( + clippy::cast_possible_truncation, + reason = "`rt_msghdr` len + `ALIGN` is <= u8::MAX per `const_assert!` above." + )] + rtm_msglen: (size_of::() + sa_len) as u16, + rtm_version: RTM_VERSION, + rtm_type: RTM_GET, + rtm_seq: seq, + rtm_addrs: RTM_ADDRS, + #[cfg(target_os = "openbsd")] + rtm_tableid: getrtable(), + ..Default::default() + }, + sa, + }) + } + + const fn version(&self) -> u8 { + self.rtm.rtm_version + } + + const fn kind(&self) -> u8 { + self.rtm.rtm_type + } + + const fn len(&self) -> usize { + self.rtm.rtm_msglen as usize + } +} + +impl From<&RouteMessage> for &[u8] { + fn from(value: &RouteMessage) -> Self { + debug_assert!(value.len() >= size_of::()); + unsafe { slice::from_raw_parts(ptr::from_ref(value).cast(), value.len()) } + } +} + +impl From<&[u8]> for rt_msghdr { + fn from(value: &[u8]) -> Self { + debug_assert!(value.len() >= size_of::()); + unsafe { ptr::read_unaligned(value.as_ptr().cast()) } + } +} + +fn if_index_mtu(remote: IpAddr) -> Result<(u16, Option)> { + // Open route socket. + let mut fd = RouteSocket::new(PF_ROUTE, AF_UNSPEC)?; + + // Send route message. + let query_seq = RouteSocket::new_seq(); + let query = RouteMessage::new(remote, query_seq)?; + let query_version = query.version(); + let query_type = query.kind(); + fd.write_all((&query).into())?; + + // Read route messages. + let pid = unsafe { getpid() }; + loop { + let mut buf = vec![ + 0u8; + size_of::() + + // There will never be `RTAX_MAX` sockaddrs attached, but it's a safe upper bound. + (RTAX_MAX as usize * size_of::()) + ]; + let len = fd.read(&mut buf[..])?; + if len < size_of::() { + return Err(default_err()); + } + let (reply, mut sa) = buf.split_at(size_of::()); + let reply: rt_msghdr = reply.into(); + if !(reply.rtm_version == query_version + && reply.rtm_pid == pid + && reply.rtm_seq == query_seq) + { + continue; + } + if reply.rtm_type != query_type { + return Err(default_err()); + } + + // This is a reply to our query. + // This is the reply we are looking for. + // Some BSDs let us get the interface index and MTU directly from the reply. + let mtu = (reply.rtm_rmx.rmx_mtu != 0) + .then(|| usize::try_from(reply.rtm_rmx.rmx_mtu)) + .transpose() + .map_err(|e: TryFromIntError| unlikely_err(e.to_string()))?; + if reply.rtm_index != 0 { + // Some BSDs return the interface index directly. + return Ok((reply.rtm_index, mtu)); + } + // For others, we need to extract it from the sockaddrs. + for i in 0..RTAX_MAX { + if (reply.rtm_addrs & (1 << i)) == 0 { + continue; + } + let saddr = unsafe { ptr::read_unaligned(sa.as_ptr().cast::()) }; + if saddr.sa_family != AF_LINK { + (_, sa) = sa.split_at(sockaddr_len(saddr.sa_family)?); + continue; + } + let sdl = unsafe { ptr::read_unaligned(sa.as_ptr().cast::()) }; + return Ok((sdl.sdl_index, mtu)); + } + } +} + +pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> { + let (if_index, mtu1) = if_index_mtu(remote)?; + let (if_name, mtu2) = if_name_mtu(if_index.into())?; + Ok((if_name, mtu1.or(mtu2).ok_or_else(default_err)?)) +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod test { + use super::*; + + #[test] + fn sockaddr_len_valid_and_invalid() { + assert!(sockaddr_len(AF_INET).is_ok()); + assert!(sockaddr_len(AF_INET6).is_ok()); + assert!(sockaddr_len(AddressFamily::MAX).is_err()); + } +} diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/src/lib.rs b/external/opennow/native/opennow-streamer/vendor/mtu/src/lib.rs new file mode 100644 index 000000000..87f341fed --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/src/lib.rs @@ -0,0 +1,243 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(coverage_nightly, feature(coverage_attribute))] + +//! A crate to return the name and maximum transmission unit (MTU) of the local network interface +//! towards a given destination `SocketAddr`, optionally from a given local `SocketAddr`. +//! +//! # Usage +//! +//! This crate exports a single function `interface_and_mtu` that returns the name and +//! [maximum transmission unit (MTU)](https://en.wikipedia.org/wiki/Maximum_transmission_unit) +//! of the outgoing network interface towards a remote destination identified by an `IpAddr`. +//! +//! # Example +//! +//! ``` +//! # use std::net::{IpAddr, Ipv4Addr}; +//! let destination = IpAddr::V4(Ipv4Addr::LOCALHOST); +//! let (name, mtu): (String, usize) = mtu::interface_and_mtu(destination).unwrap(); +//! println!("MTU towards {destination} is {mtu} on {name}"); +//! ``` +//! +//! # Supported Platforms +//! +//! * Linux +//! * Android +//! * macOS +//! * Windows +//! * FreeBSD +//! * NetBSD +//! * OpenBSD +//! * Solaris +//! +//! # Notes +//! +//! The returned MTU may exceed the maximum IP packet size of 65,535 bytes on some platforms for +//! some remote destinations. (For example, loopback destinations on Windows.) +//! +//! The returned interface name is obtained from the operating system. +//! +//! # Contributing +//! +//! We're happy to receive PRs that improve this crate. Please take a look at our [community +//! guidelines](CODE_OF_CONDUCT.md) beforehand. + +use std::{ + io::{Error, ErrorKind, Result}, + net::IpAddr, +}; + +#[cfg(not(target_os = "windows"))] +macro_rules! asserted_const_with_type { + ($name:ident, $t1:ty, $e:expr, $t2:ty) => { + #[allow( + clippy::allow_attributes, + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "Guarded by the following `const_assert_eq!`." + )] + const $name: $t1 = $e as $t1; + const_assert_eq!($name as $t2, $e); + }; +} + +#[cfg(any(target_os = "macos", bsd))] +mod bsd; + +#[cfg(any(target_os = "linux", target_os = "android"))] +mod linux; + +#[cfg(target_os = "windows")] +mod windows; + +#[cfg(not(target_os = "windows"))] +mod routesocket; + +#[cfg(any(target_os = "macos", bsd))] +use bsd::interface_and_mtu_impl; +#[cfg(any(target_os = "linux", target_os = "android"))] +use linux::interface_and_mtu_impl; +#[cfg(target_os = "windows")] +use windows::interface_and_mtu_impl; + +/// Prepare a default error. +fn default_err() -> Error { + Error::new(ErrorKind::NotFound, "Local interface MTU not found") +} + +/// Prepare an error for cases that "should never happen". +#[cfg(not(target_os = "windows"))] +fn unlikely_err(msg: String) -> Error { + debug_assert!(false, "{msg}"); + Error::other(msg) +} + +/// Align `size` to the next multiple of `align` (which needs to be a power of two). +#[cfg(not(target_os = "windows"))] +const fn aligned_by(size: usize, align: usize) -> usize { + if size == 0 { + align + } else { + 1 + ((size - 1) | (align - 1)) + } +} + +// Platforms currently not supported. +// +// See . +#[cfg(any(target_os = "ios", target_os = "tvos", target_os = "visionos"))] +pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> { + return Err(default_err()); +} + +/// Return the name and maximum transmission unit (MTU) of the outgoing network interface towards a +/// remote destination identified by an [`IpAddr`], +/// +/// The returned MTU may exceed the maximum IP packet size of 65,535 bytes on some platforms for +/// some remote destinations. (For example, loopback destinations on Windows.) +/// +/// The returned interface name is obtained from the operating system. +/// +/// # Errors +/// +/// This function returns an error if the local interface MTU cannot be determined. +pub fn interface_and_mtu(remote: IpAddr) -> Result<(String, usize)> { + interface_and_mtu_impl(remote) +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod test { + #![expect(clippy::unwrap_used, reason = "OK in tests.")] + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + + use crate::interface_and_mtu; + + #[derive(Debug)] + struct NameMtu<'a>(Option<&'a str>, usize); + + impl PartialEq> for (String, usize) { + fn eq(&self, other: &NameMtu<'_>) -> bool { + other.0.map_or(true, |name| name == self.0) && other.1 == self.1 + } + } + + const LOOPBACK: [NameMtu; 2] = // [IPv4, IPv6] + if cfg!(any(target_os = "macos", target_os = "freebsd")) { + [NameMtu(Some("lo0"), 16_384), NameMtu(Some("lo0"), 16_384)] + } else if cfg!(any(target_os = "linux", target_os = "android")) { + [NameMtu(Some("lo"), 65_536), NameMtu(Some("lo"), 65_536)] + } else if cfg!(target_os = "windows") { + [ + NameMtu(Some("loopback_0"), 4_294_967_295), + NameMtu(Some("loopback_0"), 4_294_967_295), + ] + } else if cfg!(target_os = "openbsd") { + [NameMtu(Some("lo0"), 32_768), NameMtu(Some("lo0"), 32_768)] + } else if cfg!(target_os = "netbsd") { + [NameMtu(Some("lo0"), 33_624), NameMtu(Some("lo0"), 33_624)] + } else if cfg!(target_os = "solaris") { + // Note: Different loopback MTUs for IPv4 and IPv6?! + [NameMtu(Some("lo0"), 8_232), NameMtu(Some("lo0"), 8_252)] + } else { + unreachable!(); + }; + + // Non-loopback interface names are unpredictable, so we only check the MTU. + const INET: NameMtu = NameMtu(None, 1_500); + + #[test] + fn loopback_v4() { + assert_eq!( + interface_and_mtu(IpAddr::V4(Ipv4Addr::LOCALHOST)).unwrap(), + LOOPBACK[0] + ); + } + + #[test] + fn loopback_v6() { + assert_eq!( + interface_and_mtu(IpAddr::V6(Ipv6Addr::LOCALHOST)).unwrap(), + LOOPBACK[1] + ); + } + + #[test] + fn inet_v4() { + assert_eq!( + interface_and_mtu(IpAddr::V4(Ipv4Addr::new( + 104, 16, 132, 229 // cloudflare.com + ))) + .unwrap(), + INET + ); + } + + #[test] + #[cfg(not(target_os = "windows"))] + fn aligned_by() { + for (size, align, expected) in [ + (0, 8, 8), + (1, 8, 8), + (7, 8, 8), + (8, 8, 8), + (9, 8, 16), + (17, 8, 24), + ] { + assert_eq!(crate::aligned_by(size, align), expected); + } + } + + #[test] + fn inet_v6() { + let res = interface_and_mtu(IpAddr::V6(Ipv6Addr::new( + 0x2606, 0x4700, 0, 0, 0, 0, 0x6810, 0x84e5, // cloudflare.com + ))); + match res { + Ok(res) => assert_eq!(res, INET), + Err(e) => { + #[cfg(not(target_os = "windows"))] + let no_ipv6 = matches!(e.raw_os_error(), Some(libc::ENETUNREACH | libc::ESRCH)); + #[cfg(target_os = "windows")] + let no_ipv6 = e.raw_os_error() + == Some( + windows::Win32::Foundation::ERROR_NETWORK_UNREACHABLE + .0 + .try_into() + .unwrap(), + ); + if no_ipv6 { + eprintln!("skipping IPv6 test due to lack of IPv6 connectivity: {e}"); + } else { + panic!("unexpected error on IPv6 interface_and_mtu lookup: {e}"); + } + } + } + } +} diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/src/linux.rs b/external/opennow/native/opennow-streamer/vendor/mtu/src/linux.rs new file mode 100644 index 000000000..a775ab102 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/src/linux.rs @@ -0,0 +1,425 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::{ + ffi::CStr, + io::{Error, Read as _, Result, Write as _}, + net::IpAddr, + num::TryFromIntError, + ptr, slice, +}; + +use libc::{ + c_int, AF_NETLINK, ARPHRD_NONE, IFLA_IFNAME, IFLA_MTU, NETLINK_ROUTE, RTA_DST, RTA_OIF, + RTM_GETLINK, RTM_GETROUTE, RTM_NEWLINK, RTM_NEWROUTE, RTN_UNICAST, RT_SCOPE_UNIVERSE, + RT_TABLE_MAIN, +}; +use static_assertions::{const_assert, const_assert_eq}; + +use crate::{aligned_by, default_err, routesocket::RouteSocket, unlikely_err}; + +#[allow( + clippy::allow_attributes, + clippy::allow_attributes_without_reason, + clippy::struct_field_names, + non_camel_case_types, + clippy::too_many_lines, + reason = "Bindgen-generated code" +)] +mod bindings { + include!(env!("BINDINGS")); +} + +use bindings::{ifinfomsg, nlmsghdr, rtattr, rtmsg}; + +asserted_const_with_type!(AF_INET, u8, libc::AF_INET, i32); +asserted_const_with_type!(AF_INET6, u8, libc::AF_INET6, i32); +asserted_const_with_type!(AF_UNSPEC, u8, libc::AF_UNSPEC, i32); +asserted_const_with_type!(NLM_F_REQUEST, u16, libc::NLM_F_REQUEST, c_int); +asserted_const_with_type!(NLM_F_ACK, u16, libc::NLM_F_ACK, c_int); +asserted_const_with_type!(NLMSG_ERROR, u16, libc::NLMSG_ERROR, c_int); + +const_assert!(size_of::() <= u8::MAX as usize); +const_assert!(size_of::() <= u8::MAX as usize); +const_assert!(size_of::() <= u8::MAX as usize); +const_assert!(size_of::() <= u8::MAX as usize); + +const NETLINK_BUFFER_SIZE: usize = 8192; // See netlink(7) man page. + +#[repr(C)] +enum AddrBytes { + V4([u8; 4]), + V6([u8; 16]), +} + +impl AddrBytes { + const fn new(ip: IpAddr) -> Self { + match ip { + IpAddr::V4(ip) => Self::V4(ip.octets()), + IpAddr::V6(ip) => Self::V6(ip.octets()), + } + } + + const fn len(&self) -> usize { + match self { + Self::V4(_) => 4, + Self::V6(_) => 16, + } + } +} + +impl From for [u8; 16] { + fn from(addr: AddrBytes) -> Self { + match addr { + AddrBytes::V4(bytes) => { + let mut v6 = [0; 16]; + v6[..4].copy_from_slice(&bytes); + v6 + } + AddrBytes::V6(bytes) => bytes, + } + } +} + +#[repr(C)] +#[derive(Default)] +struct IfIndexMsg { + nlmsg: nlmsghdr, + rtm: rtmsg, + rt: rtattr, + addr: [u8; 16], +} + +impl IfIndexMsg { + fn new(remote: IpAddr, nlmsg_seq: u32) -> Self { + let addr = AddrBytes::new(remote); + #[expect( + clippy::cast_possible_truncation, + reason = "Structs lens are <= u8::MAX per `const_assert!`s above; `addr_bytes` is max. 16 for IPv6." + )] + let nlmsg_len = + (size_of::() + size_of::() + size_of::() + addr.len()) as u32; + Self { + nlmsg: nlmsghdr { + nlmsg_len, + nlmsg_type: RTM_GETROUTE, + nlmsg_flags: NLM_F_REQUEST | NLM_F_ACK, + nlmsg_seq, + ..Default::default() + }, + rtm: rtmsg { + rtm_family: match remote { + IpAddr::V4(_) => AF_INET, + IpAddr::V6(_) => AF_INET6, + }, + rtm_dst_len: match remote { + IpAddr::V4(_) => 32, + IpAddr::V6(_) => 128, + }, + rtm_table: RT_TABLE_MAIN, + rtm_scope: RT_SCOPE_UNIVERSE, + rtm_type: RTN_UNICAST, + ..Default::default() + }, + rt: rtattr { + #[expect( + clippy::cast_possible_truncation, + reason = "Structs len is <= u8::MAX per `const_assert!` above; `addr_bytes` is max. 16 for IPv6." + )] + rta_len: (size_of::() + addr.len()) as u16, + rta_type: RTA_DST, + }, + addr: addr.into(), + } + } + + const fn len(&self) -> usize { + let len = self.nlmsg.nlmsg_len as usize; + debug_assert!(len <= size_of::()); + len + } +} + +impl From<&IfIndexMsg> for &[u8] { + fn from(value: &IfIndexMsg) -> Self { + unsafe { slice::from_raw_parts(ptr::from_ref(value).cast(), value.len()) } + } +} + +impl TryFrom<&[u8]> for nlmsghdr { + type Error = Error; + + fn try_from(value: &[u8]) -> Result { + if value.len() < size_of::() { + return Err(default_err()); + } + Ok(unsafe { ptr::read_unaligned(value.as_ptr().cast()) }) + } +} + +fn parse_c_int(buf: &[u8]) -> Result { + if buf.len() < size_of::() { + return Err(default_err()); + } + let bytes = <&[u8] as TryInto<[u8; size_of::()]>>::try_into(&buf[..size_of::()]) + .map_err(|_| default_err())?; + Ok(c_int::from_ne_bytes(bytes)) +} + +fn read_msg_with_seq(fd: &mut RouteSocket, seq: u32, kind: u16) -> Result<(nlmsghdr, Vec)> { + loop { + let buf = &mut [0u8; NETLINK_BUFFER_SIZE]; + let len = fd.read(buf.as_mut_slice())?; + let mut next = &buf[..len]; + while size_of::() <= next.len() { + let (hdr, mut msg) = next.split_at(size_of::()); + let hdr: nlmsghdr = hdr.try_into()?; + // `msg` has the remainder of this message plus any following messages. + // Strip those it off and assign them to `next`. + debug_assert!(size_of::() <= hdr.nlmsg_len as usize); + (msg, next) = msg.split_at(hdr.nlmsg_len as usize - size_of::()); + + if hdr.nlmsg_seq != seq { + continue; + } + + if hdr.nlmsg_type == NLMSG_ERROR { + // Extract the error code and return it. + let err = parse_c_int(msg)?; + if err != 0 { + return Err(Error::from_raw_os_error(-err)); + } + } else if hdr.nlmsg_type == kind { + // Return the header and the message. + return Ok((hdr, msg.to_vec())); + } + } + } +} + +impl TryFrom<&[u8]> for rtattr { + type Error = Error; + + fn try_from(value: &[u8]) -> Result { + if value.len() < size_of::() { + return Err(default_err()); + } + Ok(unsafe { ptr::read_unaligned(value.as_ptr().cast()) }) + } +} + +struct RtAttr<'a> { + hdr: rtattr, + msg: &'a [u8], +} + +impl<'a> RtAttr<'a> { + fn new(bytes: &'a [u8]) -> Result { + debug_assert!(bytes.len() >= size_of::()); + let (hdr, mut msg) = bytes.split_at(size_of::()); + let hdr: rtattr = hdr.try_into()?; + let aligned_len = aligned_by(hdr.rta_len.into(), 4); + debug_assert!(size_of::() <= aligned_len); + (msg, _) = msg.split_at(aligned_len - size_of::()); + Ok(Self { hdr, msg }) + } +} + +struct RtAttrs<'a>(&'a [u8]); + +impl<'a> Iterator for RtAttrs<'a> { + type Item = RtAttr<'a>; + + fn next(&mut self) -> Option { + if size_of::() <= self.0.len() { + let attr = RtAttr::new(self.0).ok()?; + let aligned_len = aligned_by(attr.hdr.rta_len.into(), 4); + debug_assert!(self.0.len() >= aligned_len); + self.0 = self.0.split_at(aligned_len).1; + Some(attr) + } else { + None + } + } +} + +fn if_index(remote: IpAddr, fd: &mut RouteSocket) -> Result { + // Send RTM_GETROUTE message to get the interface index associated with the destination. + let msg_seq = RouteSocket::new_seq(); + let msg = IfIndexMsg::new(remote, msg_seq); + fd.write_all((&msg).into())?; + + // Receive RTM_GETROUTE response. + let (_hdr, mut buf) = read_msg_with_seq(fd, msg_seq, RTM_NEWROUTE)?; + debug_assert!(size_of::() <= buf.len()); + let buf = buf.split_off(size_of::()); + + // Parse through the attributes to find the interface index. + for attr in RtAttrs(buf.as_slice()).by_ref() { + if attr.hdr.rta_type == RTA_OIF { + // We have our interface index. + return parse_c_int(attr.msg); + } + } + Err(default_err()) +} + +#[repr(C)] +struct IfInfoMsg { + nlmsg: nlmsghdr, + ifim: ifinfomsg, +} + +impl IfInfoMsg { + fn new(if_index: i32, nlmsg_seq: u32) -> Self { + #[expect( + clippy::cast_possible_truncation, + reason = "Structs lens are <= u8::MAX per `const_assert!`s above." + )] + let nlmsg_len = (size_of::() + size_of::()) as u32; + Self { + nlmsg: nlmsghdr { + nlmsg_len, + nlmsg_type: RTM_GETLINK, + nlmsg_flags: NLM_F_REQUEST | NLM_F_ACK, + nlmsg_seq, + ..Default::default() + }, + ifim: ifinfomsg { + ifi_family: AF_UNSPEC, + ifi_type: ARPHRD_NONE, + ifi_index: if_index, + ..Default::default() + }, + } + } + + const fn len(&self) -> usize { + self.nlmsg.nlmsg_len as usize + } +} + +impl From<&IfInfoMsg> for &[u8] { + fn from(value: &IfInfoMsg) -> Self { + debug_assert!(value.len() >= size_of::()); + unsafe { slice::from_raw_parts(ptr::from_ref(value).cast(), value.len()) } + } +} + +fn if_name_mtu(if_index: i32, fd: &mut RouteSocket) -> Result<(String, usize)> { + // Send RTM_GETLINK message to get interface information for the given interface index. + let msg_seq = RouteSocket::new_seq(); + let msg = IfInfoMsg::new(if_index, msg_seq); + fd.write_all((&msg).into())?; + + // Receive RTM_GETLINK response. + let (_hdr, mut buf) = read_msg_with_seq(fd, msg_seq, RTM_NEWLINK)?; + debug_assert!(size_of::() <= buf.len()); + let buf = buf.split_off(size_of::()); + + // Parse through the attributes to find the interface name and MTU. + let mut ifname = None; + let mut mtu = None; + for attr in RtAttrs(buf.as_slice()).by_ref() { + match attr.hdr.rta_type { + IFLA_IFNAME => { + let name = CStr::from_bytes_until_nul(attr.msg).map_err(Error::other)?; + ifname = Some(name.to_str().map_err(Error::other)?.to_string()); + } + IFLA_MTU => { + mtu = Some( + parse_c_int(attr.msg)? + .try_into() + .map_err(|e: TryFromIntError| unlikely_err(e.to_string()))?, + ); + } + _ => (), + } + if let (Some(ifname), Some(mtu)) = (ifname.as_ref(), mtu.as_ref()) { + return Ok((ifname.clone(), *mtu)); + } + } + + Err(default_err()) +} + +pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> { + // Create a netlink socket. + let mut fd = RouteSocket::new(AF_NETLINK, NETLINK_ROUTE)?; + let if_index = if_index(remote, &mut fd)?; + if_name_mtu(if_index, &mut fd) +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod test { + use std::net::{Ipv4Addr, Ipv6Addr}; + + use super::*; + + #[test] + fn nlmsghdr_try_from() { + assert!(nlmsghdr::try_from([0u8; 4].as_slice()).is_err()); + let mut buf = [0u8; 32]; + buf[0..4].copy_from_slice(&20u32.to_ne_bytes()); + assert_eq!(nlmsghdr::try_from(buf.as_slice()).unwrap().nlmsg_len, 20); + } + + #[test] + fn rtattr_try_from() { + assert!(rtattr::try_from([0u8; 2].as_slice()).is_err()); + let mut buf = [0u8; 8]; + buf[0..2].copy_from_slice(&8u16.to_ne_bytes()); + buf[2..4].copy_from_slice(&3u16.to_ne_bytes()); + let attr = rtattr::try_from(buf.as_slice()).unwrap(); + assert_eq!((attr.rta_len, attr.rta_type), (8, 3)); + } + + #[test] + fn rtattrs_iteration() { + assert_eq!(RtAttrs(&[]).count(), 0); + assert_eq!(RtAttrs(&[0u8; 2]).count(), 0); + + let mut buf = [0u8; 16]; + for (offset, rta_type) in [(0, 1u16), (8, 2u16)] { + buf[offset..offset + 2].copy_from_slice(&8u16.to_ne_bytes()); + buf[offset + 2..offset + 4].copy_from_slice(&rta_type.to_ne_bytes()); + } + let types: Vec<_> = RtAttrs(&buf).map(|a| a.hdr.rta_type).collect(); + assert_eq!(types, [1, 2]); + } + + #[test] + fn addr_bytes() { + assert_eq!(AddrBytes::new(IpAddr::V4(Ipv4Addr::LOCALHOST)).len(), 4); + assert_eq!(AddrBytes::new(IpAddr::V6(Ipv6Addr::LOCALHOST)).len(), 16); + + let v4: [u8; 16] = AddrBytes::new(IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4))).into(); + assert_eq!(v4, [1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + } + + #[test] + fn parse_c_int_valid_and_invalid() { + assert!(parse_c_int(&[0u8; 2]).is_err()); + assert_eq!(parse_c_int(&42i32.to_ne_bytes()).unwrap(), 42); + } + + #[test] + fn if_index_msg_len_and_slice() { + let msg = IfIndexMsg::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1); + assert!(msg.len() > 0); + let slice: &[u8] = (&msg).into(); + assert_eq!(slice.len(), msg.len()); + } + + #[test] + fn if_info_msg_len_and_slice() { + let msg = IfInfoMsg::new(1, 1); + assert!(msg.len() > 0); + let slice: &[u8] = (&msg).into(); + assert_eq!(slice.len(), msg.len()); + } +} diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/src/routesocket.rs b/external/opennow/native/opennow-streamer/vendor/mtu/src/routesocket.rs new file mode 100644 index 000000000..ae1c68884 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/src/routesocket.rs @@ -0,0 +1,95 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::{ + io::{Error, Read, Result, Write}, + num::TryFromIntError, + os::fd::{AsRawFd, FromRawFd as _, OwnedFd}, + sync::atomic::Ordering, +}; + +use libc::{fsync, read, socket, write, SOCK_RAW}; + +use crate::unlikely_err; + +#[cfg(any(target_os = "linux", target_os = "android"))] +type AtomicRouteSocketSeq = std::sync::atomic::AtomicU32; +#[cfg(any(target_os = "linux", target_os = "android"))] +type RouteSocketSeq = u32; + +#[cfg(not(any(target_os = "linux", target_os = "android")))] +type AtomicRouteSocketSeq = std::sync::atomic::AtomicI32; +#[cfg(not(any(target_os = "linux", target_os = "android")))] +type RouteSocketSeq = i32; + +static SEQ: AtomicRouteSocketSeq = AtomicRouteSocketSeq::new(0); + +pub struct RouteSocket(OwnedFd); + +impl RouteSocket { + pub fn new(domain: libc::c_int, protocol: libc::c_int) -> Result { + let fd = unsafe { socket(domain, SOCK_RAW, protocol) }; + if fd == -1 { + return Err(Error::last_os_error()); + } + Ok(Self(unsafe { OwnedFd::from_raw_fd(fd) })) + } + + pub fn new_seq() -> RouteSocketSeq { + SEQ.fetch_add(1, Ordering::Relaxed) + } +} + +impl AsRawFd for RouteSocket { + fn as_raw_fd(&self) -> i32 { + self.0.as_raw_fd() + } +} + +fn check_result(res: isize) -> Result { + if res == -1 { + Err(Error::last_os_error()) + } else { + Ok(res + .try_into() + .map_err(|e: TryFromIntError| unlikely_err(e.to_string()))?) + } +} + +impl Write for RouteSocket { + fn write(&mut self, buf: &[u8]) -> Result { + let res = unsafe { write(self.as_raw_fd(), buf.as_ptr().cast(), buf.len()) }; + check_result(res) + } + + fn flush(&mut self) -> Result<()> { + let res = unsafe { fsync(self.as_raw_fd()) }; + check_result(res as isize).and(Ok(())) + } +} + +impl Read for RouteSocket { + fn read(&mut self, buf: &mut [u8]) -> Result { + // If we've written a well-formed message into the kernel via `write`, we should be able to + // read a well-formed message back out, and not block. + let res = unsafe { read(self.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; + check_result(res) + } +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod test { + #![expect(clippy::unwrap_used, reason = "OK in tests.")] + use super::*; + + #[test] + fn check_result_error_and_success() { + assert!(check_result(-1).is_err()); + assert_eq!(check_result(0).unwrap(), 0); + assert_eq!(check_result(42).unwrap(), 42); + } +} diff --git a/external/opennow/native/opennow-streamer/vendor/mtu/src/windows.rs b/external/opennow/native/opennow-streamer/vendor/mtu/src/windows.rs new file mode 100644 index 000000000..8e1d48438 --- /dev/null +++ b/external/opennow/native/opennow-streamer/vendor/mtu/src/windows.rs @@ -0,0 +1,145 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::{ + ffi::CStr, + io::{Error, Result}, + net::IpAddr, + ptr, slice, +}; + +use windows::Win32::{ + NetworkManagement::{ + IpHelper::{ + if_indextoname, FreeMibTable, GetBestInterfaceEx, GetIpInterfaceTable, + MIB_IPINTERFACE_ROW, MIB_IPINTERFACE_TABLE, + }, + Ndis::IF_MAX_STRING_SIZE, + }, + Networking::WinSock::{ + AF_INET, AF_INET6, IN6_ADDR, IN6_ADDR_0, IN_ADDR, IN_ADDR_0, SOCKADDR, SOCKADDR_IN, + SOCKADDR_IN6, SOCKADDR_INET, + }, +}; + +use crate::default_err; + +struct MibTablePtr(*mut MIB_IPINTERFACE_TABLE); + +impl MibTablePtr { + fn mut_ptr_ptr(&mut self) -> *mut *mut MIB_IPINTERFACE_TABLE { + ptr::from_mut(&mut self.0) + } +} + +impl Default for MibTablePtr { + fn default() -> Self { + Self(ptr::null_mut()) + } +} + +impl Drop for MibTablePtr { + fn drop(&mut self) { + if !self.0.is_null() { + // Free the memory allocated by GetIpInterfaceTable. + unsafe { + FreeMibTable(self.0.cast()); + } + } + } +} + +pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> { + // Convert remote to Windows SOCKADDR_INET format. The SOCKADDR_INET union contains an IPv4 or + // an IPv6 address. + // + // See https://learn.microsoft.com/en-us/windows/win32/api/ws2ipdef/ns-ws2ipdef-sockaddr_inet + let dst = match remote { + IpAddr::V4(ip) => { + // Initialize the `SOCKADDR_IN` variant of `SOCKADDR_INET` based on `ip`. + SOCKADDR_INET { + Ipv4: SOCKADDR_IN { + sin_family: AF_INET, + sin_addr: IN_ADDR { + S_un: IN_ADDR_0 { + S_addr: u32::to_be(ip.into()), + }, + }, + ..Default::default() + }, + } + } + IpAddr::V6(ip) => { + // Initialize the `SOCKADDR_IN6` variant of `SOCKADDR_INET` based on `ip`. + SOCKADDR_INET { + Ipv6: SOCKADDR_IN6 { + sin6_family: AF_INET6, + sin6_addr: IN6_ADDR { + u: IN6_ADDR_0 { Byte: ip.octets() }, + }, + ..Default::default() + }, + } + } + }; + + // Get the interface index of the best outbound interface towards `dst`. + let mut idx = 0; + let res = unsafe { + // We're now casting `&dst` to a `SOCKADDR` pointer. This is OK based on + // https://learn.microsoft.com/en-us/windows/win32/winsock/sockaddr-2. + // With that, we call `GetBestInterfaceEx` to get the interface index into `idx`. + // See https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getbestinterfaceex + GetBestInterfaceEx( + ptr::from_ref(&dst).cast::(), + ptr::from_mut(&mut idx), + ) + }; + if res != 0 { + return Err(Error::from_raw_os_error(res.try_into().unwrap_or(i32::MAX))); + } + + // Get a list of all interfaces with associated metadata. + let mut if_table = MibTablePtr::default(); + // GetIpInterfaceTable allocates memory, which MibTablePtr::drop will free. + let family = if remote.is_ipv4() { AF_INET } else { AF_INET6 }; + let res = unsafe { GetIpInterfaceTable(family, if_table.mut_ptr_ptr()) }; + if res.is_err() { + return Err(Error::from_raw_os_error( + res.0.try_into().unwrap_or(i32::MAX), + )); + } + // Make a slice + let ifaces = unsafe { + slice::from_raw_parts::( + &(*if_table.0).Table[0], + (*if_table.0).NumEntries as usize, + ) + }; + + // Find the local interface matching `idx`. + for iface in ifaces { + if iface.InterfaceIndex == idx { + // Get the MTU. + let mtu: usize = iface.NlMtu.try_into().map_err(|_| default_err())?; + // Get the interface name. + let mut interfacename = [0u8; IF_MAX_STRING_SIZE as usize]; + // if_indextoname writes into the provided buffer. + if unsafe { if_indextoname(iface.InterfaceIndex, &mut interfacename).is_null() } { + return Err(default_err()); + } + // Convert the interface name to a Rust string. + let name = CStr::from_bytes_until_nul(interfacename.as_ref()) + .map_err(|_| default_err())? + .to_str() + .map_err(Error::other)? + .to_string(); + // We found our interface information. + return Ok((name, mtu)); + } + } + Err(default_err()) +}