From a454544fc46b6e89148cc4ce9cb60cb5f8b000ec Mon Sep 17 00:00:00 2001 From: deddroid Date: Wed, 21 Oct 2026 19:38:10 +0200 Subject: [PATCH] Vendor the FCM client without OpenSSL and rodio (RustCrypto web push decryption, rustls) to fix the Windows build Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +- .github/workflows/release.yml | 2 +- CHANGELOG.md | 2 + Cargo.lock | 682 +----------- Cargo.toml | 5 +- README.it.md | 4 +- README.md | 4 +- THIRD-PARTY-LICENSES.md | 968 ++---------------- packaging/aur/bticino-easykit-bin/PKGBUILD | 2 +- packaging/aur/bticino-easykit/PKGBUILD | 2 +- vendor/fcm_receiver/.cargo-ok | 1 + vendor/fcm_receiver/.gitignore | 1 + vendor/fcm_receiver/CHANGES.md | 10 + vendor/fcm_receiver/Cargo.toml | 40 + vendor/fcm_receiver/LICENSE-MIT | 21 + vendor/fcm_receiver/README.md | 269 +++++ vendor/fcm_receiver/src/client.rs | 565 ++++++++++ vendor/fcm_receiver/src/consts.rs | 40 + vendor/fcm_receiver/src/crypto.rs | 124 +++ vendor/fcm_receiver/src/ece_backend.rs | 106 ++ vendor/fcm_receiver/src/encryption.rs | 36 + vendor/fcm_receiver/src/error.rs | 82 ++ vendor/fcm_receiver/src/http_client.rs | 379 +++++++ vendor/fcm_receiver/src/lib.rs | 17 + vendor/fcm_receiver/src/messages/builders.rs | 121 +++ vendor/fcm_receiver/src/messages/marshal.rs | 457 +++++++++ vendor/fcm_receiver/src/messages/mod.rs | 9 + vendor/fcm_receiver/src/messages/types.rs | 309 ++++++ vendor/fcm_receiver/src/messages/unmarshal.rs | 514 ++++++++++ vendor/fcm_receiver/src/proto.rs | 321 ++++++ vendor/fcm_receiver/src/socket_handler.rs | 253 +++++ vendor/fcm_receiver/src/util.rs | 179 ++++ 32 files changed, 3976 insertions(+), 1553 deletions(-) create mode 100644 vendor/fcm_receiver/.cargo-ok create mode 100644 vendor/fcm_receiver/.gitignore create mode 100644 vendor/fcm_receiver/CHANGES.md create mode 100644 vendor/fcm_receiver/Cargo.toml create mode 100644 vendor/fcm_receiver/LICENSE-MIT create mode 100644 vendor/fcm_receiver/README.md create mode 100644 vendor/fcm_receiver/src/client.rs create mode 100644 vendor/fcm_receiver/src/consts.rs create mode 100644 vendor/fcm_receiver/src/crypto.rs create mode 100644 vendor/fcm_receiver/src/ece_backend.rs create mode 100644 vendor/fcm_receiver/src/encryption.rs create mode 100644 vendor/fcm_receiver/src/error.rs create mode 100644 vendor/fcm_receiver/src/http_client.rs create mode 100644 vendor/fcm_receiver/src/lib.rs create mode 100644 vendor/fcm_receiver/src/messages/builders.rs create mode 100644 vendor/fcm_receiver/src/messages/marshal.rs create mode 100644 vendor/fcm_receiver/src/messages/mod.rs create mode 100644 vendor/fcm_receiver/src/messages/types.rs create mode 100644 vendor/fcm_receiver/src/messages/unmarshal.rs create mode 100644 vendor/fcm_receiver/src/proto.rs create mode 100644 vendor/fcm_receiver/src/socket_handler.rs create mode 100644 vendor/fcm_receiver/src/util.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 17dcc38..429ba92 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,12 +23,12 @@ jobs: - uses: Swatinem/rust-cache@v2 - name: Linux build dependencies if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y libasound2-dev libssl-dev pkg-config + run: sudo apt-get update && sudo apt-get install -y libasound2-dev pkg-config - name: Build run: cargo build --locked --all-targets - name: Clippy run: cargo clippy --locked --all-targets -- -D warnings - name: Test - run: cargo test --locked + run: cargo test --locked --workspace - name: CLI only (no GUI) run: cargo clippy --locked --all-targets --no-default-features -- -D warnings diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fa6bc54..3d7990a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: - uses: Swatinem/rust-cache@v2 - name: Linux build dependencies if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y libasound2-dev libssl-dev pkg-config + run: sudo apt-get update && sudo apt-get install -y libasound2-dev pkg-config - name: Build shell: bash # Hide the checkout and the cargo registry paths from the binaries. diff --git a/CHANGELOG.md b/CHANGELOG.md index 412dd1e..3f8aece 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,3 +17,5 @@ All notable changes to this project are documented here. The format follows - CLI: `login`, `list`, `status`, `events`, `open`, `light`, `live`, `listen`, `test-session`. - Protocol notes in `docs/PROTOCOL.md`. +- FCM client vendored from fcm_receiver_rs without OpenSSL and audio playback + (pure-Rust web push decryption), so Windows builds need no OpenSSL. diff --git a/Cargo.lock b/Cargo.lock index e0eae44..ab80429 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "ab_glyph" @@ -301,12 +301,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - [[package]] name = "arboard" version = "3.7.0" @@ -455,18 +449,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "async-compression" -version = "0.4.51" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970" -dependencies = [ - "compression-codecs", - "compression-core", - "pin-project-lite", - "tokio", -] - [[package]] name = "async-executor" version = "1.14.0" @@ -652,12 +634,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" -[[package]] -name = "base64" -version = "0.21.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" - [[package]] name = "base64" version = "0.22.1" @@ -774,7 +750,7 @@ dependencies = [ "log", "notify-rust", "openh264", - "reqwest 0.12.28", + "reqwest", "rpassword", "rtc", "serde", @@ -787,7 +763,7 @@ dependencies = [ "unsafe-libopus", "webrtc", "windows-sys 0.61.2", - "winreg 0.56.0", + "winreg", "winresource", ] @@ -1100,23 +1076,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "compression-codecs" -version = "0.4.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe" -dependencies = [ - "compression-core", - "flate2", - "memchr", -] - -[[package]] -name = "compression-core" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" - [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1173,7 +1132,7 @@ dependencies = [ "bitflags 1.3.2", "core-foundation 0.9.4", "core-graphics-types", - "foreign-types 0.5.0", + "foreign-types", "libc", ] @@ -1188,12 +1147,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - [[package]] name = "coreaudio-rs" version = "0.13.0" @@ -1595,12 +1548,7 @@ dependencies = [ "base64 0.22.1", "byteorder", "hex", - "hkdf", - "lazy_static", "once_cell", - "openssl", - "serde", - "sha2", "thiserror 2.0.21", ] @@ -1662,7 +1610,7 @@ dependencies = [ "bitflags 2.13.2", "emath", "epaint", - "itertools 0.15.0", + "itertools", "log", "nohash-hasher", "profiling", @@ -1781,20 +1729,6 @@ dependencies = [ "bytemuck", ] -[[package]] -name = "encoding_rs" -version = "0.8.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - [[package]] name = "endi" version = "1.1.1" @@ -1928,12 +1862,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "extended" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" - [[package]] name = "fastrand" version = "2.5.0" @@ -1948,36 +1876,26 @@ checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" [[package]] name = "fcm_receiver_rs" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae876d191a628e4581039961db3d4503698ccfafeb2f9c9428ce33bf7e1ad17e" +version = "0.1.1+easykit.1" dependencies = [ "aes-gcm", - "anyhow", "base64 0.22.1", "bytes", "ece", - "getrandom 0.2.17", - "hex", "hkdf", "hmac", "log", - "native-tls", "p256", - "parking_lot", - "prost", - "prost-types", "rand 0.8.8", "regex", - "reqwest 0.11.27", - "rodio", + "reqwest", + "rustls", "serde", "serde_json", "sha2", - "simplelog", "thiserror 1.0.69", - "time", "url", + "webpki-roots", ] [[package]] @@ -2038,12 +1956,6 @@ dependencies = [ "zlib-rs", ] -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - [[package]] name = "foldhash" version = "0.1.5" @@ -2087,15 +1999,6 @@ dependencies = [ "yeslogic-fontconfig-sys", ] -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared 0.1.1", -] - [[package]] name = "foreign-types" version = "0.5.0" @@ -2103,7 +2006,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" dependencies = [ "foreign-types-macros", - "foreign-types-shared 0.3.1", + "foreign-types-shared", ] [[package]] @@ -2117,12 +2020,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "foreign-types-shared" version = "0.3.1" @@ -2649,25 +2546,6 @@ dependencies = [ "euclid", ] -[[package]] -name = "h2" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "half" version = "2.7.1" @@ -2763,17 +2641,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.5.0" @@ -2784,17 +2651,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.1.0" @@ -2802,7 +2658,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http", ] [[package]] @@ -2813,8 +2669,8 @@ checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", ] @@ -2824,12 +2680,6 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - [[package]] name = "hybrid-array" version = "0.4.15" @@ -2839,30 +2689,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "hyper" -version = "0.14.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2 0.5.10", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.12.0" @@ -2872,8 +2698,8 @@ dependencies = [ "atomic-waker", "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", "itoa", "pin-project-lite", @@ -2888,8 +2714,8 @@ version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ - "http 1.5.0", - "hyper 1.12.0", + "http", + "hyper", "hyper-util", "rustls", "tokio", @@ -2898,19 +2724,6 @@ dependencies = [ "webpki-roots", ] -[[package]] -name = "hyper-tls" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" -dependencies = [ - "bytes", - "hyper 0.14.32", - "native-tls", - "tokio", - "tokio-native-tls", -] - [[package]] name = "hyper-util" version = "0.1.21" @@ -2921,15 +2734,15 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", - "hyper 1.12.0", + "hyper", "ipnet", "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.5", + "socket2", "tokio", "tower-service", "tracing", @@ -3086,15 +2899,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" -[[package]] -name = "itertools" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.15.0" @@ -3478,12 +3282,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3551,12 +3349,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - [[package]] name = "munge" version = "0.4.7" @@ -3624,23 +3416,6 @@ dependencies = [ "log", ] -[[package]] -name = "native-tls" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - [[package]] name = "ndk" version = "0.9.0" @@ -3768,17 +3543,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-rational" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" -dependencies = [ - "num-bigint", - "num-integer", - "num-traits", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -3811,15 +3575,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "num_threads" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" -dependencies = [ - "libc", -] - [[package]] name = "objc-sys" version = "0.3.5" @@ -4236,49 +3991,12 @@ dependencies = [ "walkdir", ] -[[package]] -name = "openssl" -version = "0.10.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" -dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "foreign-types 0.3.2", - "libc", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "openssl-probe" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "openssl-sys" -version = "0.9.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - [[package]] name = "option-ext" version = "0.2.0" @@ -4758,38 +4476,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" -[[package]] -name = "prost" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" -dependencies = [ - "bytes", - "prost-derive", -] - -[[package]] -name = "prost-derive" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" -dependencies = [ - "anyhow", - "itertools 0.12.1", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "prost-types" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0" -dependencies = [ - "prost", -] - [[package]] name = "ptr_meta" version = "0.3.2" @@ -4844,7 +4530,7 @@ dependencies = [ "quinn-udp 0.5.16", "rustc-hash 2.1.3", "rustls", - "socket2 0.6.5", + "socket2", "thiserror 2.0.21", "tokio", "tracing", @@ -4882,7 +4568,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.5", + "socket2", "tracing", "windows-sys 0.61.2", ] @@ -4896,7 +4582,7 @@ dependencies = [ "cfg_aliases", "libc", "log", - "socket2 0.6.5", + "socket2", "windows-sys 0.61.2", ] @@ -5127,48 +4813,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" -[[package]] -name = "reqwest" -version = "0.11.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" -dependencies = [ - "async-compression", - "base64 0.21.7", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "h2", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.32", - "hyper-tls", - "ipnet", - "js-sys", - "log", - "mime", - "native-tls", - "once_cell", - "percent-encoding", - "pin-project-lite", - "rustls-pemfile", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper 0.1.2", - "system-configuration", - "tokio", - "tokio-native-tls", - "tokio-util", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "winreg 0.50.0", -] - [[package]] name = "reqwest" version = "0.12.28" @@ -5180,10 +4824,10 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", - "hyper 1.12.0", + "hyper", "hyper-rustls", "hyper-util", "js-sys", @@ -5196,7 +4840,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tokio-rustls", "tower", @@ -5263,18 +4907,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "rodio" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e40ecf59e742e03336be6a3d53755e789fd05a059fa22dfa0ed624722319e183" -dependencies = [ - "cpal", - "dasp_sample", - "num-rational", - "symphonia", -] - [[package]] name = "roxmltree" version = "0.21.1" @@ -5426,7 +5058,7 @@ dependencies = [ "log", "rtc-shared", "sansio", - "socket2 0.6.5", + "socket2", ] [[package]] @@ -5647,15 +5279,6 @@ dependencies = [ "security-framework", ] -[[package]] -name = "rustls-pemfile" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" -dependencies = [ - "base64 0.21.7", -] - [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -5967,17 +5590,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" -[[package]] -name = "simplelog" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16257adbfaef1ee58b1363bdc0664c9b8e1e30aed86049635fb5f147d065a9c0" -dependencies = [ - "log", - "termcolor", - "time", -] - [[package]] name = "siphasher" version = "1.0.4" @@ -6087,16 +5699,6 @@ dependencies = [ "serde", ] -[[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.5" @@ -6165,153 +5767,6 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "symphonia" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" -dependencies = [ - "lazy_static", - "symphonia-bundle-flac", - "symphonia-bundle-mp3", - "symphonia-codec-aac", - "symphonia-codec-pcm", - "symphonia-codec-vorbis", - "symphonia-core", - "symphonia-format-isomp4", - "symphonia-format-ogg", - "symphonia-format-riff", - "symphonia-metadata", -] - -[[package]] -name = "symphonia-bundle-flac" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" -dependencies = [ - "log", - "symphonia-core", - "symphonia-metadata", - "symphonia-utils-xiph", -] - -[[package]] -name = "symphonia-bundle-mp3" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" -dependencies = [ - "lazy_static", - "log", - "symphonia-core", - "symphonia-metadata", -] - -[[package]] -name = "symphonia-codec-aac" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790" -dependencies = [ - "lazy_static", - "log", - "symphonia-core", -] - -[[package]] -name = "symphonia-codec-pcm" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" -dependencies = [ - "log", - "symphonia-core", -] - -[[package]] -name = "symphonia-codec-vorbis" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" -dependencies = [ - "log", - "symphonia-core", - "symphonia-utils-xiph", -] - -[[package]] -name = "symphonia-core" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" -dependencies = [ - "arrayvec", - "bitflags 1.3.2", - "bytemuck", - "lazy_static", - "log", -] - -[[package]] -name = "symphonia-format-isomp4" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5" -dependencies = [ - "encoding_rs", - "log", - "symphonia-core", - "symphonia-metadata", - "symphonia-utils-xiph", -] - -[[package]] -name = "symphonia-format-ogg" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" -dependencies = [ - "log", - "symphonia-core", - "symphonia-metadata", - "symphonia-utils-xiph", -] - -[[package]] -name = "symphonia-format-riff" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f" -dependencies = [ - "extended", - "log", - "symphonia-core", - "symphonia-metadata", -] - -[[package]] -name = "symphonia-metadata" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" -dependencies = [ - "encoding_rs", - "lazy_static", - "log", - "symphonia-core", -] - -[[package]] -name = "symphonia-utils-xiph" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" -dependencies = [ - "symphonia-core", - "symphonia-metadata", -] - [[package]] name = "syn" version = "1.0.109" @@ -6344,12 +5799,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "sync_wrapper" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" - [[package]] name = "sync_wrapper" version = "1.0.2" @@ -6390,27 +5839,6 @@ dependencies = [ "libc", ] -[[package]] -name = "system-configuration" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "system-deps" version = "6.2.2" @@ -6524,9 +5952,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "libc", "num-conv", - "num_threads", "powerfmt", "serde_core", "time-core", @@ -6601,7 +6027,7 @@ dependencies = [ "mio", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.5", + "socket2", "tokio-macros", "tracing", "windows-sys 0.61.2", @@ -6618,16 +6044,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.6" @@ -6654,20 +6070,6 @@ dependencies = [ "tungstenite", ] -[[package]] -name = "tokio-util" -version = "0.7.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "libc", - "pin-project-lite", - "tokio", -] - [[package]] name = "toml" version = "0.8.2" @@ -6773,7 +6175,7 @@ dependencies = [ "futures-core", "futures-util", "pin-project-lite", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tower-layer", "tower-service", @@ -6788,8 +6190,8 @@ dependencies = [ "bitflags 2.13.2", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", "tower", "tower-layer", @@ -6893,7 +6295,7 @@ checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" dependencies = [ "bytes", "data-encoding", - "http 1.5.0", + "http", "httparse", "log", "rand 0.10.3", @@ -7034,12 +6436,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - [[package]] name = "vello_common" version = "0.2.0" @@ -8040,16 +7436,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "winreg" -version = "0.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" -dependencies = [ - "cfg-if", - "windows-sys 0.48.0", -] - [[package]] name = "winreg" version = "0.56.0" diff --git a/Cargo.toml b/Cargo.toml index a3b9154..436b8ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,9 @@ readme = "README.md" keywords = ["bticino", "netatmo", "intercom", "doorbell", "easykit"] categories = ["command-line-utilities"] +[workspace] +members = [".", "vendor/fcm_receiver"] + [lib] name = "bticino_easykit" path = "src/lib.rs" @@ -32,7 +35,7 @@ cpal = { version = "0.16", optional = true } dirs = "5" eframe = { version = "0.37", optional = true } env_logger = "0.11" -fcm_receiver_rs = "0.1.1" +fcm_receiver_rs = { path = "vendor/fcm_receiver" } futures-util = "0.3" image = { version = "0.25", default-features = false, features = ["png", "jpeg"], optional = true } log = "0.4" diff --git a/README.it.md b/README.it.md index fb74c20..3574187 100644 --- a/README.it.md +++ b/README.it.md @@ -89,7 +89,7 @@ cargo build --release # GUI + CLI cargo build --release --no-default-features # solo CLI ``` -Su Linux servono `alsa-lib` (`libasound2-dev`), `openssl` e `pkg-config`. +Su Linux servono `alsa-lib` (`libasound2-dev`) e `pkg-config`. ## Uso @@ -143,7 +143,7 @@ Il funzionamento è documentato in [docs/PROTOCOL.md](docs/PROTOCOL.md) (in ingl [bticino_intercom](https://github.com/k-the-hidden-hero/bticino_intercom) di k-the-hidden-hero e contributori: le basi su API, push e signaling. - [pyatmo](https://github.com/jabesq-org/pyatmo): tipi di modulo Netatmo. -- [fcm_receiver.rs](https://github.com/agusibrahim/fcm_receiver.rs) e +- [fcm_receiver.rs](https://github.com/agusibrahim/fcm_receiver.rs) (incluso e ridotto in `vendor/fcm_receiver`) e [firebase-messaging](https://github.com/sdb9696/firebase-messaging): client FCM. - [webrtc-rs](https://github.com/webrtc-rs/webrtc), [egui](https://github.com/emilk/egui), [openh264](https://github.com/ralfbiedert/openh264-rs), diff --git a/README.md b/README.md index 914545d..b1004dc 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ cargo build --release # GUI + CLI cargo build --release --no-default-features # CLI only ``` -Linux needs `alsa-lib` (`libasound2-dev`), `openssl` and `pkg-config`. +Linux needs `alsa-lib` (`libasound2-dev`) and `pkg-config`. ## Usage @@ -142,7 +142,7 @@ How everything works is documented in [docs/PROTOCOL.md](docs/PROTOCOL.md). [bticino_intercom](https://github.com/k-the-hidden-hero/bticino_intercom) by k-the-hidden-hero and contributors: API, push and signaling groundwork. - [pyatmo](https://github.com/jabesq-org/pyatmo): Netatmo module types. -- [fcm_receiver.rs](https://github.com/agusibrahim/fcm_receiver.rs) and +- [fcm_receiver.rs](https://github.com/agusibrahim/fcm_receiver.rs) (vendored and trimmed in `vendor/fcm_receiver`) and [firebase-messaging](https://github.com/sdb9696/firebase-messaging): FCM client. - [webrtc-rs](https://github.com/webrtc-rs/webrtc), [egui](https://github.com/emilk/egui), [openh264](https://github.com/ralfbiedert/openh264-rs), diff --git a/THIRD-PARTY-LICENSES.md b/THIRD-PARTY-LICENSES.md index 55caef6..8b4e717 100644 --- a/THIRD-PARTY-LICENSES.md +++ b/THIRD-PARTY-LICENSES.md @@ -3,14 +3,14 @@ `bticino-easykit` binaries include the following Rust crates. Their licenses and copyright notices are reproduced below. -- MIT License (548 crates) -- Apache License 2.0 (26 crates) +- MIT License (514 crates) +- Apache License 2.0 (21 crates) - BSD 2-Clause "Simplified" License (20 crates) - ISC License (20 crates) - Unicode License v3 (19 crates) -- Mozilla Public License 2.0 (14 crates) -- BSD 3-Clause "New" or "Revised" License (6 crates) +- BSD 3-Clause "New" or "Revised" License (4 crates) - Boost Software License 1.0 (2 crates) +- Mozilla Public License 2.0 (2 crates) - zlib License (2 crates) - Community Data License Agreement Permissive 2.0 (1 crates) - SIL Open Font License 1.1 (1 crates) @@ -933,221 +933,8 @@ Used by: ## Apache License 2.0 -Used by: -- [openssl 0.10.81](https://github.com/rust-openssl/rust-openssl) - -``` - 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. - - -``` - -## Apache License 2.0 - Used by: - [gethostname 1.1.0](https://codeberg.org/swsnr/gethostname.rs.git) -- [prost-derive 0.12.6](https://github.com/tokio-rs/prost) -- [prost-types 0.12.6](https://github.com/tokio-rs/prost) - [ring 0.17.14](https://github.com/briansmith/ring) ``` @@ -1782,12 +1569,10 @@ Used by: - [ab_glyph_rasterizer 0.1.10](https://github.com/alexheretic/ab-glyph) - [accesskit_winit 0.34.1](https://github.com/AccessKit/accesskit) - [owned_ttf_parser 0.25.1](https://github.com/alexheretic/owned-ttf-parser) -- [prost 0.12.6](https://github.com/tokio-rs/prost) - [rpassword 7.5.4](https://github.com/conradkleinespel/rpassword) - [rtoolbox 0.0.6](https://github.com/conradkleinespel/rtoolbox) - [ryu 1.0.23](https://github.com/dtolnay/ryu) - [spirv 0.4.0+sdk-1.4.341.0](https://github.com/gfx-rs/rspirv) -- [sync_wrapper 0.1.2](https://github.com/Actyx/sync_wrapper) - [sync_wrapper 1.0.2](https://github.com/Actyx/sync_wrapper) ``` @@ -3231,69 +3016,6 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS& ## BSD 3-Clause "New" or "Revised" License -Used by: -- [encoding_rs 0.8.42](https://github.com/hsivonen/encoding_rs) - -``` -// Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/// The PUA code points special-cased in the GB18030 encoder. -pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [ - 0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826, - 0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864, -]; - -/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder. -pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [ - [0xA6, 0xD9], - [0xA6, 0xDA], - [0xA6, 0xDB], - [0xA6, 0xDC], - [0xA6, 0xDD], - [0xA6, 0xDE], - [0xA6, 0xDF], - [0xA6, 0xEC], - [0xA6, 0xED], - [0xA6, 0xF3], - [0xFE, 0x59], - [0xFE, 0x61], - [0xFE, 0x66], - [0xFE, 0x67], - [0xFE, 0x6D], - [0xFE, 0x7E], - [0xFE, 0x90], - [0xFE, 0xA0], -]; - -``` - -## BSD 3-Clause "New" or "Revised" License - Used by: - [tiny-skia-path 0.11.4](https://github.com/RazrFalcon/tiny-skia/tree/master/path) - [tiny-skia 0.11.4](https://github.com/RazrFalcon/tiny-skia) @@ -3422,41 +3144,6 @@ Broadcom Corporation: https://datatracker.ietf.org/ipr/1526/ ``` -## BSD 3-Clause "New" or "Revised" License - -Used by: -- [encoding_rs 0.8.42](https://github.com/hsivonen/encoding_rs) - -``` -Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -``` - ## Boost Software License 1.0 Used by: @@ -4444,9 +4131,7 @@ DEALINGS IN THE SOFTWARE. Used by: - [cfg-if 1.0.5](https://github.com/rust-lang/cfg-if) - [openssl-probe 0.2.1](https://github.com/rustls/openssl-probe) -- [openssl-sys 0.9.117](https://github.com/rust-openssl/rust-openssl) - [scoped-tls 1.0.1](https://github.com/alexcrichton/scoped-tls) -- [socket2 0.5.10](https://github.com/rust-lang/socket2) - [socket2 0.6.5](https://github.com/rust-lang/socket2) - [toml_datetime 0.6.3](https://github.com/toml-rs/toml) @@ -4544,50 +4229,21 @@ DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [mime 0.3.17](https://github.com/hyperium/mime) +- [base64ct 1.8.3](https://github.com/RustCrypto/formats) ``` -Copyright (c) 2014 Sean McArthur +Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) +Copyright (c) 2021-2025 The RustCrypto Project Developers -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. - - -``` - -## MIT License - -Used by: -- [base64ct 1.8.3](https://github.com/RustCrypto/formats) - -``` -Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) -Copyright (c) 2021-2025 The RustCrypto Project Developers - -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: +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 @@ -4649,7 +4305,6 @@ Used by: - [num-bigint 0.4.8](https://github.com/rust-num/num-bigint) - [num-complex 0.4.6](https://github.com/rust-num/num-complex) - [num-integer 0.1.47](https://github.com/rust-num/num-integer) -- [num-rational 0.4.2](https://github.com/rust-num/num-rational) - [num-traits 0.2.19](https://github.com/rust-num/num-traits) - [regex-automata 0.4.18](https://github.com/rust-lang/regex) - [regex-syntax 0.8.11](https://github.com/rust-lang/regex) @@ -4751,34 +4406,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## MIT License -Used by: -- [hyper 0.14.32](https://github.com/hyperium/hyper) - -``` -Copyright (c) 2014-2021 Sean McArthur - -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. - -``` - -## MIT License - Used by: - [flate2 1.1.10](https://github.com/rust-lang/flate2-rs) @@ -4872,7 +4499,6 @@ THE SOFTWARE. Used by: - [either 1.19.0](https://github.com/rayon-rs/either) -- [itertools 0.12.1](https://github.com/rust-itertools/itertools) - [itertools 0.15.0](https://github.com/rust-itertools/itertools) - [petgraph 0.8.3](https://github.com/petgraph/petgraph) @@ -4945,7 +4571,6 @@ THE SOFTWARE. ## MIT License Used by: -- [winreg 0.50.0](https://github.com/gentoo90/winreg-rs) - [winreg 0.56.0](https://github.com/gentoo90/winreg-rs) ``` @@ -5466,7 +5091,6 @@ DEALINGS IN THE SOFTWARE. Used by: - [hyper-rustls 0.27.10](https://github.com/rustls/hyper-rustls) - [rustls-native-certs 0.8.5](https://github.com/rustls/rustls-native-certs) -- [rustls-pemfile 1.0.4](https://github.com/rustls/pemfile) - [rustls 0.23.46](https://github.com/rustls/rustls) ``` @@ -5512,63 +5136,6 @@ The above copyright notice and this permission notice shall be included in all c 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. -``` - -## MIT License - -Used by: -- [httpdate 1.0.3](https://github.com/pyfisch/httpdate) - -``` -Copyright (c) 2016 Pyfisch - -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. - -``` - -## MIT License - -Used by: -- [reqwest 0.11.27](https://github.com/seanmonstar/reqwest) - -``` -Copyright (c) 2016 Sean McArthur - -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. - - ``` ## MIT License @@ -5609,34 +5176,6 @@ DEALINGS IN THE SOFTWARE. ## MIT License -Used by: -- [native-tls 0.2.18](https://github.com/rust-native-tls/rust-native-tls) - -``` -Copyright (c) 2016 The rust-native-tls Developers - -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. - -``` - -## MIT License - Used by: - [indexmap 2.14.2](https://github.com/indexmap-rs/indexmap) @@ -5903,40 +5442,6 @@ DEALINGS IN THE SOFTWARE. ## MIT License -Used by: -- [fnv 1.0.7](https://github.com/servo/rust-fnv) - -``` -Copyright (c) 2017 Contributors - -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. - -``` - -## MIT License - Used by: - [tokio-tungstenite 0.30.0](https://github.com/snapview/tokio-tungstenite) @@ -6072,157 +5577,32 @@ Used by: ``` Copyright (c) 2017 Pyfisch -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. -``` - -## MIT License - -Used by: -- [stable_deref_trait 1.2.1](https://github.com/storyyeller/stable_deref_trait) - -``` -Copyright (c) 2017 Robert Grosse - -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. -``` - -## MIT License - -Used by: -- [hyper-tls 0.5.0](https://github.com/hyperium/hyper-tls) - -``` -Copyright (c) 2017 Sean McArthur - -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. - - -``` - -## MIT License - -Used by: -- [foreign-types-shared 0.1.1](https://github.com/sfackler/foreign-types) -- [foreign-types 0.3.2](https://github.com/sfackler/foreign-types) - -``` -Copyright (c) 2017 The foreign-types Developers - -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. - -``` - -## MIT License - -Used by: -- [arc-swap 1.9.3](https://github.com/vorner/arc-swap) - -``` -Copyright (c) 2017 arc-swap developers - -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. +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. ``` ## MIT License Used by: -- [h2 0.3.27](https://github.com/hyperium/h2) +- [stable_deref_trait 1.2.1](https://github.com/storyyeller/stable_deref_trait) ``` -Copyright (c) 2017 h2 authors +Copyright (c) 2017 Robert Grosse Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -6247,17 +5627,15 @@ 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. - ``` ## MIT License Used by: -- [http 0.2.12](https://github.com/hyperium/http) -- [http 1.5.0](https://github.com/hyperium/http) +- [arc-swap 1.9.3](https://github.com/vorner/arc-swap) ``` -Copyright (c) 2017 http-rs authors +Copyright (c) 2017 arc-swap developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -6288,10 +5666,10 @@ DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [tokio-rustls 0.26.6](https://github.com/rustls/tokio-rustls) +- [http 1.5.0](https://github.com/hyperium/http) ``` -Copyright (c) 2017 quininer kel +Copyright (c) 2017 http-rs authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -6322,10 +5700,10 @@ DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [signal-hook-registry 1.4.8](https://github.com/vorner/signal-hook) +- [tokio-rustls 0.26.6](https://github.com/rustls/tokio-rustls) ``` -Copyright (c) 2017 tokio-jsonrpc developers +Copyright (c) 2017 quininer kel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -6356,10 +5734,10 @@ DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [core_detect 1.0.0](https://github.com/thomcc/core_detect) +- [signal-hook-registry 1.4.8](https://github.com/vorner/signal-hook) ``` -Copyright (c) 2017-2020 The Rust Project Developers +Copyright (c) 2017 tokio-jsonrpc developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -7335,40 +6713,6 @@ DEALINGS IN THE SOFTWARE. ## MIT License -Used by: -- [http-body 0.4.6](https://github.com/hyperium/http-body) - -``` -Copyright (c) 2019 Hyper Contributors - -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. - -``` - -## MIT License - Used by: - [wl-clipboard-rs 0.9.4](https://github.com/YaLTeR/wl-clipboard-rs) @@ -7541,7 +6885,6 @@ DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [tokio-native-tls 0.3.1](https://github.com/tokio-rs/tls) - [tracing-attributes 0.1.31](https://github.com/tokio-rs/tracing) - [tracing-core 0.1.36](https://github.com/tokio-rs/tracing) - [tracing 0.1.44](https://github.com/tokio-rs/tracing) @@ -8190,34 +7533,6 @@ DEALINGS IN THE SOFTWARE. ## MIT License -Used by: -- [num_threads 0.1.8](https://github.com/jhpratt/num_threads) - -``` -Copyright (c) 2021 Jacob Pratt - -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. - -``` - -## MIT License - Used by: - [crypto-common 0.1.6](https://github.com/RustCrypto/traits) @@ -8438,34 +7753,6 @@ DEALINGS IN THE SOFTWARE. ## MIT License -Used by: -- [openssl-macros 0.1.1](https://crates.io/crates/openssl-macros) - -``` -Copyright (c) 2022 Steven Fackler - -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. - -``` - -## MIT License - Used by: - [atspi-common 0.13.0](https://github.com/odilia-app/atspi) - [atspi-proxies 0.13.0](https://github.com/odilia-app/atspi) @@ -9417,34 +8704,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES ## MIT License -Used by: -- [extended 0.1.0](https://github.com/depp/extended-rs) - -``` -Copyright 2022 Dietrich Epp - -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. - -``` - -## MIT License - Used by: - [bytecheck 0.8.3](https://github.com/rkyv/bytecheck) - [rancor 0.1.3](https://github.com/rkyv/rancor) @@ -9584,8 +8843,6 @@ DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [encoding_rs 0.8.42](https://github.com/hsivonen/encoding_rs) -- [multiversion_no_op 1.0.0](https://github.com/hsivonen/multiversion_no_op) - [utf8_iter 1.0.4](https://github.com/hsivonen/utf8_iter) ``` @@ -10497,7 +9754,6 @@ Used by: - [egui_system_font_provider 0.37.0](https://github.com/emilk/egui/tree/main/crates/egui_system_font_provider) - [emath 0.37.0](https://github.com/emilk/egui/tree/main/crates/emath) - [epaint 0.37.0](https://github.com/emilk/egui/tree/main/crates/epaint) -- [fcm_receiver_rs 0.1.1](https://github.com/agusibrahim/fcm_receiver.rs) - [libappindicator-sys 0.9.0](https://crates.io/crates/libappindicator-sys) - [libm 0.2.16](https://github.com/rust-lang/compiler-builtins) - [profiling 1.0.18](https://github.com/aclysma/profiling) @@ -10570,7 +9826,37 @@ USE OR OTHER DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [tokio-util 0.7.20](https://github.com/tokio-rs/tokio) +- [bticino-easykit 0.1.0](https://github.com/deddroid/bticino-easykit) +- [fcm_receiver_rs 0.1.1+easykit.1](https://crates.io/crates/fcm_receiver_rs) + +``` +MIT License + +Copyright (c) Agus Ibrahim + +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. + +``` + +## MIT License + +Used by: - [tokio 1.54.0](https://github.com/tokio-rs/tokio) ``` @@ -10920,7 +10206,6 @@ DEALINGS IN THE SOFTWARE. Used by: - [adler2 2.0.1](https://github.com/oyvindln/adler2) -- [anyhow 1.0.104](https://github.com/dtolnay/anyhow) - [async-channel 2.5.0](https://github.com/smol-rs/async-channel) - [async-executor 1.14.0](https://github.com/smol-rs/async-executor) - [async-io 2.6.0](https://github.com/smol-rs/async-io) @@ -10957,7 +10242,6 @@ Used by: - [proc-macro-crate 3.5.0](https://github.com/bkchr/proc-macro-crate) - [proc-macro2 1.0.107](https://github.com/dtolnay/proc-macro2) - [quote 1.0.47](https://github.com/dtolnay/quote) -- [rodio 0.21.1](https://github.com/RustAudio/rodio) - [rustc-hash 1.1.0](https://github.com/rust-lang-nursery/rustc-hash) - [rustix 0.38.44](https://github.com/bytecodealliance/rustix) - [rustix 1.1.5](https://github.com/bytecodealliance/rustix) @@ -11267,7 +10551,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## MIT License Used by: -- [base64 0.21.7](https://github.com/marshallpierce/rust-base64) - [base64 0.22.1](https://github.com/marshallpierce/rust-base64) ``` @@ -11304,7 +10587,6 @@ Used by: - [jiff-core 0.1.1](https://github.com/BurntSushi/jiff) - [jiff 0.2.38](https://github.com/BurntSushi/jiff) - [memchr 2.8.3](https://github.com/BurntSushi/memchr) -- [termcolor 1.4.1](https://github.com/BurntSushi/termcolor) ``` The MIT License (MIT) @@ -11395,36 +10677,6 @@ SOFTWARE. ## MIT License -Used by: -- [simplelog 0.12.2](https://github.com/drakulix/simplelog.rs) - -``` -The MIT License (MIT) - -Copyright (c) 2015 Victor Brekenfeld - -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. - -``` - -## MIT License - Used by: - [data-encoding 2.11.1](https://github.com/ia0/data-encoding) @@ -11523,36 +10775,6 @@ SOFTWARE. ## MIT License -Used by: -- [winapi-util 0.1.11](https://github.com/BurntSushi/winapi-util) - -``` -The MIT License (MIT) - -Copyright (c) 2017 Andrew Gallant - -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. - -``` - -## MIT License - Used by: - [ff 0.13.1](https://github.com/zkcrypto/ff) @@ -11583,38 +10805,6 @@ THE SOFTWARE. ## MIT License -Used by: -- [async-compression 0.4.51](https://github.com/Nullus157/async-compression) -- [compression-codecs 0.4.46](https://github.com/Nullus157/async-compression) -- [compression-core 0.4.34](https://github.com/Nullus157/async-compression) - -``` -The MIT License (MIT) - -Copyright (c) 2018 the rustasync developers - -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. - -``` - -## MIT License - Used by: - [guillotiere 0.7.0](https://github.com/nical/guillotiere) @@ -12310,18 +11500,6 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice Used by: - [option-ext 0.2.0](https://github.com/soc/option-ext.git) -- [symphonia-bundle-flac 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-bundle-mp3 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-codec-aac 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-codec-pcm 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-codec-vorbis 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-core 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-format-isomp4 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-format-ogg 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-format-riff 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-metadata 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia-utils-xiph 0.5.5](https://github.com/pdeljanov/Symphonia) -- [symphonia 0.5.5](https://github.com/pdeljanov/Symphonia) ``` Mozilla Public License Version 2.0 diff --git a/packaging/aur/bticino-easykit-bin/PKGBUILD b/packaging/aur/bticino-easykit-bin/PKGBUILD index 6e7bd63..13cd618 100644 --- a/packaging/aur/bticino-easykit-bin/PKGBUILD +++ b/packaging/aur/bticino-easykit-bin/PKGBUILD @@ -7,7 +7,7 @@ pkgdesc="Unofficial client for the BTicino EASYKIT WiFi video door entry kit (pr arch=('x86_64') url="https://github.com/deddroid/bticino-easykit" license=('MIT') -depends=('alsa-lib' 'gcc-libs' 'glibc' 'hicolor-icon-theme' 'openssl') +depends=('alsa-lib' 'gcc-libs' 'glibc' 'hicolor-icon-theme') provides=("$_pkgname=$pkgver") conflicts=("$_pkgname") options=('!lto' '!strip') diff --git a/packaging/aur/bticino-easykit/PKGBUILD b/packaging/aur/bticino-easykit/PKGBUILD index a476c11..6df5cf0 100644 --- a/packaging/aur/bticino-easykit/PKGBUILD +++ b/packaging/aur/bticino-easykit/PKGBUILD @@ -6,7 +6,7 @@ pkgdesc="Unofficial client for the BTicino EASYKIT WiFi video door entry kit (li arch=('x86_64' 'aarch64') url="https://github.com/deddroid/bticino-easykit" license=('MIT') -depends=('alsa-lib' 'gcc-libs' 'glibc' 'hicolor-icon-theme' 'openssl') +depends=('alsa-lib' 'gcc-libs' 'glibc' 'hicolor-icon-theme') makedepends=('cargo' 'pkgconf') conflicts=('bticino-easykit-bin') options=('!lto') diff --git a/vendor/fcm_receiver/.cargo-ok b/vendor/fcm_receiver/.cargo-ok new file mode 100644 index 0000000..5f8b795 --- /dev/null +++ b/vendor/fcm_receiver/.cargo-ok @@ -0,0 +1 @@ +{"v":1} \ No newline at end of file diff --git a/vendor/fcm_receiver/.gitignore b/vendor/fcm_receiver/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/vendor/fcm_receiver/.gitignore @@ -0,0 +1 @@ +/target diff --git a/vendor/fcm_receiver/CHANGES.md b/vendor/fcm_receiver/CHANGES.md new file mode 100644 index 0000000..33fbf48 --- /dev/null +++ b/vendor/fcm_receiver/CHANGES.md @@ -0,0 +1,10 @@ +# Changes from upstream fcm_receiver_rs 0.1.1 + +Upstream: https://github.com/agusibrahim/fcm_receiver.rs (MIT OR Apache-2.0), +copyright Agus Ibrahim. Vendored into bticino-easykit and modified: + +- removed the `fun` module and the `rodio` dependency (sound playback); +- MCS socket: `rustls` with webpki roots instead of `native-tls`; +- `ece` without its OpenSSL backend; `src/ece_backend.rs` provides a + RustCrypto backend (validated with `ece::crypto::test_cryptographer`); +- reqwest 0.12 with rustls; unused dependencies dropped. diff --git a/vendor/fcm_receiver/Cargo.toml b/vendor/fcm_receiver/Cargo.toml new file mode 100644 index 0000000..cf5d571 --- /dev/null +++ b/vendor/fcm_receiver/Cargo.toml @@ -0,0 +1,40 @@ +# Vendored and trimmed copy of fcm_receiver_rs 0.1.1 by Agus Ibrahim +# (https://github.com/agusibrahim/fcm_receiver.rs, MIT OR Apache-2.0). +# Changes for bticino-easykit: no rodio/sound module, rustls instead of +# native-tls, `ece` without its OpenSSL backend (a RustCrypto backend is +# registered in `ece_backend.rs`), reqwest 0.12. See CHANGES.md. +[package] +name = "fcm_receiver_rs" +version = "0.1.1+easykit.1" +edition = "2021" +authors = ["Agus Ibrahim"] +description = "Receive Firebase Cloud Messaging notifications as an Android/Chrome client (vendored for bticino-easykit)" +license = "MIT OR Apache-2.0" +publish = false + +[lib] +name = "fcm_receiver_rs" +path = "src/lib.rs" + +[dependencies] +aes-gcm = { version = "0.10", features = ["aes"] } +base64 = "0.22" +bytes = "1" +ece = { version = "2.3", default-features = false } +hkdf = "0.12" +hmac = "0.12" +log = "0.4" +p256 = { version = "0.13", features = ["pkcs8", "ecdh"] } +rand = "0.8" +regex = "1" +reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +thiserror = "1" +url = "2" +webpki-roots = "1" + +[dev-dependencies] +ece = { version = "2.3", default-features = false, features = ["backend-test-helper"] } diff --git a/vendor/fcm_receiver/LICENSE-MIT b/vendor/fcm_receiver/LICENSE-MIT new file mode 100644 index 0000000..32e8a8f --- /dev/null +++ b/vendor/fcm_receiver/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Agus Ibrahim + +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/vendor/fcm_receiver/README.md b/vendor/fcm_receiver/README.md new file mode 100644 index 0000000..9a02138 --- /dev/null +++ b/vendor/fcm_receiver/README.md @@ -0,0 +1,269 @@ +# Rust FCM Receiver + +A Rust library that simulates an Android device to receive Firebase Cloud Messaging (FCM) notifications. This library allows your application to behave like a real device when receiving push notifications from FCM servers. + +## Overview + +This library emulates Android device functionality in the FCM ecosystem, including the ability to: +- Register as a new device and obtain FCM/GCM tokens +- Receive push notifications in real-time +- Subscribe to and unsubscribe from specific topics +- Handle encrypted messages properly + +The FCM/GCM tokens generated can be used to send notifications to this simulated device, just like sending notifications to a real Android device. + +## Features + +- **Device Emulation**: Behaves like a real Android device in the FCM ecosystem +- **Token Generation**: Generates valid FCM and GCM tokens for receiving notifications +- **Topic Management**: Subscribe and unsubscribe from FCM topics like a regular device +- **Real-time Notifications**: Receive push notifications in real-time through persistent connections + +## Manual Protobuf Implementation + +**Important**: This library implements FCM protobuf messages manually without using the `protobuf` library. While FCM communication uses protobuf over socket connections, this library: + +- Manually encodes and decodes protobuf messages +- Does not require protobuf compilation or reflection +- Implements only the necessary FCM message types +- Provides a lightweight alternative to full protobuf dependencies + +This approach keeps the library lightweight and avoids the complexity of protobuf compilation while maintaining full compatibility with FCM protocols. + +## Technical Documentation + +For detailed technical information about the FCM protocol implementation, see [TECHNICAL.md](TECHNICAL.md). + +The TECHNICAL.md document provides: +- End-to-end explanation of building an FCM receiver from scratch +- Detailed protocol flow including device check-in, registration, and MCS connection +- Complete request/response examples for all FCM endpoints +- Manual protobuf implementation details without external dependencies +- Topic subscription/unsubscription implementation based on microg/GmsCore +- Error handling strategies and implementation checklist + +This technical guide is essential for understanding how the library works internally and can help with debugging or extending the functionality. + +## Android Package Configuration (optional) + +For Firebase projects with protection/restrictions, you need to properly configure the Android package information. This is crucial when Firebase is configured to only accept connections from specific Android packages. + +### Package ID and Signature Configuration + +```rust +use fcm_receiver_rs::client::{FcmClient, AndroidApp}; + +fn main() -> Result<()> { + let mut client = FcmClient::new( + "YOUR_API_KEY".to_string(), + "YOUR_APP_ID".to_string(), + "YOUR_PROJECT_ID".to_string(), + )?; + + // Configure Android package information + client.android_app = Some(AndroidApp { + gcm_sender_id: "123456789".to_string(), // Your sender id + android_package: "com.example.app".to_string(), // Your Android package name + android_package_cert: "YOUR_SHA1_SIGNATURE".to_string(), // SHA1 signature of your APK + }); + + // Continue with registration... + Ok(()) +} +``` + +### Generating SHA1 Signature + +For testing purposes, you can use a SHA1 signature from a real APK or generate one: + +```bash +# Get SHA1 from debug keystore (for development) +keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android + +# Or use a known SHA1 from a production app +# Example: "2E:4A:3B:8C:1D:9E:F5:A0:B6:C7:D8:E9:F0:A1:B2:C3:D4:E5:F6" +# Just passing: "2E4A3B8C1D9EF5A0B6C7D8E9F0A1B2C3D4E5F6" +``` + +## Installation + +Add to your `Cargo.toml`: + +```toml +[dependencies] +fcm_receiver_rs = { path = "./fcm_receiver_rs" } +``` + +## Quick Start + +```rust +use fcm_receiver_rs::client::FcmClient; +use fcm_receiver_rs::Result; +use std::sync::Arc; + +fn main() -> Result<()> { + // Initialize FCM client + let mut client = FcmClient::new( + "YOUR_API_KEY".to_string(), + "YOUR_APP_ID".to_string(), + "YOUR_PROJECT_ID".to_string(), + )?; + + // Configure Android package for Firebase compatibility (optional) + client.android_app = Some(fcm_receiver_rs::client::AndroidApp { + gcm_sender_id: "123456789".to_string(), + android_package: "com.example.app".to_string(), + android_package_cert: "YOUR_SHA1_SIGNATURE".to_string(), + }); + + // Set up notification handler + client.on_data_message = Some(Arc::new(|payload| { + let text = String::from_utf8_lossy(&payload); + println!("Received notification: {}", text); + })); + + // Generate encryption keys + let (private_key_b64, auth_secret_b64) = client.create_new_keys()?; + client.load_keys(&private_key_b64, &auth_secret_b64)?; + + // Register as device and get tokens + let (fcm_token, gcm_token, android_id, security_token) = client.register()?; + println!("Registration successful!"); + println!("FCM Token: {}", fcm_token); + println!("GCM Token: {}", gcm_token); + println!("Android ID: {}", android_id); + + // Save tokens for server use + // These tokens can be used in FCM HTTP API v1 + + // Subscribe to topic + client.subscribe_to_topic("promotions")?; + + // Start listening for notifications + client.start_listening()?; + + Ok(()) +} +``` + +## Usage + +### 1. Getting FCM/GCM Tokens + +The generated tokens can be used by servers to send notifications: + +```rust +// Register device +let (fcm_token, gcm_token, android_id, security_token) = client.register()?; + +// FCM Token can be used in FCM HTTP API v1 +// Format: fcm_token can be used directly in FCM endpoints +println!("FCM Token for server: {}", fcm_token); +``` + +### 2. Managing Topics + +Subscribe and unsubscribe from topics like a real Android device: + +```rust +// Subscribe to topics +client.subscribe_to_topic("news")?; +client.subscribe_to_topic("promotions")?; + +// Unsubscribe from topics +client.unsubscribe_from_topic("old_topic")?; +``` + +### 3. Receiving Notifications + +After subscribing to topics, the device will receive notifications sent to those topics: + +```rust +// Handler for decrypted notifications +client.on_data_message = Some(Arc::new(|payload| { + let text = String::from_utf8_lossy(&payload); + println!("Incoming notification: {}", text); +})); + +// Handler for raw messages (for debugging) +client.on_raw_message = Some(Arc::new(|msg| { + println!("Raw message: {:?}", msg); +})); +``` + +## Server Integration + +The generated FCM tokens can be used on servers to send notifications. Example using curl: + +```bash +# Send notification to simulated device +curl -X POST https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send \ + -H "Authorization: Bearer YOUR_SERVER_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "message": { + "token": "FCM_TOKEN_FROM_SIMULATED_DEVICE", + "notification": { + "title": "Test Notification", + "body": "Hello from server!" + }, + "data": { + "custom_data": "value" + } + } + }' +``` + +## Project Reference + +The topic subscription/unsubscription implementation in this library references the [microg/GmsCore](https://github.com/microg/GmsCore) project, which is an open-source implementation of Google Play Services. + +## Complete Example + +See the `example/` directory for a complete implementation that includes: +- Save and load device credentials +- Handle different message types +- Topic subscription +- Error handling + +Run the example: + +```bash +cd example +cargo run +``` + +## Configuration + +### Required Credentials + +- **API Key**: FCM server API key +- **App ID**: Firebase app ID (format: `1:123456789:android:abc123`) +- **Project ID**: Firebase project ID + +### Optional Configuration + +- **Heartbeat Interval**: Heartbeat interval to server (default: 600 seconds) +- **Android App Info**: For Android-specific features and Firebase compatibility + +## Security Notes + +- Private keys and auth secrets should be stored securely +- Use HTTPS for all network communications +- Validate all incoming messages +- Keep API keys confidential +- Use proper SHA1 signatures when mimicking real apps + +## Dependencies + +- `reqwest` - HTTP client +- `serde` - JSON serialization +- `p256` - Elliptic curve cryptography +- `aes-gcm` - AES encryption +- `base64` - Base64 encoding/decoding + +**Note**: This library does NOT use `protobuf` as a dependency. All protobuf messages are implemented manually. + +## License + +This project is licensed under the MIT License. diff --git a/vendor/fcm_receiver/src/client.rs b/vendor/fcm_receiver/src/client.rs new file mode 100644 index 0000000..6ecb60b --- /dev/null +++ b/vendor/fcm_receiver/src/client.rs @@ -0,0 +1,565 @@ +use std::collections::HashSet; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use base64::engine::general_purpose::{STANDARD as BASE64_STANDARD, URL_SAFE, URL_SAFE_NO_PAD}; +use base64::Engine; +use rand::Rng; +use reqwest::blocking::Client as HttpClient; + +use crate::crypto::{create_keys, decode_private_key, encode_private_key, public_key_bytes}; +use crate::encryption::decrypt_message; +use crate::error::{Error, Result}; +use crate::http_client::{ + self, AndroidAppOptions, FcmInstallRequest, FcmRegisterRequest, GcmRegisterRequest, +}; +use crate::messages::{ + create_check_in_request, create_login_request_raw, decode_data_message_stanza, + ManualDataMessageStanza, +}; +use crate::socket_handler::SocketHandler; +use crate::util; + +use p256::{PublicKey, SecretKey}; + +pub struct AndroidApp { + pub gcm_sender_id: String, + pub android_package: String, + pub android_package_cert: String, +} + +pub struct FcmClient { + pub vapid_key: String, + pub api_key: String, + pub app_id: String, + pub project_id: String, + pub gcm_token: Option, + pub fcm_token: Option, + pub android_id: u64, + pub security_token: u64, + pub heartbeat_interval: Duration, + pub on_data_message: Option) + Send + Sync>>, + pub on_raw_message: Option>, + pub android_app: Option, + http_client: HttpClient, + private_key: Option, + public_key: Option, + auth_secret: Option>, + persistent_ids: Arc>>, + installation_auth_token: Option, + socket_handler: Option, +} + +impl FcmClient { + pub fn new(api_key: String, app_id: String, project_id: String) -> Result { + let http_client = http_client::build_default_http_client()?; + Ok(Self { + vapid_key: String::new(), + api_key, + app_id, + project_id, + gcm_token: None, + fcm_token: None, + android_id: 0, + security_token: 0, + heartbeat_interval: Duration::from_secs(600), + on_data_message: None, + on_raw_message: None, + android_app: None, + http_client, + private_key: None, + public_key: None, + auth_secret: None, + persistent_ids: Arc::new(Mutex::new(HashSet::new())), + installation_auth_token: None, + socket_handler: None, + }) + } + + pub fn with_http_client( + api_key: String, + app_id: String, + project_id: String, + http_client: HttpClient, + ) -> Self { + Self { + vapid_key: String::new(), + api_key, + app_id, + project_id, + gcm_token: None, + fcm_token: None, + android_id: 0, + security_token: 0, + heartbeat_interval: Duration::from_secs(600), + on_data_message: None, + on_raw_message: None, + android_app: None, + http_client, + private_key: None, + public_key: None, + auth_secret: None, + persistent_ids: Arc::new(Mutex::new(HashSet::new())), + installation_auth_token: None, + socket_handler: None, + } + } + + pub fn create_new_keys(&mut self) -> Result<(String, String)> { + let (private_key, public_key, auth_secret) = create_keys()?; + let private_key_der = encode_private_key(&private_key)?; + let private_key_b64 = BASE64_STANDARD.encode(private_key_der); + let auth_secret_b64 = BASE64_STANDARD.encode(&auth_secret); + + self.private_key = Some(private_key); + self.public_key = Some(public_key); + self.auth_secret = Some(auth_secret); + + Ok((private_key_b64, auth_secret_b64)) + } + + pub fn load_keys(&mut self, private_key_b64: &str, auth_secret_b64: &str) -> Result<()> { + let private_bytes = BASE64_STANDARD + .decode(private_key_b64) + .map_err(|_| Error::InvalidData("invalid private key encoding"))?; + let private_key = decode_private_key(&private_bytes)?; + let public_key = private_key.public_key(); + let auth_secret = BASE64_STANDARD + .decode(auth_secret_b64) + .map_err(|_| Error::InvalidData("invalid auth secret encoding"))?; + + self.private_key = Some(private_key); + self.public_key = Some(public_key); + self.auth_secret = Some(auth_secret); + + Ok(()) + } + + pub fn register(&mut self) -> Result<(String, String, u64, u64)> { + if self.api_key.is_empty() || self.app_id.is_empty() || self.project_id.is_empty() { + return Err(Error::InvalidData("missing ApiKey/AppId/ProjectId")); + } + + if self.android_id == 0 || self.security_token == 0 { + self.check_in_request_gcm()?; + } + + if self.private_key.is_none() || self.auth_secret.is_none() { + return Err(Error::InvalidData("keys not loaded")); + } + + if self.gcm_token.is_none() && self.android_app.is_none() { + let token = self.register_request_gcm()?; + self.gcm_token = Some(token); + } else if self.gcm_token.is_none() { + let token = self.register_request_gcm()?; + self.fcm_token = Some(token); + } + + let install_token = self.install_request()?; + self.installation_auth_token = Some(install_token); + + if self.android_app.is_none() { + let token = self.register_request()?; + self.fcm_token = Some(token); + } + + let fcm_token = self + .fcm_token + .clone() + .ok_or_else(|| Error::InvalidData("FCM token not available"))?; + let gcm_token = self.gcm_token.clone().unwrap_or_default(); + + Ok((fcm_token, gcm_token, self.android_id, self.security_token)) + } + + fn check_in_request_gcm(&mut self) -> Result<()> { + let request = create_check_in_request(self.android_id as i64, Some(self.security_token)); + let response = http_client::send_gcm_check_in_request(&self.http_client, &request)?; + if let Some(android_id) = response.android_id { + self.android_id = android_id; + } + if let Some(security_token) = response.security_token { + self.security_token = security_token; + } + Ok(()) + } + + fn register_request_gcm(&mut self) -> Result { + let android_app = self.android_app.as_ref().map(|app| AndroidAppOptions { + gcm_sender_id: app.gcm_sender_id.as_str(), + android_package: app.android_package.as_str(), + android_package_cert: app.android_package_cert.as_str(), + }); + + let request = GcmRegisterRequest { + android_id: self.android_id, + security_token: self.security_token, + app_id: self.app_id.as_str(), + android_app, + installation_auth: self.installation_auth_token.as_deref(), + sender_override: None, + subtype_override: None, + delete: false, + extra_params: Vec::new(), + }; + + let token = http_client::send_gcm_register_request(&self.http_client, &request)?; + if self.android_app.is_none() { + self.gcm_token = Some(token.clone()); + } else { + self.fcm_token = Some(token.clone()); + } + Ok(token) + } + + fn install_request(&mut self) -> Result { + let fid = util::generate_firebase_fid()?; + let android_app = self.android_app.as_ref().map(|app| AndroidAppOptions { + gcm_sender_id: app.gcm_sender_id.as_str(), + android_package: app.android_package.as_str(), + android_package_cert: app.android_package_cert.as_str(), + }); + let request = FcmInstallRequest { + api_key: self.api_key.as_str(), + project_id: self.project_id.as_str(), + app_id: self.app_id.as_str(), + fid: fid.as_str(), + android_app, + firebase_client_header: None, + firebase_client_log_type: None, + user_agent: None, + }; + let response = http_client::send_fcm_install_request(&self.http_client, &request)?; + Ok(response.auth_token.token) + } + + fn register_request(&mut self) -> Result { + let public_key = self + .public_key + .as_ref() + .ok_or_else(|| Error::InvalidData("public key missing"))?; + let auth_secret = self + .auth_secret + .as_ref() + .ok_or_else(|| Error::InvalidData("auth secret missing"))?; + let installation_auth = self + .installation_auth_token + .as_ref() + .ok_or_else(|| Error::InvalidData("installation auth missing"))?; + let gcm_token = self + .gcm_token + .as_ref() + .ok_or_else(|| Error::InvalidData("GCM token missing"))?; + + let mut public_key_b64 = URL_SAFE_NO_PAD.encode(public_key_bytes(public_key)); + public_key_b64 = public_key_b64.replace('=', ""); + + let mut auth_secret_b64 = URL_SAFE_NO_PAD.encode(auth_secret); + auth_secret_b64 = auth_secret_b64.replace('=', ""); + + let endpoint = http_client::build_endpoint_url(gcm_token); + + let request = FcmRegisterRequest { + api_key: self.api_key.as_str(), + project_id: self.project_id.as_str(), + installation_auth: installation_auth.as_str(), + vapid_key: self.vapid_key.as_str(), + auth_secret: auth_secret_b64.as_str(), + endpoint: endpoint.as_str(), + p256dh: public_key_b64.as_str(), + }; + + let response = http_client::send_fcm_register_request(&self.http_client, &request)?; + Ok(response.token) + } + + pub fn start_listening(&mut self) -> Result<()> { + if self.android_id == 0 || self.security_token == 0 { + return Err(Error::InvalidData("client's AndroidId and SecurityToken hasn't been set. use FcmClient.register() to generate a new AndroidId and SecurityToken")); + } + + if self.private_key.is_none() || self.auth_secret.is_none() { + return Err(Error::InvalidData("client's private key hasn't been set. use FcmClient.load_keys() or FcmClient.create_new_keys()")); + } + + let persistent_ids: Vec = self + .persistent_ids + .lock() + .unwrap() + .iter() + .cloned() + .collect(); + let login_request = + create_login_request_raw(self.android_id, self.security_token, &persistent_ids)?; + + let mut socket_handler = SocketHandler::new(); + socket_handler.set_heartbeat_interval(self.heartbeat_interval); + + let on_data_message = self.on_data_message.clone(); + let on_raw_message = self.on_raw_message.clone(); + let persistent_ids_clone = self.persistent_ids.clone(); + let auth_secret = self.auth_secret.clone(); + let private_key = self.private_key.clone(); + + socket_handler.set_on_message(move |tag, data| { + Self::handle_message( + tag, + data, + &on_data_message, + &on_raw_message, + &persistent_ids_clone, + &auth_secret, + &private_key, + ) + }); + + socket_handler.connect()?; + socket_handler.send_login_handshake(&login_request)?; + + self.socket_handler = Some(socket_handler); + + if let Some(handler) = self.socket_handler.as_mut() { + handler.start_socket_handler() + } else { + Err(Error::Other( + "Socket handler initialization failed".to_string(), + )) + } + } + + fn handle_message( + tag: u8, + data: Vec, + on_data_message: &Option) + Send + Sync>>, + on_raw_message: &Option>, + persistent_ids: &Arc>>, + auth_secret: &Option>, + private_key: &Option, + ) -> Result<()> { + use crate::consts::*; + + match tag { + K_HEARTBEAT_PING_TAG | K_HEARTBEAT_ACK_TAG | K_LOGIN_RESPONSE_TAG => Ok(()), + K_CLOSE_TAG => Err(Error::Other("server returned close tag".to_string())), + K_IQ_STANZA_TAG => Ok(()), + K_DATA_MESSAGE_STANZA_TAG => { + let message = decode_data_message_stanza(&data)?; + + if let Some(ref persistent_id) = message.persistent_id { + let ttl_duration = message + .ttl + .and_then(|ttl| { + if ttl > 0 { + Some(Duration::from_secs(ttl as u64)) + } else { + None + } + }) + .unwrap_or_else(|| Duration::from_secs(DEFAULT_FCM_MESSAGE_TTL_SECS)); + + let mut ids = persistent_ids.lock().unwrap(); + if ids.contains(persistent_id) { + return Ok(()); + } + ids.insert(persistent_id.clone()); + drop(ids); + + let persistent_id_clone = persistent_id.clone(); + let persistent_ids_clone = Arc::clone(persistent_ids); + std::thread::spawn(move || { + std::thread::sleep(ttl_duration); + if let Ok(mut guard) = persistent_ids_clone.lock() { + guard.remove(&persistent_id_clone); + } + }); + } + + let mut crypto_key_bytes: Option> = None; + let mut encryption_bytes: Option> = None; + let mut is_raw = true; + + for app_data in &message.app_data { + if app_data.key == "crypto-key" { + is_raw = false; + if let Some(dh_part) = app_data + .value + .split(';') + .find(|part| part.starts_with("dh=")) + { + let encoded = dh_part + .get(3..) + .ok_or_else(|| Error::InvalidData("invalid dh parameter"))?; + crypto_key_bytes = Some(Self::decode_base64_url(encoded)?); + } + } else if app_data.key == "encryption" { + if let Some(salt_part) = app_data + .value + .split(';') + .find(|part| part.starts_with("salt=")) + { + let encoded = salt_part + .get(5..) + .ok_or_else(|| Error::InvalidData("invalid salt parameter"))?; + encryption_bytes = Some(Self::decode_base64_url(encoded)?); + } + } + } + + if !is_raw { + if let ( + Some(crypto_key), + Some(encryption), + Some(auth_secret), + Some(private_key), + ) = ( + crypto_key_bytes.as_ref(), + encryption_bytes.as_ref(), + auth_secret.as_ref(), + private_key.as_ref(), + ) { + let decrypted = decrypt_message( + crypto_key, + encryption, + message + .raw_data + .as_deref() + .ok_or_else(|| Error::InvalidData("missing raw data payload"))?, + auth_secret, + private_key, + )?; + + if let Some(callback) = on_data_message { + callback(decrypted); + } + } + } else if let Some(callback) = on_raw_message { + callback(message); + } + + Ok(()) + } + _ => Ok(()), + } + } + + fn decode_base64_url(value: &str) -> Result> { + let mut input = value.to_string(); + while input.len() % 4 != 0 { + input.push('='); + } + + URL_SAFE + .decode(input.as_bytes()) + .map_err(|_| Error::InvalidData("invalid base64 value")) + } + + pub fn close(&mut self) { + if let Some(mut socket_handler) = self.socket_handler.take() { + socket_handler.close(); + } + } + + pub fn remove_persistent_id(&self, id: &str) { + self.persistent_ids.lock().unwrap().remove(id); + } + + pub fn subscribe_to_topic(&self, topic: &str) -> Result<()> { + let normalized = topic.strip_prefix("/topics/").unwrap_or(topic); + http_client::validate_topic_name(normalized)?; + + if self.android_id == 0 || self.security_token == 0 { + return Err(Error::InvalidData( + "client's AndroidId and SecurityToken hasn't been set. use FcmClient.register() first", + )); + } + + let fcm_token = self + .fcm_token + .as_ref() + .ok_or_else(|| Error::InvalidData("FCM token not available"))?; + + let topic_path = format!("/topics/{normalized}"); + + let android_app = self.android_app.as_ref().map(|app| AndroidAppOptions { + gcm_sender_id: app.gcm_sender_id.as_str(), + android_package: app.android_package.as_str(), + android_package_cert: app.android_package_cert.as_str(), + }); + + let extra_params = vec![ + ("X-gcm.topic".to_string(), topic_path.clone()), + ("X-scope".to_string(), topic_path.clone()), + ("X-subscription".to_string(), fcm_token.clone()), + ("X-kid".to_string(), Self::generate_kid()), + ]; + + let request = GcmRegisterRequest { + android_id: self.android_id, + security_token: self.security_token, + app_id: self.app_id.as_str(), + android_app, + installation_auth: self.installation_auth_token.as_deref(), + sender_override: Some(fcm_token.clone()), + subtype_override: Some(fcm_token.clone()), + delete: false, + extra_params, + }; + + http_client::send_gcm_register_request(&self.http_client, &request)?; + Ok(()) + } + + pub fn unsubscribe_from_topic(&self, topic: &str) -> Result<()> { + let normalized = topic.strip_prefix("/topics/").unwrap_or(topic); + http_client::validate_topic_name(normalized)?; + + if self.android_id == 0 || self.security_token == 0 { + return Err(Error::InvalidData( + "client's AndroidId and SecurityToken hasn't been set. use FcmClient.register() first", + )); + } + + let fcm_token = self + .fcm_token + .as_ref() + .ok_or_else(|| Error::InvalidData("FCM token not available"))?; + + let topic_path = format!("/topics/{normalized}"); + + let android_app = self.android_app.as_ref().map(|app| AndroidAppOptions { + gcm_sender_id: app.gcm_sender_id.as_str(), + android_package: app.android_package.as_str(), + android_package_cert: app.android_package_cert.as_str(), + }); + + let extra_params = vec![ + ("X-gcm.topic".to_string(), topic_path.clone()), + ("X-scope".to_string(), topic_path.clone()), + ("X-subscription".to_string(), fcm_token.clone()), + ("X-kid".to_string(), Self::generate_kid()), + ("X-delete".to_string(), "1".to_string()), + ]; + + let request = GcmRegisterRequest { + android_id: self.android_id, + security_token: self.security_token, + app_id: self.app_id.as_str(), + android_app, + installation_auth: self.installation_auth_token.as_deref(), + sender_override: Some(fcm_token.clone()), + subtype_override: Some(fcm_token.clone()), + delete: true, + extra_params, + }; + + http_client::send_gcm_register_request(&self.http_client, &request)?; + Ok(()) + } + + fn generate_kid() -> String { + let mut rng = rand::thread_rng(); + let value: u32 = rng.gen_range(1..1_000_000); + format!("|ID|{}|", value) + } +} diff --git a/vendor/fcm_receiver/src/consts.rs b/vendor/fcm_receiver/src/consts.rs new file mode 100644 index 0000000..37c7679 --- /dev/null +++ b/vendor/fcm_receiver/src/consts.rs @@ -0,0 +1,40 @@ +pub const CHECK_IN_URL: &str = "https://android.clients.google.com/checkin"; +pub const REGISTER_URL: &str = "https://android.clients.google.com/c2dm/register3"; + +pub const FIREBASE_INSTALLATION_URL: &str = "https://firebaseinstallations.googleapis.com/v1/"; +pub const FIREBASE_REGISTRATION_URL: &str = "https://fcmregistrations.googleapis.com/v1/"; +pub const FCM_ENDPOINT_URL: &str = "https://fcm.googleapis.com/fcm/send"; +pub const FCM_SOCKET_ADDRESS: &str = "mtalk.google.com:5228"; + +pub const DEFAULT_FCM_MESSAGE_TTL_SECS: u64 = 60 * 60 * 24 * 28; + +pub const MCS_VERSION_TAG_AND_SIZE: u8 = 0; +pub const MCS_TAG_AND_SIZE: u8 = 1; +pub const MCS_SIZE: u8 = 2; +pub const MCS_PROTO_BYTES: u8 = 3; + +pub const VERSION_PACKET_LEN: usize = 1; +pub const TAG_PACKET_LEN: usize = 1; +pub const SIZE_PACKET_LEN_MIN: usize = 1; +pub const SIZE_PACKET_LEN_MAX: usize = 5; + +pub const KMCS_VERSION: u8 = 41; + +pub const K_HEARTBEAT_PING_TAG: u8 = 0; +pub const K_HEARTBEAT_ACK_TAG: u8 = 1; +pub const K_LOGIN_REQUEST_TAG: u8 = 2; +pub const K_LOGIN_RESPONSE_TAG: u8 = 3; +pub const K_CLOSE_TAG: u8 = 4; +pub const K_MESSAGE_STANZA_TAG: u8 = 5; +pub const K_PRESENCE_STANZA_TAG: u8 = 6; +pub const K_IQ_STANZA_TAG: u8 = 7; +pub const K_DATA_MESSAGE_STANZA_TAG: u8 = 8; +pub const K_BATCH_PRESENCE_STANZA_TAG: u8 = 9; +pub const K_STREAM_ERROR_STANZA_TAG: u8 = 10; + +pub const FCM_SERVER_KEY: [u8; 65] = [ + 4, 51, 148, 247, 223, 161, 235, 177, 220, 3, 162, 94, 21, 113, 219, 72, 211, 46, 237, 237, 178, + 52, 219, 183, 71, 58, 12, 143, 196, 204, 225, 111, 60, 140, 132, 223, 171, 182, 102, 62, 242, + 12, 212, 139, 254, 227, 249, 118, 47, 20, 28, 99, 8, 106, 111, 45, 177, 26, 149, 176, 206, 55, + 192, 156, 110, +]; diff --git a/vendor/fcm_receiver/src/crypto.rs b/vendor/fcm_receiver/src/crypto.rs new file mode 100644 index 0000000..ccad444 --- /dev/null +++ b/vendor/fcm_receiver/src/crypto.rs @@ -0,0 +1,124 @@ +use aes_gcm::aead::{Aead, KeyInit}; +use aes_gcm::{Aes128Gcm, Nonce}; +use hkdf::Hkdf; +use hmac::{Hmac, Mac}; +use p256::ecdh::diffie_hellman; +use p256::elliptic_curve::sec1::ToEncodedPoint; +use p256::pkcs8::{DecodePrivateKey, EncodePrivateKey}; +use p256::{EncodedPoint, PublicKey, SecretKey}; +use rand::rngs::OsRng; +use rand::RngCore; +use sha2::Sha256; + +use crate::error::{Error, Result}; + +pub fn create_keys() -> Result<(SecretKey, PublicKey, Vec)> { + let private_key = SecretKey::random(&mut OsRng); + let public_key = private_key.public_key(); + let auth_secret = create_auth_secret()?; + Ok((private_key, public_key, auth_secret)) +} + +pub fn create_auth_secret() -> Result> { + let mut secret = vec![0u8; 16]; + OsRng.fill_bytes(&mut secret); + Ok(secret) +} + +pub fn encode_private_key(key: &SecretKey) -> Result> { + let der = key + .to_pkcs8_der() + .map_err(|err| Error::Crypto(format!("pkcs8 encode failed: {err}")))?; + Ok(der.as_bytes().to_vec()) +} + +pub fn decode_private_key(bytes: &[u8]) -> Result { + let key = SecretKey::from_pkcs8_der(bytes) + .map_err(|err| Error::Crypto(format!("pkcs8 decode failed: {err}")))?; + Ok(key) +} + +pub fn public_key_bytes(key: &PublicKey) -> Vec { + key.to_encoded_point(false).as_bytes().to_vec() +} + +pub fn decrypt_message( + crypto_key: &[u8], + encryption_salt: &[u8], + raw_data: &[u8], + auth_secret: &[u8], + private_key: &SecretKey, + public_key: &PublicKey, +) -> Result> { + let remote_point = EncodedPoint::from_bytes(crypto_key) + .map_err(|_| Error::InvalidData("invalid dh public key"))?; + let remote_public = PublicKey::from_sec1_bytes(remote_point.as_bytes()) + .map_err(|_| Error::InvalidData("invalid dh public key"))?; + + let shared_secret = diffie_hellman(private_key.to_nonzero_scalar(), remote_public.as_affine()); + let shared_bytes = shared_secret.raw_secret_bytes(); + + let prk_key = hkdf_extract(auth_secret, shared_bytes.as_slice())?; + + let hkdf_salt = Hkdf::::new(Some(encryption_salt), prk_key.as_slice()); + + let client_public = public_key_bytes(public_key); + let server_public = remote_public.to_encoded_point(false).as_bytes().to_vec(); + + let context = build_context(&client_public, &server_public); + let mut cek_info = Vec::with_capacity(24 + context.len()); + cek_info.extend_from_slice(b"Content-Encoding: aesgcm"); + cek_info.push(0); + cek_info.extend_from_slice(&context); + + let mut nonce_info = Vec::with_capacity(24 + context.len()); + nonce_info.extend_from_slice(b"Content-Encoding: nonce"); + nonce_info.push(0); + nonce_info.extend_from_slice(&context); + + let mut cek = [0u8; 16]; + hkdf_salt + .expand(&cek_info, &mut cek) + .map_err(|_| Error::Crypto("hkdf expand cek failed".into()))?; + + let mut nonce_bytes = [0u8; 12]; + hkdf_salt + .expand(&nonce_info, &mut nonce_bytes) + .map_err(|_| Error::Crypto("hkdf expand nonce failed".into()))?; + + let cipher = Aes128Gcm::new_from_slice(&cek) + .map_err(|_| Error::Crypto("failed to init AES key".into()))?; + let nonce = Nonce::from_slice(&nonce_bytes); + + let plaintext = cipher + .decrypt(nonce, raw_data) + .map_err(|_| Error::Crypto("failed to decrypt message".into()))?; + + Ok(plaintext) +} + +fn build_context(client_public: &[u8], server_public: &[u8]) -> Vec { + let mut context = Vec::with_capacity(1 + 2 + client_public.len() + 2 + server_public.len()); + context.push(0); + context.extend_from_slice(&(client_public.len() as u16).to_be_bytes()); + context.extend_from_slice(client_public); + context.extend_from_slice(&(server_public.len() as u16).to_be_bytes()); + context.extend_from_slice(server_public); + context +} + +fn hkdf_extract(salt: &[u8], ikm: &[u8]) -> Result<[u8; 32]> { + let key_material = if salt.is_empty() { + vec![0u8; 32] + } else { + salt.to_vec() + }; + + let mut mac = as Mac>::new_from_slice(&key_material) + .map_err(|_| Error::Crypto("invalid hmac key".into()))?; + mac.update(ikm); + let result = mac.finalize().into_bytes(); + let mut prk = [0u8; 32]; + prk.copy_from_slice(&result); + Ok(prk) +} diff --git a/vendor/fcm_receiver/src/ece_backend.rs b/vendor/fcm_receiver/src/ece_backend.rs new file mode 100644 index 0000000..331d11e --- /dev/null +++ b/vendor/fcm_receiver/src/ece_backend.rs @@ -0,0 +1,106 @@ +//! Pure-Rust (RustCrypto) backend for the `ece` crate, so that decrypting +//! web pushes does not need OpenSSL (which is not available on Windows CI). + +use std::any::Any; +use std::sync::Once; + +use aes_gcm::aead::{Aead, KeyInit}; +use aes_gcm::{Aes128Gcm, Nonce}; +use ece::{Cryptographer, EcKeyComponents, LocalKeyPair, RemotePublicKey}; +use p256::elliptic_curve::sec1::ToEncodedPoint; +use rand::RngCore; +use sha2::Sha256; + +type EceResult = std::result::Result; + +struct Local(p256::SecretKey); +struct Remote(p256::PublicKey); + +fn raw_point(pk: &p256::PublicKey) -> Vec { + pk.to_encoded_point(false).as_bytes().to_vec() +} + +impl LocalKeyPair for Local { + fn pub_as_raw(&self) -> EceResult> { + Ok(raw_point(&self.0.public_key())) + } + fn raw_components(&self) -> EceResult { + Ok(EcKeyComponents::new(self.0.to_bytes().to_vec(), raw_point(&self.0.public_key()))) + } + fn as_any(&self) -> &dyn Any { + self + } +} + +impl RemotePublicKey for Remote { + fn as_raw(&self) -> EceResult> { + Ok(raw_point(&self.0)) + } + fn as_any(&self) -> &dyn Any { + self + } +} + +pub struct RustCryptoBackend; + +impl Cryptographer for RustCryptoBackend { + fn generate_ephemeral_keypair(&self) -> EceResult> { + Ok(Box::new(Local(p256::SecretKey::random(&mut rand::thread_rng())))) + } + + fn import_key_pair(&self, c: &EcKeyComponents) -> EceResult> { + let sk = p256::SecretKey::from_slice(c.private_key()).map_err(|_| ece::Error::InvalidKeyLength)?; + Ok(Box::new(Local(sk))) + } + + fn import_public_key(&self, raw: &[u8]) -> EceResult> { + let pk = p256::PublicKey::from_sec1_bytes(raw).map_err(|_| ece::Error::InvalidKeyLength)?; + Ok(Box::new(Remote(pk))) + } + + fn compute_ecdh_secret(&self, remote: &dyn RemotePublicKey, local: &dyn LocalKeyPair) -> EceResult> { + let r = remote.as_any().downcast_ref::().ok_or(ece::Error::CryptoError)?; + let l = local.as_any().downcast_ref::().ok_or(ece::Error::CryptoError)?; + let shared = p256::ecdh::diffie_hellman(l.0.to_nonzero_scalar(), r.0.as_affine()); + Ok(shared.raw_secret_bytes().to_vec()) + } + + fn hkdf_sha256(&self, salt: &[u8], secret: &[u8], info: &[u8], len: usize) -> EceResult> { + let mut out = vec![0u8; len]; + hkdf::Hkdf::::new(Some(salt), secret).expand(info, &mut out).map_err(|_| ece::Error::CryptoError)?; + Ok(out) + } + + fn aes_gcm_128_encrypt(&self, key: &[u8], iv: &[u8], data: &[u8]) -> EceResult> { + let c = Aes128Gcm::new_from_slice(key).map_err(|_| ece::Error::InvalidKeyLength)?; + c.encrypt(Nonce::from_slice(iv), data).map_err(|_| ece::Error::CryptoError) + } + + fn aes_gcm_128_decrypt(&self, key: &[u8], iv: &[u8], ciphertext_and_tag: &[u8]) -> EceResult> { + let c = Aes128Gcm::new_from_slice(key).map_err(|_| ece::Error::InvalidKeyLength)?; + c.decrypt(Nonce::from_slice(iv), ciphertext_and_tag).map_err(|_| ece::Error::CryptoError) + } + + fn random_bytes(&self, dest: &mut [u8]) -> EceResult<()> { + rand::thread_rng().fill_bytes(dest); + Ok(()) + } +} + +/// Registers the backend once; safe to call before every decryption. +pub fn init() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| { + let _ = ece::crypto::set_boxed_cryptographer(Box::new(RustCryptoBackend)); + }); +} + +#[cfg(test)] +mod tests { + #[test] + fn passes_ece_backend_test_suite() { + // The suite also goes through the global backend. + super::init(); + ece::crypto::test_cryptographer(super::RustCryptoBackend); + } +} diff --git a/vendor/fcm_receiver/src/encryption.rs b/vendor/fcm_receiver/src/encryption.rs new file mode 100644 index 0000000..8f3f6db --- /dev/null +++ b/vendor/fcm_receiver/src/encryption.rs @@ -0,0 +1,36 @@ +use crate::crypto::public_key_bytes; +use crate::error::{Error, Result}; +use ece::crypto::EcKeyComponents; +use ece::legacy::{decrypt_aesgcm, AesGcmEncryptedBlock}; +use p256::SecretKey; + +const DEFAULT_RECORD_SIZE: u32 = 4096; + +pub fn decrypt_message( + crypto_key: &[u8], + encryption: &[u8], + raw_data: &[u8], + auth_secret: &[u8], + private_key: &SecretKey, +) -> Result> { + crate::ece_backend::init(); + if raw_data.is_empty() { + return Err(Error::InvalidData("raw data payload missing")); + } + + let block = AesGcmEncryptedBlock::new( + crypto_key, + encryption, + DEFAULT_RECORD_SIZE, + raw_data.to_vec(), + ) + .map_err(|err| Error::Other(format!("failed to create encrypted block: {err}")))?; + + let public_key = private_key.public_key(); + let private_bytes = private_key.to_bytes().to_vec(); + let public_bytes = public_key_bytes(&public_key); + let components = EcKeyComponents::new(private_bytes, public_bytes); + + decrypt_aesgcm(&components, auth_secret, &block) + .map_err(|err| Error::Other(format!("failed to decrypt message: {err}"))) +} diff --git a/vendor/fcm_receiver/src/error.rs b/vendor/fcm_receiver/src/error.rs new file mode 100644 index 0000000..9be7b17 --- /dev/null +++ b/vendor/fcm_receiver/src/error.rs @@ -0,0 +1,82 @@ +use std::fmt; + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("proto error: {0}")] + Proto(#[from] ProtoError), + #[error("io error: {0}")] + Io(#[from] std::io::Error), + #[error("http error: {0}")] + Http(#[from] reqwest::Error), + #[error("serialization error: {0}")] + Serde(#[from] serde_json::Error), + #[error("url error: {0}")] + Url(#[from] url::ParseError), + #[error("hkdf error: {0}")] + Hkdf(String), + #[error("crypto error: {0}")] + Crypto(String), + #[error("invalid data: {0}")] + InvalidData(&'static str), + #[error("other error: {0}")] + Other(String), +} + +pub type Result = std::result::Result; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProtoErrorKind { + Eof, + InvalidVarint, + InvalidLength, + UnsupportedWireType(u8), + InvalidWireType, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProtoError { + kind: ProtoErrorKind, + context: Option<&'static str>, +} + +impl ProtoError { + pub fn new(kind: ProtoErrorKind) -> Self { + Self { + kind, + context: None, + } + } + + pub fn with_context(kind: ProtoErrorKind, context: &'static str) -> Self { + Self { + kind, + context: Some(context), + } + } + + pub fn kind(&self) -> &ProtoErrorKind { + &self.kind + } +} + +impl fmt::Display for ProtoError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let base = match &self.kind { + ProtoErrorKind::Eof => "unexpected EOF".to_string(), + ProtoErrorKind::InvalidVarint => "invalid varint encoding".to_string(), + ProtoErrorKind::InvalidLength => "invalid length".to_string(), + ProtoErrorKind::UnsupportedWireType(wt) => format!("unsupported wire type {wt}"), + ProtoErrorKind::InvalidWireType => "invalid wire type".to_string(), + }; + + if let Some(ctx) = self.context { + write!(f, "{base} ({ctx})") + } else { + write!(f, "{base}") + } + } +} + +impl std::error::Error for ProtoError {} diff --git a/vendor/fcm_receiver/src/http_client.rs b/vendor/fcm_receiver/src/http_client.rs new file mode 100644 index 0000000..8e814e6 --- /dev/null +++ b/vendor/fcm_receiver/src/http_client.rs @@ -0,0 +1,379 @@ +use std::collections::HashMap; + +use base64::engine::general_purpose::{STANDARD as BASE64_STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use reqwest::blocking::Client; +use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE, USER_AGENT}; +use serde::{Deserialize, Serialize}; +use url::form_urlencoded; + +use crate::consts::{ + CHECK_IN_URL, FCM_ENDPOINT_URL, FIREBASE_INSTALLATION_URL, FIREBASE_REGISTRATION_URL, + REGISTER_URL, +}; +use crate::error::{Error, Result}; +use crate::messages::{ + marshal_android_checkin_request, unmarshal_android_checkin_response, + ManualAndroidCheckinRequest, ManualAndroidCheckinResponse, +}; + +#[derive(Debug, Clone, Deserialize)] +pub struct AuthToken { + #[serde(rename = "token")] + pub token: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct FcmInstallationResponse { + #[serde(rename = "authToken")] + pub auth_token: AuthToken, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct FcmRegisterResponse { + #[serde(rename = "token")] + pub token: String, + #[serde(rename = "pushSet")] + pub push_set: Option, +} + +#[derive(Debug, Clone)] +pub struct AndroidAppOptions<'a> { + pub gcm_sender_id: &'a str, + pub android_package: &'a str, + pub android_package_cert: &'a str, +} + +#[derive(Debug, Clone)] +pub struct GcmRegisterRequest<'a> { + pub android_id: u64, + pub security_token: u64, + pub app_id: &'a str, + pub android_app: Option>, + pub installation_auth: Option<&'a str>, + pub sender_override: Option, + pub subtype_override: Option, + pub delete: bool, + pub extra_params: Vec<(String, String)>, +} + +#[derive(Debug, Clone)] +pub struct FcmInstallRequest<'a> { + pub api_key: &'a str, + pub project_id: &'a str, + pub app_id: &'a str, + pub fid: &'a str, + pub android_app: Option>, + pub firebase_client_header: Option<&'a str>, + pub firebase_client_log_type: Option<&'a str>, + pub user_agent: Option<&'a str>, +} + +#[derive(Debug, Clone)] +pub struct FcmRegisterRequest<'a> { + pub api_key: &'a str, + pub project_id: &'a str, + pub installation_auth: &'a str, + pub vapid_key: &'a str, + pub auth_secret: &'a str, + pub endpoint: &'a str, + pub p256dh: &'a str, +} + +pub fn build_default_http_client() -> Result { + let client = Client::builder().build()?; + Ok(client) +} + +pub fn validate_topic_name(topic: &str) -> Result<()> { + if topic.is_empty() { + return Err(Error::InvalidData("topic name is empty")); + } + + if !topic + .chars() + .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' | '~' | '%')) + { + return Err(Error::InvalidData( + "topic name contains invalid characters. allowed: a-z, A-Z, 0-9, '-', '_', '.', '~', '%'", + )); + } + + Ok(()) +} + +pub fn send_gcm_check_in_request( + client: &Client, + request_body: &ManualAndroidCheckinRequest, +) -> Result { + let body = marshal_android_checkin_request(request_body)?; + + let mut headers = HeaderMap::new(); + headers.insert( + CONTENT_TYPE, + HeaderValue::from_static("application/x-protobuf"), + ); + headers.insert(USER_AGENT, HeaderValue::from_static("")); + + let response = client + .post(CHECK_IN_URL) + .headers(headers) + .body(body) + .send()?; + + let status = response.status(); + let bytes = response.bytes()?; + if !status.is_success() { + return Err(Error::Other(format!( + "check-in HTTP {}: {}", + status, + String::from_utf8_lossy(&bytes) + ))); + } + + let message = unmarshal_android_checkin_response(&bytes)?; + Ok(message) +} + +pub fn send_gcm_register_request(client: &Client, cfg: &GcmRegisterRequest<'_>) -> Result { + let mut params: HashMap = HashMap::new(); + + match &cfg.android_app { + Some(app) => { + let subtype_value = cfg.subtype_override.as_deref().unwrap_or(app.gcm_sender_id); + params.insert("X-subtype".to_string(), subtype_value.to_string()); + params.insert("device".to_string(), cfg.android_id.to_string()); + params.insert("app".to_string(), app.android_package.to_string()); + params.insert("cert".to_string(), app.android_package_cert.to_string()); + params.insert("app_ver".to_string(), "1".to_string()); + params.insert("X-app_ver".to_string(), "1".to_string()); + params.insert("X-osv".to_string(), "29".to_string()); + params.insert("X-cliv".to_string(), "fiid-21.1.1".to_string()); + params.insert("X-gmsv".to_string(), "220217001".to_string()); + params.insert("X-scope".to_string(), "*".to_string()); + if let Some(auth) = cfg.installation_auth { + params.insert( + "X-Goog-Firebase-Installations-Auth".to_string(), + auth.to_string(), + ); + } + params.insert("X-gms_app_id".to_string(), cfg.app_id.to_string()); + params.insert( + "X-Firebase-Client".to_string(), + "android-min-sdk/23 fire-core/20.0.0 device-name/a21snnxx device-brand/samsung device-model/a21s android-installer/com.android.vending fire-android/30 fire-installations/17.0.0 fire-fcm/22.0.0 android-platform/ kotlin/1.9.23 android-target-sdk/34".to_string(), + ); + params.insert("X-Firebase-Client-Log-Type".to_string(), "1".to_string()); + params.insert("X-app_ver_name".to_string(), "1".to_string()); + params.insert("target_ver".to_string(), "31".to_string()); + let sender_value = cfg + .sender_override + .as_ref() + .map(|s| s.as_str()) + .unwrap_or(app.gcm_sender_id); + params.insert("sender".to_string(), sender_value.to_string()); + } + None => { + let subtype_value = cfg.subtype_override.as_deref().unwrap_or(cfg.app_id); + params.insert("X-subtype".to_string(), subtype_value.to_string()); + params.insert("app".to_string(), "org.chromium.linux".to_string()); + params.insert("device".to_string(), cfg.android_id.to_string()); + let default_sender = URL_SAFE_NO_PAD.encode(crate::consts::FCM_SERVER_KEY); + let sender_value = cfg + .sender_override + .as_ref() + .map(|s| s.as_str()) + .unwrap_or(default_sender.as_str()); + params.insert("sender".to_string(), sender_value.to_string()); + params.insert("X-gms_app_id".to_string(), cfg.app_id.to_string()); + } + } + + if cfg.delete { + params.insert("delete".to_string(), "1".to_string()); + params.insert("X-delete".to_string(), "1".to_string()); + } + + for (key, value) in &cfg.extra_params { + params.insert(key.clone(), value.clone()); + } + + let mut serializer = form_urlencoded::Serializer::new(String::new()); + for (k, v) in ¶ms { + serializer.append_pair(k, v); + } + let body = serializer.finish(); + + let authorization_value = format!("AidLogin {}:{}", cfg.android_id, cfg.security_token); + + let response = client + .post(REGISTER_URL) + .header("Authorization", authorization_value) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(USER_AGENT, "") + .body(body) + .send()?; + + let status = response.status(); + let body_bytes = response.bytes()?; + if !status.is_success() { + return Err(Error::Other(format!( + "register HTTP {}: {}", + status, + String::from_utf8_lossy(&body_bytes) + ))); + } + + let body_str = String::from_utf8_lossy(&body_bytes); + let parsed: HashMap = form_urlencoded::parse(body_str.as_bytes()) + .into_owned() + .collect(); + + if let Some(err) = parsed.get("Error") { + return Err(Error::Other(err.clone())); + } + + parsed + .get("token") + .cloned() + .ok_or_else(|| Error::InvalidData("missing token in register response")) +} + +pub fn send_fcm_install_request( + client: &Client, + cfg: &FcmInstallRequest<'_>, +) -> Result { + #[derive(Serialize)] + struct Body<'a> { + fid: &'a str, + #[serde(rename = "appId")] + app_id: &'a str, + #[serde(rename = "authVersion")] + auth_version: &'a str, + #[serde(rename = "sdkVersion")] + sdk_version: &'a str, + } + + let mut headers = HeaderMap::new(); + headers.insert("Accept", HeaderValue::from_static("application/json")); + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + let api_key_header = HeaderValue::from_str(cfg.api_key) + .map_err(|err| Error::Other(format!("invalid api key header: {err}")))?; + headers.insert("x-goog-api-key", api_key_header); + + let sdk_version = if cfg.android_app.is_some() { + "a:17.0.0" + } else { + "w:0.6.4" + }; + + let body = Body { + fid: cfg.fid, + app_id: cfg.app_id, + auth_version: "FIS_v2", + sdk_version, + }; + + let mut request = client + .post(format!( + "{}projects/{}/installations", + FIREBASE_INSTALLATION_URL, cfg.project_id + )) + .headers(headers) + .json(&body); + + if let Some(app) = &cfg.android_app { + request = request + .header("X-Android-Package", app.android_package) + .header("X-Android-Cert", app.android_package_cert) + .header( + "x-firebase-client", + cfg.firebase_client_header.unwrap_or("android-min-sdk/23 fire-core/20.0.0 device-name/a21snnxx device-brand/samsung device-model/a21s android-installer/com.android.vending fire-android/30 fire-installations/17.0.0 fire-fcm/22.0.0 android-platform/ kotlin/1.9.23 android-target-sdk/34"), + ) + .header( + "x-firebase-client-log-type", + cfg.firebase_client_log_type.unwrap_or("3"), + ) + .header( + USER_AGENT, + cfg.user_agent.unwrap_or("Dalvik/2.1.0 (Linux; U; Android 11; SM-A217F Build/RP1A.200720.012)"), + ); + } else { + let client_info = serde_json::json!({ + "heartbeats": [], + "version": 2, + }); + let encoded = BASE64_STANDARD.encode(client_info.to_string()); + request = request.header("x-firebase-client", encoded); + } + + let response = request.send()?; + let status = response.status(); + let bytes = response.bytes()?; + if !status.is_success() { + return Err(Error::Other(format!( + "installation HTTP {}: {}", + status, + String::from_utf8_lossy(&bytes) + ))); + } + + let parsed: FcmInstallationResponse = serde_json::from_slice(&bytes)?; + Ok(parsed) +} + +pub fn send_fcm_register_request( + client: &Client, + cfg: &FcmRegisterRequest<'_>, +) -> Result { + #[derive(Serialize)] + struct Web<'a> { + #[serde(rename = "applicationPubKey")] + application_pub_key: &'a str, + auth: &'a str, + endpoint: &'a str, + #[serde(rename = "p256dh")] + p256dh: &'a str, + } + + #[derive(Serialize)] + struct Body<'a> { + web: Web<'a>, + } + + let body = Body { + web: Web { + application_pub_key: cfg.vapid_key, + auth: cfg.auth_secret, + endpoint: cfg.endpoint, + p256dh: cfg.p256dh, + }, + }; + + let response = client + .post(format!( + "{}projects/{}/registrations", + FIREBASE_REGISTRATION_URL, cfg.project_id + )) + .header("x-goog-api-key", cfg.api_key) + .header("x-goog-firebase-installations-auth", cfg.installation_auth) + .header(CONTENT_TYPE, "application/json") + .json(&body) + .send()?; + + let status = response.status(); + let bytes = response.bytes()?; + if !status.is_success() { + return Err(Error::Other(format!( + "register HTTP {}: {}", + status, + String::from_utf8_lossy(&bytes) + ))); + } + + let parsed: FcmRegisterResponse = serde_json::from_slice(&bytes)?; + Ok(parsed) +} + +pub fn build_endpoint_url(token: &str) -> String { + format!("{}/{}", FCM_ENDPOINT_URL.trim_end_matches('/'), token) +} diff --git a/vendor/fcm_receiver/src/lib.rs b/vendor/fcm_receiver/src/lib.rs new file mode 100644 index 0000000..a78238f --- /dev/null +++ b/vendor/fcm_receiver/src/lib.rs @@ -0,0 +1,17 @@ +//! Vendored third-party code (see CHANGES.md): lints are not enforced here. +#![allow(deprecated, clippy::all)] + +pub mod client; +pub mod consts; +pub mod crypto; +pub mod ece_backend; +pub mod encryption; +pub mod http_client; +pub mod messages; +pub mod proto; +pub mod socket_handler; +pub mod util; + +mod error; + +pub use error::{Error, ProtoError, ProtoErrorKind, Result}; diff --git a/vendor/fcm_receiver/src/messages/builders.rs b/vendor/fcm_receiver/src/messages/builders.rs new file mode 100644 index 0000000..a8b2be3 --- /dev/null +++ b/vendor/fcm_receiver/src/messages/builders.rs @@ -0,0 +1,121 @@ +use crate::consts::{KMCS_VERSION, K_LOGIN_REQUEST_TAG}; +use crate::error::Result; +use crate::proto::put_uvarint; + +use super::types::*; +use super::{ + marshal_login_request, unmarshal_close, unmarshal_data_message_stanza, unmarshal_heartbeat_ack, + unmarshal_heartbeat_ping, unmarshal_iq_stanza, unmarshal_login_request, + unmarshal_login_response, unmarshal_stream_error_stanza, +}; + +pub fn create_login_request_raw( + android_id: u64, + security_token: u64, + persistent_ids: &[String], +) -> Result> { + let chrome_version = "chrome-63.0.3234.0"; + let domain = "mcs.android.com"; + + let android_id_formatted = android_id.to_string(); + let android_id_hex = format!("android-{android_id:x}"); + let security_token_formatted = security_token.to_string(); + + let persistent_copy = if persistent_ids.len() > 2 { + persistent_ids[persistent_ids.len() - 2..].to_vec() + } else { + persistent_ids.to_vec() + }; + + let request = ManualLoginRequest { + id: chrome_version.to_string(), + domain: domain.to_string(), + user: android_id_formatted.clone(), + resource: android_id_formatted.clone(), + auth_token: security_token_formatted, + device_id: android_id_hex, + last_rmq_id: None, + setting: vec![ManualSetting { + name: "new_vc".to_string(), + value: "1".to_string(), + }], + received_persistent_id: persistent_copy, + adaptive_heartbeat: Some(false), + heartbeat_stat: None, + use_rmq2: Some(true), + account_id: None, + auth_service: Some(ManualLoginRequestAuthService::AndroidId), + network_type: Some(1), + status: None, + client_event: Vec::new(), + }; + + let payload = marshal_login_request(&request)?; + + let mut packet = Vec::with_capacity(2 + 5 + payload.len()); + packet.push(KMCS_VERSION); + packet.push(K_LOGIN_REQUEST_TAG); + packet.extend_from_slice(&put_uvarint(payload.len() as u64)); + packet.extend_from_slice(&payload); + Ok(packet) +} + +pub fn create_check_in_request( + android_id: i64, + security_token: Option, +) -> ManualAndroidCheckinRequest { + let mut request = ManualAndroidCheckinRequest::default(); + request.id = Some(android_id); + request.version = Some(3); + request.security_token = security_token; + + let chrome_build = ManualChromeBuildProto { + platform: Some(ManualChromeBuildPlatform::Linux), + chrome_version: Some("63.0.3234.0".to_string()), + channel: Some(ManualChromeBuildChannel::Stable), + }; + + request.checkin = Some(ManualAndroidCheckinProto { + last_checkin_msec: None, + cell_operator: None, + sim_operator: None, + roaming: None, + user_number: None, + device_type: Some(ManualDeviceType::ChromeBrowser), + chrome_build: Some(chrome_build), + }); + + request +} + +pub fn decode_heartbeat_ping(data: &[u8]) -> Result { + unmarshal_heartbeat_ping(data) +} + +pub fn decode_heartbeat_ack(data: &[u8]) -> Result { + unmarshal_heartbeat_ack(data) +} + +pub fn decode_login_request(data: &[u8]) -> Result { + unmarshal_login_request(data) +} + +pub fn decode_login_response(data: &[u8]) -> Result { + unmarshal_login_response(data) +} + +pub fn decode_close(data: &[u8]) -> Result { + unmarshal_close(data) +} + +pub fn decode_iq_stanza(data: &[u8]) -> Result { + unmarshal_iq_stanza(data) +} + +pub fn decode_data_message_stanza(data: &[u8]) -> Result { + unmarshal_data_message_stanza(data) +} + +pub fn decode_stream_error_stanza(data: &[u8]) -> Result { + unmarshal_stream_error_stanza(data) +} diff --git a/vendor/fcm_receiver/src/messages/marshal.rs b/vendor/fcm_receiver/src/messages/marshal.rs new file mode 100644 index 0000000..f9fe52a --- /dev/null +++ b/vendor/fcm_receiver/src/messages/marshal.rs @@ -0,0 +1,457 @@ +use crate::error::Result; +use crate::proto::ProtoEncoder; + +use super::types::*; + +pub fn marshal_android_checkin_request(msg: &ManualAndroidCheckinRequest) -> Result> { + let mut encoder = ProtoEncoder::new(); + + if let Some(imei) = &msg.imei { + encoder.encode_string(1, imei); + } + if let Some(meid) = &msg.meid { + encoder.encode_string(10, meid); + } + for addr in &msg.mac_addr { + encoder.encode_string(9, addr); + } + for addr_type in &msg.mac_addr_type { + encoder.encode_string(19, addr_type); + } + if let Some(serial) = &msg.serial_number { + encoder.encode_string(16, serial); + } + if let Some(esn) = &msg.esn { + encoder.encode_string(17, esn); + } + if let Some(id) = msg.id { + encoder.encode_int64(2, id); + } + if let Some(logging_id) = msg.logging_id { + encoder.encode_int64(7, logging_id); + } + if let Some(digest) = &msg.digest { + encoder.encode_string(3, digest); + } + if let Some(locale) = &msg.locale { + encoder.encode_string(6, locale); + } + if let Some(checkin) = &msg.checkin { + let bytes = marshal_android_checkin_proto(checkin)?; + encoder.encode_bytes(4, &bytes); + } + if let Some(desired) = &msg.desired_build { + encoder.encode_string(5, desired); + } + if let Some(market) = &msg.market_checkin { + encoder.encode_string(8, market); + } + for cookie in &msg.account_cookie { + encoder.encode_string(11, cookie); + } + if let Some(tz) = &msg.time_zone { + encoder.encode_string(12, tz); + } + if let Some(token) = msg.security_token { + encoder.encode_fixed64(13, token); + } + if let Some(version) = msg.version { + encoder.encode_int32(14, version); + } + for cert in &msg.ota_cert { + encoder.encode_string(15, cert); + } + if let Some(fragment) = msg.fragment { + encoder.encode_int32(20, fragment); + } + if let Some(user_name) = &msg.user_name { + encoder.encode_string(21, user_name); + } + if let Some(serial) = msg.user_serial_number { + encoder.encode_int32(22, serial); + } + + Ok(encoder.into_bytes()) +} + +pub fn marshal_android_checkin_proto(msg: &ManualAndroidCheckinProto) -> Result> { + let mut encoder = ProtoEncoder::new(); + + if let Some(last) = msg.last_checkin_msec { + encoder.encode_int64(2, last); + } + if let Some(cell) = &msg.cell_operator { + encoder.encode_string(6, cell); + } + if let Some(sim) = &msg.sim_operator { + encoder.encode_string(7, sim); + } + if let Some(roaming) = &msg.roaming { + encoder.encode_string(8, roaming); + } + if let Some(user_number) = msg.user_number { + encoder.encode_int32(9, user_number); + } + if let Some(device_type) = msg.device_type { + encoder.encode_int32(12, device_type as i32); + } + if let Some(chrome) = &msg.chrome_build { + let bytes = marshal_chrome_build_proto(chrome)?; + encoder.encode_bytes(13, &bytes); + } + + Ok(encoder.into_bytes()) +} + +pub fn marshal_chrome_build_proto(msg: &ManualChromeBuildProto) -> Result> { + let mut encoder = ProtoEncoder::new(); + + if let Some(platform) = msg.platform { + encoder.encode_int32(1, platform as i32); + } + if let Some(version) = &msg.chrome_version { + encoder.encode_string(2, version); + } + if let Some(channel) = msg.channel { + encoder.encode_int32(3, channel as i32); + } + + Ok(encoder.into_bytes()) +} + +pub fn marshal_login_request(msg: &ManualLoginRequest) -> Result> { + let mut encoder = ProtoEncoder::new(); + + encoder.encode_string(1, &msg.id); + encoder.encode_string(2, &msg.domain); + encoder.encode_string(3, &msg.user); + encoder.encode_string(4, &msg.resource); + encoder.encode_string(5, &msg.auth_token); + encoder.encode_string(6, &msg.device_id); + + if let Some(last_rmq) = msg.last_rmq_id { + encoder.encode_int64(7, last_rmq); + } + + for setting in &msg.setting { + let bytes = marshal_setting(setting)?; + encoder.encode_bytes(8, &bytes); + } + + for id in &msg.received_persistent_id { + encoder.encode_string(10, id); + } + + if let Some(adaptive) = msg.adaptive_heartbeat { + encoder.encode_bool(12, adaptive); + } + + if let Some(stat) = &msg.heartbeat_stat { + let bytes = marshal_heartbeat_stat(stat)?; + encoder.encode_bytes(13, &bytes); + } + + if let Some(use_rmq2) = msg.use_rmq2 { + encoder.encode_bool(14, use_rmq2); + } + + if let Some(account_id) = msg.account_id { + encoder.encode_int64(15, account_id); + } + + if let Some(auth_service) = msg.auth_service { + encoder.encode_int32(16, auth_service as i32); + } + + if let Some(network_type) = msg.network_type { + encoder.encode_int32(17, network_type); + } + + if let Some(status) = msg.status { + encoder.encode_int64(18, status); + } + + for event in &msg.client_event { + let bytes = marshal_client_event(event)?; + encoder.encode_bytes(22, &bytes); + } + + Ok(encoder.into_bytes()) +} + +pub fn marshal_setting(msg: &ManualSetting) -> Result> { + let mut encoder = ProtoEncoder::new(); + encoder.encode_string(1, &msg.name); + encoder.encode_string(2, &msg.value); + Ok(encoder.into_bytes()) +} + +pub fn marshal_heartbeat_stat(msg: &ManualHeartbeatStat) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(ip) = &msg.ip { + encoder.encode_string(1, ip); + } + if let Some(timeout) = msg.timeout { + encoder.encode_bool(2, timeout); + } + if let Some(interval) = msg.interval_ms { + encoder.encode_int32(3, interval); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_client_event(msg: &ManualClientEvent) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(event_type) = msg.event_type { + encoder.encode_int32(1, event_type as i32); + } + if let Some(discarded) = msg.number_discarded_events { + encoder.encode_uint32(100, discarded); + } + if let Some(network_type) = msg.network_type { + encoder.encode_int32(200, network_type); + } + if let Some(started) = msg.time_connection_started_ms { + encoder.encode_uint64(202, started); + } + if let Some(ended) = msg.time_connection_ended_ms { + encoder.encode_uint64(203, ended); + } + if let Some(error_code) = msg.error_code { + encoder.encode_int32(204, error_code); + } + if let Some(established) = msg.time_connection_established_ms { + encoder.encode_uint64(300, established); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_data_message_stanza(msg: &ManualDataMessageStanza) -> Result> { + let mut encoder = ProtoEncoder::new(); + + if let Some(id) = &msg.id { + encoder.encode_string(2, id); + } + if let Some(from) = &msg.from { + encoder.encode_string(3, from); + } + if let Some(to) = &msg.to { + encoder.encode_string(4, to); + } + if let Some(category) = &msg.category { + encoder.encode_string(5, category); + } + if let Some(token) = &msg.token { + encoder.encode_string(6, token); + } + for app_data in &msg.app_data { + let bytes = marshal_app_data(app_data)?; + encoder.encode_bytes(7, &bytes); + } + if let Some(from_trusted) = msg.from_trusted_server { + encoder.encode_bool(8, from_trusted); + } + if let Some(pid) = &msg.persistent_id { + encoder.encode_string(9, pid); + } + if let Some(stream_id) = msg.stream_id { + encoder.encode_int32(10, stream_id); + } + if let Some(last_stream) = msg.last_stream_id_received { + encoder.encode_int32(11, last_stream); + } + if let Some(reg_id) = &msg.reg_id { + encoder.encode_string(13, reg_id); + } + if let Some(device_user_id) = msg.device_user_id { + encoder.encode_int64(16, device_user_id); + } + if let Some(ttl) = msg.ttl { + encoder.encode_int32(17, ttl); + } + if let Some(sent) = msg.sent { + encoder.encode_int64(18, sent); + } + if let Some(queued) = msg.queued { + encoder.encode_int32(19, queued); + } + if let Some(status) = msg.status { + encoder.encode_int64(20, status); + } + if let Some(raw) = &msg.raw_data { + encoder.encode_bytes(21, raw); + } + if let Some(immediate_ack) = msg.immediate_ack { + encoder.encode_bool(24, immediate_ack); + } + + Ok(encoder.into_bytes()) +} + +pub fn marshal_app_data(msg: &ManualAppData) -> Result> { + let mut encoder = ProtoEncoder::new(); + encoder.encode_string(1, &msg.key); + encoder.encode_string(2, &msg.value); + Ok(encoder.into_bytes()) +} + +pub fn marshal_heartbeat_ping(msg: &ManualHeartbeatPing) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(stream_id) = msg.stream_id { + encoder.encode_int32(1, stream_id); + } + if let Some(last_stream) = msg.last_stream_id_received { + encoder.encode_int32(2, last_stream); + } + if let Some(status) = msg.status { + encoder.encode_int64(3, status); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_heartbeat_ack(msg: &ManualHeartbeatAck) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(stream_id) = msg.stream_id { + encoder.encode_int32(1, stream_id); + } + if let Some(last_stream) = msg.last_stream_id_received { + encoder.encode_int32(2, last_stream); + } + if let Some(status) = msg.status { + encoder.encode_int64(3, status); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_login_response(msg: &ManualLoginResponse) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(id) = &msg.id { + encoder.encode_string(1, id); + } + if let Some(jid) = &msg.jid { + encoder.encode_string(2, jid); + } + if let Some(error) = &msg.error { + let bytes = marshal_error_info(error)?; + encoder.encode_bytes(3, &bytes); + } + for setting in &msg.setting { + let bytes = marshal_setting(setting)?; + encoder.encode_bytes(5, &bytes); + } + if let Some(stream_id) = msg.stream_id { + encoder.encode_int32(7, stream_id); + } + if let Some(last_stream) = msg.last_stream_id_received { + encoder.encode_int32(8, last_stream); + } + if let Some(heartbeat) = &msg.heartbeat_config { + let bytes = marshal_heartbeat_config(heartbeat)?; + encoder.encode_bytes(9, &bytes); + } + if let Some(server_ts) = msg.server_timestamp { + encoder.encode_int64(10, server_ts); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_error_info(msg: &ManualErrorInfo) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(code) = msg.code { + encoder.encode_int32(1, code); + } + if let Some(message) = &msg.message { + encoder.encode_string(2, message); + } + if let Some(t) = &msg.error_type { + encoder.encode_string(3, t); + } + if let Some(ext) = &msg.extension { + let bytes = marshal_extension(ext)?; + encoder.encode_bytes(4, &bytes); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_extension(msg: &ManualExtension) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(id) = msg.id { + encoder.encode_int32(1, id); + } + if !msg.data.is_empty() { + encoder.encode_bytes(2, &msg.data); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_heartbeat_config(msg: &ManualHeartbeatConfig) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(upload) = msg.upload_stat { + encoder.encode_bool(1, upload); + } + if let Some(ip) = &msg.ip { + encoder.encode_string(2, ip); + } + if let Some(interval) = msg.interval_ms { + encoder.encode_int32(3, interval); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_close(_: &ManualClose) -> Result> { + Ok(Vec::new()) +} + +pub fn marshal_iq_stanza(msg: &ManualIqStanza) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(rmq) = msg.rmq_id { + encoder.encode_int64(1, rmq); + } + if let Some(stanza_type) = msg.stanza_type { + encoder.encode_int32(2, stanza_type as i32); + } + if let Some(id) = &msg.id { + encoder.encode_string(3, id); + } + if let Some(from) = &msg.from { + encoder.encode_string(4, from); + } + if let Some(to) = &msg.to { + encoder.encode_string(5, to); + } + if let Some(error) = &msg.error { + let bytes = marshal_error_info(error)?; + encoder.encode_bytes(6, &bytes); + } + if let Some(extension) = &msg.extension { + let bytes = marshal_extension(extension)?; + encoder.encode_bytes(7, &bytes); + } + if let Some(pid) = &msg.persistent_id { + encoder.encode_string(8, pid); + } + if let Some(stream_id) = msg.stream_id { + encoder.encode_int32(9, stream_id); + } + if let Some(last_stream) = msg.last_stream_id_received { + encoder.encode_int32(10, last_stream); + } + if let Some(account_id) = msg.account_id { + encoder.encode_int64(12, account_id); + } + if let Some(status) = msg.status { + encoder.encode_int64(13, status); + } + Ok(encoder.into_bytes()) +} + +pub fn marshal_stream_error_stanza(msg: &ManualStreamErrorStanza) -> Result> { + let mut encoder = ProtoEncoder::new(); + if let Some(t) = &msg.error_type { + encoder.encode_string(1, t); + } + if let Some(text) = &msg.text { + encoder.encode_string(2, text); + } + Ok(encoder.into_bytes()) +} diff --git a/vendor/fcm_receiver/src/messages/mod.rs b/vendor/fcm_receiver/src/messages/mod.rs new file mode 100644 index 0000000..5a34328 --- /dev/null +++ b/vendor/fcm_receiver/src/messages/mod.rs @@ -0,0 +1,9 @@ +mod builders; +mod marshal; +mod types; +mod unmarshal; + +pub use builders::*; +pub use marshal::*; +pub use types::*; +pub use unmarshal::*; diff --git a/vendor/fcm_receiver/src/messages/types.rs b/vendor/fcm_receiver/src/messages/types.rs new file mode 100644 index 0000000..0a3227c --- /dev/null +++ b/vendor/fcm_receiver/src/messages/types.rs @@ -0,0 +1,309 @@ +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ManualDeviceType { + AndroidOs = 1, + IosOs = 2, + ChromeBrowser = 3, + ChromeOs = 4, +} + +impl Default for ManualDeviceType { + fn default() -> Self { + ManualDeviceType::AndroidOs + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ManualChromeBuildPlatform { + Win = 1, + Mac = 2, + Linux = 3, + Cros = 4, + Ios = 5, + Android = 6, +} + +impl Default for ManualChromeBuildPlatform { + fn default() -> Self { + ManualChromeBuildPlatform::Linux + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ManualChromeBuildChannel { + Stable = 1, + Beta = 2, + Dev = 3, + Canary = 4, + Unknown = 5, +} + +impl Default for ManualChromeBuildChannel { + fn default() -> Self { + ManualChromeBuildChannel::Stable + } +} + +#[derive(Debug, Clone, Default)] +pub struct ManualChromeBuildProto { + pub platform: Option, + pub chrome_version: Option, + pub channel: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualAndroidCheckinProto { + pub last_checkin_msec: Option, + pub cell_operator: Option, + pub sim_operator: Option, + pub roaming: Option, + pub user_number: Option, + pub device_type: Option, + pub chrome_build: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualGservicesSetting { + pub name: Vec, + pub value: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualAndroidCheckinRequest { + pub imei: Option, + pub meid: Option, + pub mac_addr: Vec, + pub mac_addr_type: Vec, + pub serial_number: Option, + pub esn: Option, + pub id: Option, + pub logging_id: Option, + pub digest: Option, + pub locale: Option, + pub checkin: Option, + pub desired_build: Option, + pub market_checkin: Option, + pub account_cookie: Vec, + pub time_zone: Option, + pub security_token: Option, + pub version: Option, + pub ota_cert: Vec, + pub fragment: Option, + pub user_name: Option, + pub user_serial_number: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualAndroidCheckinResponse { + pub stats_ok: Option, + pub time_msec: Option, + pub digest: Option, + pub settings_diff: Option, + pub delete_setting: Vec, + pub setting: Vec, + pub market_ok: Option, + pub android_id: Option, + pub security_token: Option, + pub version_info: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualHeartbeatPing { + pub stream_id: Option, + pub last_stream_id_received: Option, + pub status: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualHeartbeatAck { + pub stream_id: Option, + pub last_stream_id_received: Option, + pub status: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualErrorInfo { + pub code: Option, + pub message: Option, + pub error_type: Option, + pub extension: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualSetting { + pub name: String, + pub value: String, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualHeartbeatStat { + pub ip: Option, + pub timeout: Option, + pub interval_ms: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualHeartbeatConfig { + pub upload_stat: Option, + pub ip: Option, + pub interval_ms: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ManualClientEventType { + Unknown = 0, + UnvisitMcs = 1, +} + +impl Default for ManualClientEventType { + fn default() -> Self { + ManualClientEventType::Unknown + } +} + +#[derive(Debug, Clone, Default)] +pub struct ManualClientEvent { + pub event_type: Option, + pub number_discarded_events: Option, + pub network_type: Option, + pub time_connection_started_ms: Option, + pub time_connection_ended_ms: Option, + pub error_code: Option, + pub time_connection_established_ms: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ManualLoginRequestAuthService { + AndroidId = 2, +} + +impl Default for ManualLoginRequestAuthService { + fn default() -> Self { + ManualLoginRequestAuthService::AndroidId + } +} + +#[derive(Debug, Clone, Default)] +pub struct ManualLoginRequest { + pub id: String, + pub domain: String, + pub user: String, + pub resource: String, + pub auth_token: String, + pub device_id: String, + pub last_rmq_id: Option, + pub setting: Vec, + pub received_persistent_id: Vec, + pub adaptive_heartbeat: Option, + pub heartbeat_stat: Option, + pub use_rmq2: Option, + pub account_id: Option, + pub auth_service: Option, + pub network_type: Option, + pub status: Option, + pub client_event: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualLoginResponse { + pub id: Option, + pub jid: Option, + pub error: Option, + pub setting: Vec, + pub stream_id: Option, + pub last_stream_id_received: Option, + pub heartbeat_config: Option, + pub server_timestamp: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualClose; + +#[derive(Debug, Clone, Default)] +pub struct ManualStreamErrorStanza { + pub error_type: Option, + pub text: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualExtension { + pub id: Option, + pub data: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ManualIqStanzaType { + Get = 0, + Set = 1, + Result = 2, + Error = 3, +} + +impl Default for ManualIqStanzaType { + fn default() -> Self { + ManualIqStanzaType::Get + } +} + +#[derive(Debug, Clone, Default)] +pub struct ManualIqStanza { + pub rmq_id: Option, + pub stanza_type: Option, + pub id: Option, + pub from: Option, + pub to: Option, + pub error: Option, + pub extension: Option, + pub persistent_id: Option, + pub stream_id: Option, + pub last_stream_id_received: Option, + pub account_id: Option, + pub status: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualAppData { + pub key: String, + pub value: String, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualDataMessageStanza { + pub id: Option, + pub from: Option, + pub to: Option, + pub category: Option, + pub token: Option, + pub app_data: Vec, + pub from_trusted_server: Option, + pub persistent_id: Option, + pub stream_id: Option, + pub last_stream_id_received: Option, + pub reg_id: Option, + pub device_user_id: Option, + pub ttl: Option, + pub sent: Option, + pub queued: Option, + pub status: Option, + pub raw_data: Option>, + pub immediate_ack: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ManualStreamAck; + +#[derive(Debug, Clone, Default)] +pub struct ManualSelectiveAck { + pub id: Vec, +} + +impl fmt::Display for ManualDataMessageStanza { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "ManualDataMessageStanza{{id={:?}, from={:?}, category={:?}}}", + self.id, self.from, self.category + ) + } +} diff --git a/vendor/fcm_receiver/src/messages/unmarshal.rs b/vendor/fcm_receiver/src/messages/unmarshal.rs new file mode 100644 index 0000000..cfd480f --- /dev/null +++ b/vendor/fcm_receiver/src/messages/unmarshal.rs @@ -0,0 +1,514 @@ +use crate::error::{Error, Result}; +use crate::proto::{ProtoDecoder, WireType}; + +use super::types::*; + +pub fn unmarshal_android_checkin_response(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualAndroidCheckinResponse::default(); + + while decoder.remaining() > 0 { + let (field_number, wire_type) = decoder.decode_field_number()?; + match field_number { + 1 => { + if wire_type != WireType::Varint { + return Err(Error::InvalidData("field 1 expects varint")); + } + msg.stats_ok = Some(decoder.decode_bool()?); + } + 2 => { + // Unknown/repeated message; skip for compatibility + decoder.skip_field(wire_type)?; + } + 3 => { + if wire_type != WireType::Varint { + decoder.skip_field(wire_type)?; + } else { + msg.time_msec = Some(decoder.decode_int64()?); + } + } + 4 => { + if wire_type == WireType::LengthDelimited { + msg.digest = Some(decoder.decode_string()?); + } else { + decoder.skip_field(wire_type)?; + } + } + 5 => { + if wire_type == WireType::LengthDelimited { + let bytes = decoder.decode_bytes()?; + let setting = unmarshal_gservices_setting(bytes)?; + msg.setting.push(setting); + } else { + decoder.skip_field(wire_type)?; + } + } + 6 => { + if wire_type == WireType::Varint { + msg.market_ok = Some(decoder.decode_bool()?); + } else { + decoder.skip_field(wire_type)?; + } + } + 7 => match wire_type { + WireType::Bit64 => { + msg.android_id = Some(decoder.decode_fixed64()?); + } + WireType::Varint => { + msg.android_id = Some(decoder.decode_uint64()?); + } + _ => decoder.skip_field(wire_type)?, + }, + 8 => match wire_type { + WireType::Bit64 => { + msg.security_token = Some(decoder.decode_fixed64()?); + } + WireType::Varint => { + msg.security_token = Some(decoder.decode_uint64()?); + } + _ => decoder.skip_field(wire_type)?, + }, + 9 => { + if wire_type == WireType::Varint { + msg.settings_diff = Some(decoder.decode_bool()?); + } else { + decoder.skip_field(wire_type)?; + } + } + 10 => { + if wire_type == WireType::LengthDelimited { + msg.delete_setting.push(decoder.decode_string()?); + } else { + decoder.skip_field(wire_type)?; + } + } + 11 => { + if wire_type == WireType::LengthDelimited { + msg.version_info = Some(decoder.decode_string()?); + } else { + decoder.skip_field(wire_type)?; + } + } + _ => decoder.skip_field(wire_type)?, + } + } + + Ok(msg) +} + +fn unmarshal_gservices_setting(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut setting = ManualGservicesSetting::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => { + if wire_type != WireType::LengthDelimited { + return Err(Error::InvalidData("field 1 expects bytes")); + } + setting.name = decoder.decode_bytes()?.to_vec(); + } + 2 => { + if wire_type != WireType::LengthDelimited { + return Err(Error::InvalidData("field 2 expects bytes")); + } + setting.value = decoder.decode_bytes()?.to_vec(); + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(setting) +} + +pub fn unmarshal_heartbeat_ping(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualHeartbeatPing::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => { + msg.stream_id = Some(decoder.decode_int32()?); + } + 2 => { + msg.last_stream_id_received = Some(decoder.decode_int32()?); + } + 3 => { + msg.status = Some(decoder.decode_int64()?); + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_heartbeat_ack(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualHeartbeatAck::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => { + msg.stream_id = Some(decoder.decode_int32()?); + } + 2 => { + msg.last_stream_id_received = Some(decoder.decode_int32()?); + } + 3 => { + msg.status = Some(decoder.decode_int64()?); + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_setting(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut setting = ManualSetting::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => { + setting.name = decoder.decode_string()?; + } + 2 => { + setting.value = decoder.decode_string()?; + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(setting) +} + +pub fn unmarshal_heartbeat_stat(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut stat = ManualHeartbeatStat::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => stat.ip = Some(decoder.decode_string()?), + 2 => stat.timeout = Some(decoder.decode_bool()?), + 3 => stat.interval_ms = Some(decoder.decode_int32()?), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(stat) +} + +pub fn unmarshal_client_event(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut event = ManualClientEvent::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => { + let value = decoder.decode_int32()?; + event.event_type = Some(match value { + 0 => ManualClientEventType::Unknown, + 1 => ManualClientEventType::UnvisitMcs, + _ => ManualClientEventType::Unknown, + }); + } + 100 => event.number_discarded_events = Some(decoder.decode_uint32()?), + 200 => event.network_type = Some(decoder.decode_int32()?), + 202 => event.time_connection_started_ms = Some(decoder.decode_uint64()?), + 203 => event.time_connection_ended_ms = Some(decoder.decode_uint64()?), + 204 => event.error_code = Some(decoder.decode_int32()?), + 300 => event.time_connection_established_ms = Some(decoder.decode_uint64()?), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(event) +} + +pub fn unmarshal_android_checkin_proto(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualAndroidCheckinProto::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 2 => msg.last_checkin_msec = Some(decoder.decode_int64()?), + 6 => msg.cell_operator = Some(decoder.decode_string()?), + 7 => msg.sim_operator = Some(decoder.decode_string()?), + 8 => msg.roaming = Some(decoder.decode_string()?), + 9 => msg.user_number = Some(decoder.decode_int32()?), + 12 => { + let val = decoder.decode_int32()?; + msg.device_type = Some(match val { + 1 => ManualDeviceType::AndroidOs, + 2 => ManualDeviceType::IosOs, + 3 => ManualDeviceType::ChromeBrowser, + 4 => ManualDeviceType::ChromeOs, + _ => ManualDeviceType::AndroidOs, + }); + } + 13 => { + let bytes = decoder.decode_bytes()?; + msg.chrome_build = Some(unmarshal_chrome_build_proto(bytes)?); + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_chrome_build_proto(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualChromeBuildProto::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => { + let val = decoder.decode_int32()?; + msg.platform = Some(match val { + 1 => ManualChromeBuildPlatform::Win, + 2 => ManualChromeBuildPlatform::Mac, + 3 => ManualChromeBuildPlatform::Linux, + 4 => ManualChromeBuildPlatform::Cros, + 5 => ManualChromeBuildPlatform::Ios, + 6 => ManualChromeBuildPlatform::Android, + _ => ManualChromeBuildPlatform::Linux, + }); + } + 2 => msg.chrome_version = Some(decoder.decode_string()?), + 3 => { + let val = decoder.decode_int32()?; + msg.channel = Some(match val { + 1 => ManualChromeBuildChannel::Stable, + 2 => ManualChromeBuildChannel::Beta, + 3 => ManualChromeBuildChannel::Dev, + 4 => ManualChromeBuildChannel::Canary, + 5 => ManualChromeBuildChannel::Unknown, + _ => ManualChromeBuildChannel::Stable, + }); + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_login_request(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualLoginRequest::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.id = decoder.decode_string()?, + 2 => msg.domain = decoder.decode_string()?, + 3 => msg.user = decoder.decode_string()?, + 4 => msg.resource = decoder.decode_string()?, + 5 => msg.auth_token = decoder.decode_string()?, + 6 => msg.device_id = decoder.decode_string()?, + 7 => msg.last_rmq_id = Some(decoder.decode_int64()?), + 8 => { + let bytes = decoder.decode_bytes()?; + msg.setting.push(unmarshal_setting(bytes)?); + } + 10 => msg.received_persistent_id.push(decoder.decode_string()?), + 12 => msg.adaptive_heartbeat = Some(decoder.decode_bool()?), + 13 => { + let bytes = decoder.decode_bytes()?; + msg.heartbeat_stat = Some(unmarshal_heartbeat_stat(bytes)?); + } + 14 => msg.use_rmq2 = Some(decoder.decode_bool()?), + 15 => msg.account_id = Some(decoder.decode_int64()?), + 16 => { + let val = decoder.decode_int32()?; + msg.auth_service = Some(match val { + 2 => ManualLoginRequestAuthService::AndroidId, + _ => ManualLoginRequestAuthService::AndroidId, + }); + } + 17 => msg.network_type = Some(decoder.decode_int32()?), + 18 => msg.status = Some(decoder.decode_int64()?), + 22 => { + let bytes = decoder.decode_bytes()?; + msg.client_event.push(unmarshal_client_event(bytes)?); + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_login_response(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualLoginResponse::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.id = Some(decoder.decode_string()?), + 2 => msg.jid = Some(decoder.decode_string()?), + 3 => { + let bytes = decoder.decode_bytes()?; + msg.error = Some(unmarshal_error_info(bytes)?); + } + 5 => { + let bytes = decoder.decode_bytes()?; + msg.setting.push(unmarshal_setting(bytes)?); + } + 7 => msg.stream_id = Some(decoder.decode_int32()?), + 8 => msg.last_stream_id_received = Some(decoder.decode_int32()?), + 9 => { + let bytes = decoder.decode_bytes()?; + msg.heartbeat_config = Some(unmarshal_heartbeat_config(bytes)?); + } + 10 => msg.server_timestamp = Some(decoder.decode_int64()?), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_error_info(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualErrorInfo::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.code = Some(decoder.decode_int32()?), + 2 => msg.message = Some(decoder.decode_string()?), + 3 => msg.error_type = Some(decoder.decode_string()?), + 4 => { + let bytes = decoder.decode_bytes()?; + msg.extension = Some(unmarshal_extension(bytes)?); + } + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_extension(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualExtension::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.id = Some(decoder.decode_int32()?), + 2 => msg.data = decoder.decode_bytes()?.to_vec(), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_heartbeat_config(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualHeartbeatConfig::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.upload_stat = Some(decoder.decode_bool()?), + 2 => msg.ip = Some(decoder.decode_string()?), + 3 => msg.interval_ms = Some(decoder.decode_int32()?), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_close(_data: &[u8]) -> Result { + Ok(ManualClose) +} + +pub fn unmarshal_iq_stanza(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualIqStanza::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.rmq_id = Some(decoder.decode_int64()?), + 2 => { + let raw = decoder.decode_int32()?; + msg.stanza_type = Some(match raw { + 0 => ManualIqStanzaType::Get, + 1 => ManualIqStanzaType::Set, + 2 => ManualIqStanzaType::Result, + 3 => ManualIqStanzaType::Error, + _ => ManualIqStanzaType::Get, + }); + } + 3 => msg.id = Some(decoder.decode_string()?), + 4 => msg.from = Some(decoder.decode_string()?), + 5 => msg.to = Some(decoder.decode_string()?), + 6 => { + let bytes = decoder.decode_bytes()?; + msg.error = Some(unmarshal_error_info(bytes)?); + } + 7 => { + let bytes = decoder.decode_bytes()?; + msg.extension = Some(unmarshal_extension(bytes)?); + } + 8 => msg.persistent_id = Some(decoder.decode_string()?), + 9 => msg.stream_id = Some(decoder.decode_int32()?), + 10 => msg.last_stream_id_received = Some(decoder.decode_int32()?), + 12 => msg.account_id = Some(decoder.decode_int64()?), + 13 => msg.status = Some(decoder.decode_int64()?), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_data_message_stanza(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualDataMessageStanza::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 2 => msg.id = Some(decoder.decode_string()?), + 3 => msg.from = Some(decoder.decode_string()?), + 4 => msg.to = Some(decoder.decode_string()?), + 5 => msg.category = Some(decoder.decode_string()?), + 6 => msg.token = Some(decoder.decode_string()?), + 7 => { + let bytes = decoder.decode_bytes()?; + msg.app_data.push(unmarshal_app_data(bytes)?); + } + 8 => msg.from_trusted_server = Some(decoder.decode_bool()?), + 9 => msg.persistent_id = Some(decoder.decode_string()?), + 10 => msg.stream_id = Some(decoder.decode_int32()?), + 11 => msg.last_stream_id_received = Some(decoder.decode_int32()?), + 13 => msg.reg_id = Some(decoder.decode_string()?), + 16 => msg.device_user_id = Some(decoder.decode_int64()?), + 17 => msg.ttl = Some(decoder.decode_int32()?), + 18 => msg.sent = Some(decoder.decode_int64()?), + 19 => msg.queued = Some(decoder.decode_int32()?), + 20 => msg.status = Some(decoder.decode_int64()?), + 21 => msg.raw_data = Some(decoder.decode_bytes()?.to_vec()), + 24 => msg.immediate_ack = Some(decoder.decode_bool()?), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_app_data(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualAppData::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.key = decoder.decode_string()?, + 2 => msg.value = decoder.decode_string()?, + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} + +pub fn unmarshal_stream_error_stanza(data: &[u8]) -> Result { + let mut decoder = ProtoDecoder::new(data); + let mut msg = ManualStreamErrorStanza::default(); + while decoder.remaining() > 0 { + let (field, wire_type) = decoder.decode_field_number()?; + match field { + 1 => msg.error_type = Some(decoder.decode_string()?), + 2 => msg.text = Some(decoder.decode_string()?), + _ => decoder.skip_field(wire_type)?, + } + } + Ok(msg) +} diff --git a/vendor/fcm_receiver/src/proto.rs b/vendor/fcm_receiver/src/proto.rs new file mode 100644 index 0000000..1c00a0c --- /dev/null +++ b/vendor/fcm_receiver/src/proto.rs @@ -0,0 +1,321 @@ +use crate::error::{ProtoError, ProtoErrorKind}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum WireType { + Varint = 0, + Bit64 = 1, + LengthDelimited = 2, + StartGroup = 3, + EndGroup = 4, + Bit32 = 5, +} + +impl WireType { + pub fn from_u8(value: u8) -> std::result::Result { + match value { + 0 => Ok(WireType::Varint), + 1 => Ok(WireType::Bit64), + 2 => Ok(WireType::LengthDelimited), + 3 => Ok(WireType::StartGroup), + 4 => Ok(WireType::EndGroup), + 5 => Ok(WireType::Bit32), + other => Err(ProtoError::with_context( + ProtoErrorKind::UnsupportedWireType(other), + "wire type", + )), + } + } +} + +#[derive(Debug, Default, Clone)] +pub struct ProtoEncoder { + buf: Vec, +} + +impl ProtoEncoder { + pub fn new() -> Self { + Self { buf: Vec::new() } + } + + pub fn into_bytes(self) -> Vec { + self.buf + } + + pub fn bytes(&self) -> &[u8] { + &self.buf + } + + pub fn clear(&mut self) { + self.buf.clear(); + } + + pub fn encode_field_number(&mut self, field_number: u32, wire_type: WireType) { + let key = ((field_number as u64) << 3) | (wire_type as u64); + self.encode_varint_internal(key); + } + + pub fn encode_varint_value(&mut self, value: u64) { + self.encode_varint_internal(value); + } + + pub fn encode_bool(&mut self, field_number: u32, value: bool) { + self.encode_field_number(field_number, WireType::Varint); + self.encode_varint_internal(value as u64); + } + + pub fn encode_int32(&mut self, field_number: u32, value: i32) { + self.encode_field_number(field_number, WireType::Varint); + self.encode_varint_internal(value as u64); + } + + pub fn encode_uint32(&mut self, field_number: u32, value: u32) { + self.encode_field_number(field_number, WireType::Varint); + self.encode_varint_internal(value as u64); + } + + pub fn encode_int64(&mut self, field_number: u32, value: i64) { + self.encode_field_number(field_number, WireType::Varint); + self.encode_varint_internal(value as u64); + } + + pub fn encode_uint64(&mut self, field_number: u32, value: u64) { + self.encode_field_number(field_number, WireType::Varint); + self.encode_varint_internal(value); + } + + pub fn encode_zigzag(&mut self, value: i64) { + let encoded = ((value << 1) ^ (value >> 63)) as u64; + self.encode_varint_internal(encoded); + } + + pub fn encode_string(&mut self, field_number: u32, value: &str) { + self.encode_field_number(field_number, WireType::LengthDelimited); + self.encode_varint_internal(value.len() as u64); + self.buf.extend_from_slice(value.as_bytes()); + } + + pub fn encode_bytes(&mut self, field_number: u32, value: &[u8]) { + self.encode_field_number(field_number, WireType::LengthDelimited); + self.encode_varint_internal(value.len() as u64); + self.buf.extend_from_slice(value); + } + + pub fn encode_fixed64(&mut self, field_number: u32, value: u64) { + self.encode_field_number(field_number, WireType::Bit64); + self.buf.extend_from_slice(&value.to_le_bytes()); + } + + pub fn encode_fixed32(&mut self, field_number: u32, value: u32) { + self.encode_field_number(field_number, WireType::Bit32); + self.buf.extend_from_slice(&value.to_le_bytes()); + } + + pub fn encode_float(&mut self, field_number: u32, value: f32) { + self.encode_fixed32(field_number, value.to_bits()); + } + + pub fn encode_double(&mut self, field_number: u32, value: f64) { + self.encode_fixed64(field_number, value.to_bits()); + } + + fn encode_varint_internal(&mut self, mut value: u64) { + while value >= 0x80 { + self.buf.push(((value as u8) & 0x7F) | 0x80); + value >>= 7; + } + self.buf.push(value as u8); + } +} + +#[derive(Debug, Clone)] +pub struct ProtoDecoder<'a> { + buf: &'a [u8], + pos: usize, +} + +impl<'a> ProtoDecoder<'a> { + pub fn new(buf: &'a [u8]) -> Self { + Self { buf, pos: 0 } + } + + pub fn reset(&mut self, buf: &'a [u8]) { + self.buf = buf; + self.pos = 0; + } + + pub fn remaining(&self) -> usize { + self.buf.len().saturating_sub(self.pos) + } + + pub fn decode_field_number(&mut self) -> std::result::Result<(u32, WireType), ProtoError> { + let (key, n) = self.decode_varint_raw()?; + let field_number = (key >> 3) as u32; + let wire_type = WireType::from_u8((key & 0x7) as u8)?; + self.pos += n; + Ok((field_number, wire_type)) + } + + pub fn decode_varint(&mut self) -> std::result::Result { + let (value, n) = self.decode_varint_raw()?; + self.pos += n; + Ok(value) + } + + pub fn decode_int32(&mut self) -> std::result::Result { + Ok(self.decode_varint()? as i32) + } + + pub fn decode_uint32(&mut self) -> std::result::Result { + Ok(self.decode_varint()? as u32) + } + + pub fn decode_int64(&mut self) -> std::result::Result { + Ok(self.decode_varint()? as i64) + } + + pub fn decode_uint64(&mut self) -> std::result::Result { + self.decode_varint() + } + + pub fn decode_bool(&mut self) -> std::result::Result { + Ok(self.decode_varint()? != 0) + } + + pub fn decode_string(&mut self) -> std::result::Result { + let len = self.decode_length()?; + let end = self + .pos + .checked_add(len) + .ok_or_else(|| ProtoError::new(ProtoErrorKind::InvalidLength))?; + if end > self.buf.len() { + return Err(ProtoError::new(ProtoErrorKind::InvalidLength)); + } + let slice = &self.buf[self.pos..end]; + self.pos = end; + String::from_utf8(slice.to_vec()) + .map_err(|_| ProtoError::with_context(ProtoErrorKind::InvalidLength, "string utf8")) + } + + pub fn decode_bytes(&mut self) -> std::result::Result<&'a [u8], ProtoError> { + let len = self.decode_length()?; + let end = self + .pos + .checked_add(len) + .ok_or_else(|| ProtoError::new(ProtoErrorKind::InvalidLength))?; + if end > self.buf.len() { + return Err(ProtoError::new(ProtoErrorKind::InvalidLength)); + } + let slice = &self.buf[self.pos..end]; + self.pos = end; + Ok(slice) + } + + pub fn decode_fixed64(&mut self) -> std::result::Result { + let end = self + .pos + .checked_add(8) + .ok_or_else(|| ProtoError::new(ProtoErrorKind::InvalidLength))?; + if end > self.buf.len() { + return Err(ProtoError::new(ProtoErrorKind::Eof)); + } + let value = u64::from_le_bytes(self.buf[self.pos..end].try_into().unwrap()); + self.pos = end; + Ok(value) + } + + pub fn decode_fixed32(&mut self) -> std::result::Result { + let end = self + .pos + .checked_add(4) + .ok_or_else(|| ProtoError::new(ProtoErrorKind::InvalidLength))?; + if end > self.buf.len() { + return Err(ProtoError::new(ProtoErrorKind::Eof)); + } + let value = u32::from_le_bytes(self.buf[self.pos..end].try_into().unwrap()); + self.pos = end; + Ok(value) + } + + pub fn skip_field(&mut self, wire_type: WireType) -> std::result::Result<(), ProtoError> { + match wire_type { + WireType::Varint => { + let (_, n) = self.decode_varint_raw()?; + self.pos += n; + Ok(()) + } + WireType::Bit64 => self.advance(8), + WireType::LengthDelimited => { + let len = self.decode_length()?; + self.advance(len) + } + WireType::StartGroup => self.skip_group(), + WireType::EndGroup => Ok(()), + WireType::Bit32 => self.advance(4), + } + } + + fn skip_group(&mut self) -> std::result::Result<(), ProtoError> { + let mut depth = 1; + while depth > 0 { + let (key, n) = self.decode_varint_raw()?; + self.pos += n; + let wire_type = WireType::from_u8((key & 0x7) as u8)?; + match wire_type { + WireType::StartGroup => depth += 1, + WireType::EndGroup => depth -= 1, + other => self.skip_field(other)?, + } + } + Ok(()) + } + + fn advance(&mut self, len: usize) -> std::result::Result<(), ProtoError> { + let end = self + .pos + .checked_add(len) + .ok_or_else(|| ProtoError::new(ProtoErrorKind::InvalidLength))?; + if end > self.buf.len() { + return Err(ProtoError::new(ProtoErrorKind::Eof)); + } + self.pos = end; + Ok(()) + } + + fn decode_length(&mut self) -> std::result::Result { + let (len, n) = self.decode_varint_raw()?; + self.pos += n; + len.try_into() + .map_err(|_| ProtoError::new(ProtoErrorKind::InvalidLength)) + } + + fn decode_varint_raw(&self) -> std::result::Result<(u64, usize), ProtoError> { + let mut x = 0u64; + let mut s = 0u32; + for (i, &b) in self.buf[self.pos..].iter().enumerate() { + if b < 0x80 { + if i == 9 && b > 1 { + return Err(ProtoError::new(ProtoErrorKind::InvalidVarint)); + } + x |= ((b & 0x7F) as u64) << s; + return Ok((x, i + 1)); + } + x |= ((b & 0x7F) as u64) << s; + s += 7; + if s >= 64 { + return Err(ProtoError::new(ProtoErrorKind::InvalidVarint)); + } + } + Err(ProtoError::new(ProtoErrorKind::Eof)) + } +} + +pub fn put_uvarint(mut x: u64) -> Vec { + let mut buf = Vec::new(); + while x >= 0x80 { + buf.push(((x as u8) & 0x7F) | 0x80); + x >>= 7; + } + buf.push(x as u8); + buf +} diff --git a/vendor/fcm_receiver/src/socket_handler.rs b/vendor/fcm_receiver/src/socket_handler.rs new file mode 100644 index 0000000..cfdc28a --- /dev/null +++ b/vendor/fcm_receiver/src/socket_handler.rs @@ -0,0 +1,253 @@ +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use crate::consts::*; +use crate::error::{Error, Result}; +type TlsStream = rustls::StreamOwned; + +fn tls_config() -> Arc { + let roots = rustls::RootCertStore { roots: webpki_roots::TLS_SERVER_ROOTS.to_vec() }; + let provider = Arc::new(rustls::crypto::ring::default_provider()); + Arc::new( + rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .expect("default TLS versions") + .with_root_certificates(roots) + .with_no_client_auth(), + ) +} + +pub struct SocketHandler { + socket: Option, + heartbeat_interval: Duration, + on_message: Option) -> Result<()> + Send + Sync>>, + buffer: Vec, + state: u8, + message_tag: u8, + message_size: usize, + last_heartbeat: Instant, +} + +impl SocketHandler { + pub fn new() -> Self { + Self { + socket: None, + heartbeat_interval: Duration::from_secs(600), + on_message: None, + buffer: Vec::new(), + state: MCS_VERSION_TAG_AND_SIZE, + message_tag: 0, + message_size: 0, + last_heartbeat: Instant::now(), + } + } + + pub fn connect(&mut self) -> Result<()> { + let stream = TcpStream::connect(FCM_SOCKET_ADDRESS).map_err(|e| { + Error::Other(format!( + "Failed to connect to {}: {}", + FCM_SOCKET_ADDRESS, e + )) + })?; + + stream + .set_nodelay(true) + .map_err(|e| Error::Other(format!("Failed to set TCP_NODELAY: {}", e)))?; + + let name = rustls::pki_types::ServerName::try_from("mtalk.google.com") + .map_err(|e| Error::Other(format!("Bad TLS server name: {}", e)))?; + let conn = rustls::ClientConnection::new(tls_config(), name) + .map_err(|e| Error::Other(format!("Failed to establish TLS connection: {}", e)))?; + let tls_stream = rustls::StreamOwned::new(conn, stream); + + self.socket = Some(tls_stream); + self.init(); + + Ok(()) + } + + pub fn start_socket_handler(&mut self) -> Result<()> { + loop { + while self.process_state_step()? {} + self.maybe_send_periodic_heartbeat()?; + self.read_from_socket()?; + } + } + + fn read_from_socket(&mut self) -> Result<()> { + let mut buffer = [0u8; 32 * 1024]; + let socket = self.socket_mut()?; + let bytes_read = socket + .read(&mut buffer) + .map_err(|e| Error::Other(format!("Failed to read from socket: {}", e)))?; + + if bytes_read == 0 { + return Err(Error::Other("Connection closed by peer".to_string())); + } + + self.buffer.extend_from_slice(&buffer[..bytes_read]); + Ok(()) + } + + fn process_state_step(&mut self) -> Result { + match self.state { + MCS_VERSION_TAG_AND_SIZE => { + if self.buffer.len() < VERSION_PACKET_LEN { + return Ok(false); + } + let version = self.buffer.remove(0); + if version < KMCS_VERSION && version != 38 { + return Err(Error::Other(format!("Invalid version: {}", version))); + } + self.state = MCS_TAG_AND_SIZE; + Ok(true) + } + MCS_TAG_AND_SIZE => { + if self.buffer.len() < TAG_PACKET_LEN { + return Ok(false); + } + self.message_tag = self.buffer.remove(0); + self.state = MCS_SIZE; + Ok(true) + } + MCS_SIZE => match Self::try_read_varint(&self.buffer)? { + Some((size, consumed)) => { + self.buffer.drain(0..consumed); + self.message_size = size; + if self.message_size == 0 { + self.dispatch_message(Vec::new())?; + self.state = MCS_TAG_AND_SIZE; + } else { + self.state = MCS_PROTO_BYTES; + } + Ok(true) + } + None => Ok(false), + }, + MCS_PROTO_BYTES => { + if self.buffer.len() < self.message_size { + return Ok(false); + } + let payload: Vec = self.buffer.drain(0..self.message_size).collect(); + self.dispatch_message(payload)?; + self.state = MCS_TAG_AND_SIZE; + Ok(true) + } + _ => Err(Error::Other(format!( + "Socket handler reached unexpected state ({})", + self.state + ))), + } + } + + fn dispatch_message(&mut self, payload: Vec) -> Result<()> { + if self.message_tag == K_HEARTBEAT_PING_TAG { + self.send_heartbeat_ping()?; + } + + if let Some(ref callback) = self.on_message { + callback(self.message_tag, payload)?; + } + + self.message_tag = 0; + self.message_size = 0; + Ok(()) + } + + fn maybe_send_periodic_heartbeat(&mut self) -> Result<()> { + if self.heartbeat_interval.as_secs() == 0 { + return Ok(()); + } + + if self.last_heartbeat.elapsed() >= self.heartbeat_interval { + self.send_heartbeat_ping()?; + self.last_heartbeat = Instant::now(); + } + + Ok(()) + } + + fn socket_mut(&mut self) -> Result<&mut TlsStream> { + self.socket + .as_mut() + .ok_or_else(|| Error::Other("Socket not connected".to_string())) + } + + fn try_read_varint(data: &[u8]) -> Result> { + let mut result = 0usize; + let mut shift = 0usize; + + for (idx, &byte) in data.iter().enumerate().take(SIZE_PACKET_LEN_MAX) { + result |= ((byte & 0x7F) as usize) << shift; + + if byte & 0x80 == 0 { + return Ok(Some((result, idx + 1))); + } + + shift += 7; + } + + if data.len() >= SIZE_PACKET_LEN_MAX { + return Err(Error::Other("Invalid varint encoding".to_string())); + } + + Ok(None) + } + + fn send_heartbeat_ping(&mut self) -> Result<()> { + let socket = self.socket_mut()?; + socket + .write_all(&[K_HEARTBEAT_PING_TAG, 0]) + .map_err(|e| Error::Other(format!("Failed to send heartbeat ping: {}", e)))?; + socket + .flush() + .map_err(|e| Error::Other(format!("Failed to flush socket: {}", e)))?; + Ok(()) + } + + pub fn send_login_handshake(&mut self, login_request: &[u8]) -> Result<()> { + let socket = self.socket_mut()?; + socket + .write_all(login_request) + .map_err(|e| Error::Other(format!("Failed to send login handshake: {}", e)))?; + socket + .flush() + .map_err(|e| Error::Other(format!("Failed to flush socket: {}", e)))?; + Ok(()) + } + + pub fn close(&mut self) { + if let Some(mut socket) = self.socket.take() { + socket.conn.send_close_notify(); + let _ = socket.flush(); + } + self.init(); + } + + pub fn set_on_message(&mut self, callback: F) + where + F: Fn(u8, Vec) -> Result<()> + Send + Sync + 'static, + { + self.on_message = Some(Arc::new(callback)); + } + + pub fn set_heartbeat_interval(&mut self, interval: Duration) { + self.heartbeat_interval = interval; + } + + fn init(&mut self) { + self.buffer.clear(); + self.state = MCS_VERSION_TAG_AND_SIZE; + self.message_tag = 0; + self.message_size = 0; + self.last_heartbeat = Instant::now(); + } +} + +impl Drop for SocketHandler { + fn drop(&mut self) { + self.close(); + } +} diff --git a/vendor/fcm_receiver/src/util.rs b/vendor/fcm_receiver/src/util.rs new file mode 100644 index 0000000..33d7379 --- /dev/null +++ b/vendor/fcm_receiver/src/util.rs @@ -0,0 +1,179 @@ +use crate::error::Result; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; +use base64::Engine; +use rand::rngs::OsRng; +use rand::RngCore; +use regex::Regex; + +pub fn generate_firebase_fid() -> Result { + let mut fid = [0u8; 17]; + OsRng.fill_bytes(&mut fid); + fid[0] = 0b0111_0000 | (fid[0] & 0b0000_1111); + Ok(BASE64_STANDARD.encode(fid)) +} + +pub fn contains(items: &[T], target: &T) -> bool { + items.iter().any(|item| item == target) +} + +pub fn remove_first(items: &mut Vec, target: &str) { + if let Some(pos) = items.iter().position(|item| item == target) { + items.remove(pos); + } +} + +pub fn parse_rupiah_nominal(text: &str) -> i64 { + // Cek apakah teks mengandung "qris-transaction" atau "transaction-in" (case-insensitive) + if !text.to_lowercase().contains("qris-transaction") + && !text.to_lowercase().contains("transaction-in") + { + return 0; + } + + // Regex untuk mencari pola "Rp" + optional space + angka (dengan atau tanpa titik ribuan) + let re = Regex::new(r"(?i)rp\s*([\d\.]+)").expect("Invalid regex"); + + for cap in re.captures_iter(text) { + if let Some(matched) = cap.get(1) { + let cleaned = matched.as_str().replace(".", ""); + if let Ok(nominal) = cleaned.parse::() { + return nominal; + } + } + } + + 0 // fallback jika tidak ditemukan nominal meskipun syarat keyword terpenuhi +} +pub fn terbilang(n: i64) -> String { + if n == 0 { + return "nol".to_string(); + } + + let mut result = String::new(); + let neg = if n < 0 { "minus " } else { "" }; + let n = n.abs(); + + // Satuan + let satuan = [ + "", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", + ]; + + // Belasan + let belasan = [ + "sepuluh", + "sebelas", + "dua belas", + "tiga belas", + "empat belas", + "lima belas", + "enam belas", + "tujuh belas", + "delapan belas", + "sembilan belas", + ]; + + // Puluhan + let puluhan = [ + "", + "sepuluh", + "dua puluh", + "tiga puluh", + "empat puluh", + "lima puluh", + "enam puluh", + "tujuh puluh", + "delapan puluh", + "sembilan puluh", + ]; + + fn process_chunk( + num: i64, + satuan: &[&str; 10], + belasan: &[&str; 10], + puluhan: &[&str; 10], + ) -> String { + let mut s = String::new(); + let ratusan = num / 100; + let sisa = num % 100; + + if ratusan > 0 { + if ratusan == 1 { + s.push_str("seratus"); + } else { + s.push_str(satuan[ratusan as usize]); + s.push_str(" ratus"); + } + if sisa > 0 { + s.push_str(" "); + } + } + + if sisa > 0 { + if sisa < 10 { + s.push_str(satuan[sisa as usize]); + } else if sisa < 20 { + s.push_str(belasan[(sisa - 10) as usize]); + } else { + let puluh = sisa / 10; + let sat = sisa % 10; + s.push_str(puluhan[puluh as usize]); + if sat > 0 { + s.push_str(" "); + s.push_str(satuan[sat as usize]); + } + } + } + + s + } + + let miliar = n / 1_000_000_000; + let sisa_miliar = n % 1_000_000_000; + + let juta = sisa_miliar / 1_000_000; + let sisa_juta = sisa_miliar % 1_000_000; + + let ribu = sisa_juta / 1_000; + let sisa_ribu = sisa_juta % 1_000; + + let mut parts = Vec::new(); + + if miliar > 0 { + let chunk = process_chunk(miliar, &satuan, &belasan, &puluhan); + parts.push(if chunk.is_empty() || chunk == "satu" { + "satu miliar".to_string() + } else { + format!("{} miliar", chunk) + }); + } + + if juta > 0 { + let chunk = process_chunk(juta, &satuan, &belasan, &puluhan); + parts.push(if chunk.is_empty() || chunk == "satu" { + "satu juta".to_string() + } else { + format!("{} juta", chunk) + }); + } + + if ribu > 0 { + let chunk = process_chunk(ribu, &satuan, &belasan, &puluhan); + parts.push(if chunk.is_empty() { + "seribu".to_string() + } else if chunk == "satu" { + "seribu".to_string() + } else { + format!("{} ribu", chunk) + }); + } + + if sisa_ribu > 0 { + let chunk = process_chunk(sisa_ribu, &satuan, &belasan, &puluhan); + parts.push(chunk); + } + + result.push_str(neg); + result.push_str(&parts.join(" ")); + + result +}