From d7f2fc1e143f85963a3a7136c2c7ec3ea697a50e Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Wed, 22 Apr 2026 09:31:16 +0200 Subject: [PATCH 01/33] feat: add proxy-core crate with shared types, MDD service resolver, and workspace setup Signed-off-by: Arvind Rathod --- Cargo.lock | 2341 +++++++++++++++++++++++++++- Cargo.toml | 61 +- README.md | 78 +- config.toml | 27 + deny.toml | 77 +- proxy-core/Cargo.toml | 34 + proxy-core/src/config.rs | 197 +++ proxy-core/src/diag_handler.rs | 35 + proxy-core/src/error.rs | 302 ++++ proxy-core/src/lib.rs | 27 + proxy-core/src/service_resolver.rs | 1633 +++++++++++++++++++ testcontainer/mdd/FLXC1000.mdd | Bin 0 -> 4891 bytes 12 files changed, 4740 insertions(+), 72 deletions(-) create mode 100644 config.toml create mode 100644 proxy-core/Cargo.toml create mode 100644 proxy-core/src/config.rs create mode 100644 proxy-core/src/diag_handler.rs create mode 100644 proxy-core/src/error.rs create mode 100644 proxy-core/src/lib.rs create mode 100644 proxy-core/src/service_resolver.rs create mode 100644 testcontainer/mdd/FLXC1000.mdd diff --git a/Cargo.lock b/Cargo.lock index 55e3925..42f3cf3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,5 +3,2344 @@ version = 4 [[package]] -name = "uds2sovd-proxy" +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "aide" +version = "0.16.0-alpha.1" +source = "git+https://github.com/alexmohr/aide.git?rev=56355cb#56355cbeb5a036cfaa35433b60717720350b4ad2" +dependencies = [ + "axum", + "bytes", + "cfg-if", + "http", + "indexmap", + "schemars", + "serde", + "serde_json", + "serde_qs", + "thiserror", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "sync_wrapper", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-extra" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be44683b41ccb9ab2d23a5230015c9c3c55be97a25e4428366de8873103f7970" +dependencies = [ + "axum", + "axum-core", + "bytes", + "futures-core", + "futures-util", + "headers", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cargo_toml" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77" +dependencies = [ + "serde", + "toml", +] + +[[package]] +name = "cc" +version = "1.2.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cda-build" +version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cda-core" +version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +dependencies = [ + "cda-database", + "cda-interfaces", + "cda-plugin-security", + "num-traits", + "parking_lot", + "schemars", + "serde", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "cda-database" +version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +dependencies = [ + "bytes", + "cargo_toml", + "cda-build", + "cda-interfaces", + "flatbuffers", + "memmap2", + "ouroboros", + "prost", + "prost-build", + "serde", + "serde_json", + "sha2", + "tokio", + "toml", + "tracing", + "uuid", + "xz2", +] + +[[package]] +name = "cda-interfaces" +version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +dependencies = [ + "async-trait", + "bytes", + "foldhash 0.2.0", + "hex", + "parking_lot", + "schemars", + "serde", + "serde_json", + "strum", + "strum_macros", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "cda-plugin-security" +version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +dependencies = [ + "aide", + "async-trait", + "axum", + "axum-extra", + "cda-database", + "cda-interfaces", + "http", + "jsonwebtoken", + "schemars", + "serde", + "serde_json", + "sovd-interfaces", + "thiserror", + "tracing", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "flatbuffers" +version = "25.9.23" +source = "git+https://github.com/alexmohr/flatbuffers.git?rev=0ba3307d#0ba3307d110a6def7419ad1158245cdf47c6d0c5" +dependencies = [ + "bitflags", + "rustc_version", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", + "wasip3", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" + +[[package]] +name = "headers" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" +dependencies = [ + "base64", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1", +] + +[[package]] +name = "headers-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" +dependencies = [ + "http", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", + "serde", + "serde_core", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "jsonwebtoken" +version = "10.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1" +dependencies = [ + "base64", + "ed25519-dalek", + "getrandom 0.2.17", + "hmac", + "js-sys", + "p256", + "p384", + "pem", + "rand", + "rsa", + "serde", + "serde_json", + "sha2", + "signature", + "simple_asn1", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "leb128fmt" version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.185" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "lzma-sys" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27" +dependencies = [ + "cc", + "libc", + "pkg-config", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "memmap2" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3" +dependencies = [ + "libc", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "ouroboros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" +dependencies = [ + "aliasable", + "ouroboros_macro", + "static_assertions", +] + +[[package]] +name = "ouroboros_macro" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn", +] + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "version_check", + "yansi", +] + +[[package]] +name = "prost" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" +dependencies = [ + "heck 0.5.0", + "itertools", + "log", + "multimap", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "prost-types" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" +dependencies = [ + "prost", +] + +[[package]] +name = "proxy-core" +version = "0.1.0" +dependencies = [ + "async-trait", + "cda-core", + "cda-database", + "cda-interfaces", + "cda-plugin-security", + "serde", + "serde_json", + "thiserror", + "tokio", + "toml", + "tracing", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schemars" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +dependencies = [ + "dyn-clone", + "indexmap", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_qs" +version = "1.0.0-rc.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cb0b9062a400c31442e67d1f2b1e7746bebd691110ebee1b7d0c7293b04fab1" +dependencies = [ + "axum", + "futures", + "itoa", + "percent-encoding", + "ryu", + "serde", + "thiserror", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "sovd-interfaces" +version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +dependencies = [ + "cda-interfaces", + "chrono", + "schemars", + "serde", + "serde_json", + "strum", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tokio" +version = "1.52.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow 1.0.2", +] + +[[package]] +name = "toml_writer" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "uuid" +version = "1.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" +dependencies = [ + "getrandom 0.4.2", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck 0.5.0", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck 0.5.0", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "xz2" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2" +dependencies = [ + "lzma-sys", +] + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml index 529569d..05bfb6f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,39 +8,60 @@ # terms of the Apache License Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0 -[package] -name = "uds2sovd-proxy" +[workspace.package] version = "0.1.0" edition = "2024" license = "Apache-2.0" homepage = "https://github.com/eclipse-opensovd/uds2sovd-proxy" -[lints] -workspace = true +[workspace] +resolver = "3" +members = [ + "proxy-core", +] + +[workspace.dependencies] +proxy-core = { path = "proxy-core" } +proxy-doip = { path = "proxy-doip" } +proxy-sovd = { path = "proxy-sovd" } +cda-core = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } +cda-database = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } +cda-interfaces = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } +cda-plugin-security = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } + +# ---- common crates ---- +async-trait = "0.1.89" +thiserror = "2.0.17" +serde = "1.0" +serde_json = "1.0" +tokio = { version = "1.48.0", default-features = false } +bytes = "1" +clap = "4.6.1" +toml = "0.9.8" + +# ---- networking crates ---- +reqwest = { version = "0.12.24", default-features = false } + +# ---- tracing & logging crates ---- +tracing = "0.1.41" +tracing-subscriber = { version = "0.3.20", default-features = false } -# Lints are aligned with shared-lints.toml from: -# https://github.com/eclipse-opensovd/cicd-workflows/tree/main/shared-lints [workspace.lints.clippy] # enable pedantic pedantic = { level = "warn", priority = -1 } ## exclude some too pedantic lints for now similar_names = "allow" -## lints related to runtime panic behavior -# enforce only checked access to slices to avoid runtime panics +# additional lints +clone_on_ref_ptr = "warn" indexing_slicing = "deny" -# disallow any unwraps in the production code -# (unwrap in test code is explicitly allowed) unwrap_used = "deny" -# enforce that arithmetic operations that can produce side effects always use -# either checked or explicit versions of the operations. eg. `.checked_add(...)` -# or `.saturating_sub(...)` to avoid unexpected runtime behavior or panics. arithmetic_side_effects = "deny" - -## lints related to readability of code -# enforce that references are cloned via eg. `Arc::clone` instead of `.clone()` -# making it explicit that a reference is cloned here and not the underlying data. -clone_on_ref_ptr = "warn" -# enforce that the type suffix of a literal is always appended directly -# eg. 12u8 instead of 12_u8 separated_literal_suffix = "deny" + +[workspace.lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(nightly)'] } + +[patch.crates-io] +aide = { git = "https://github.com/alexmohr/aide.git", rev = "56355cb" } +flatbuffers = { git = "https://github.com/alexmohr/flatbuffers.git", rev = "0ba3307d" } diff --git a/README.md b/README.md index 0cb94f5..b1f9528 100644 --- a/README.md +++ b/README.md @@ -33,22 +33,92 @@ SOVD-enabled vehicle architectures without modification. - ๐Ÿ›ก๏ธ safe & secure - โšก fast startup -## introduction +## features -### usage +- **MDD-Agnostic**: Works with any valid MDD file +- **DoIP Server**: ISO 13400-2 compliant, port configurable (default: `13400`) +- **SOVD Mapping**: UDS โ†” SOVD REST API conversion +- **Mock Gateway**: Built-in SOVD mock responses for testing +- **Service Resolution**: DID โ†’ service mapping via MDD (MUX map or brute-force) -### prerequisites +## prerequisites +To run the proxy you will need at least one `MDD` file. Check out [eclipse-opensovd/odx-converter](https://github.com/eclipse-opensovd/odx-converter) on how to create `MDD`(s) from ODX. + +Sample ODX/MDD files are available in the CDA repository: [testcontainer/odx](https://github.com/eclipse-opensovd/classic-diagnostic-adapter/tree/main/testcontainer/odx) + +Once you have the `MDD`(s) you can place them in `testcontainer/mdd/` or pass the path via `--mdd-dir`. ### build the executable +```shell +cargo build --release +``` + +### running + +Ensure that the config (`config.toml`) fits your setup: + +- `doip_port` is set to the desired DoIP server port (default: `13400`) +- `gateway_url` points to the SOVD gateway (CDA or mock) +- `mock_gateway = true` enables built-in mock responses for testing without a real CDA + +Run the proxy: + +```shell +cargo run --release -- --mdd-dir testcontainer/mdd +``` + +Or with a specific MDD file: + +```shell +cargo run --release -- --mdd-file FLXC1000.mdd +``` + +### running with SOVD Server + +To use the proxy with a real SOVD Server instance, set `mock_gateway = false` in `config.toml` and point `gateway_url` to the SOVD Server endpoint. + +## architecture + +``` +DoIP Client (port 13400) + โ†“ UDS request (0x22 DID) +Proxy (service resolution via MDD) + โ†“ SOVD REST (GET /data/vindataidentifier_read) +Mock Gateway OR Real CDA + โ†“ SOVD JSON response +Proxy (MDD-based UDS encoding) + โ†“ UDS response (0x62 DID data) +DoIP Client +``` + +## directory structure + +- `proxy-core/`: Shared types, errors, MDD engine, and `DiagHandler` trait +- `proxy-doip/`: DoIP transport layer (ISO 13400-2) โ€” server and session handling +- `proxy-sovd/`: SOVD REST client and UDS โ†” SOVD mapping +- `proxy-main/`: Binary entry point, CLI, configuration, and example clients +- `testcontainer/mdd/`: MDD files (FLXC1000.mdd) +- `proxy-main/examples/`: Test clients for each MDD + +## configuration + +Edit `config.toml`: + +- `doip_port = 13_400`: DoIP server port +- `mock_gateway = true`: Use built-in mock responses +- `gateway_url`: SOVD gateway endpoint +- MDD directory: `--mdd-dir testcontainer/mdd` (default) ## developing ### pre commit + ```shell uv run https://raw.githubusercontent.com/eclipse-opensovd/cicd-workflows/main/run_checks.py ``` + ### codestyle see [codestyle](CODESTYLE.md) @@ -58,6 +128,7 @@ see [codestyle](CODESTYLE.md) #### unit tests Unittests are placed in the relevant module as usual in rust: + ```rust ... #[cfg(test)] @@ -67,6 +138,7 @@ mod test { ``` Run unit tests with: + ```shell cargo test --locked --lib ``` diff --git a/config.toml b/config.toml new file mode 100644 index 0000000..8d6a2da --- /dev/null +++ b/config.toml @@ -0,0 +1,27 @@ +[server] +doip_port = 13_400 +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3_712 + + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "uds2sovd_proxy" +client_secret = "test_secret" +timeout_ms = 5_000 +mock_gateway = true +include_schema = false +api_version = "v15" + + +[ecu] +default_name = "AUTO_DETECT" +logical_address = 1 +eid = [ 0, 1, 2, 3, 4, 5 ] +gid = [ 0, 1, 2, 3, 4, 5 ] + + +[logging] +level = "debug" +format = "pretty" diff --git a/deny.toml b/deny.toml index 10e3516..639d194 100644 --- a/deny.toml +++ b/deny.toml @@ -1,78 +1,59 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) -# -# See the NOTICE file(s) distributed with this work for additional -# information regarding copyright ownership. -# -# This program and the accompanying materials are made available under the -# terms of the Apache License Version 2.0 which is available at -# https://www.apache.org/licenses/LICENSE-2.0 - [graph] -# TODO: add targets once the officially supported platforms are known. -# Leaving targets empty means cargo-deny checks all platforms in the dependency -# graph, which is the safest default. - all-features = false no-default-features = false + [output] feature-depth = 1 -# This section is considered when running `cargo deny check advisories` -# More documentation for the advisories section can be found here: -# https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html + [advisories] -ignore = [] +ignore = [ "RUSTSEC-2023-0071" ] -# This section is considered when running `cargo deny check licenses` -# More documentation for the licenses section can be found here: -# https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html -[licenses] -# List of explicitly allowed licenses -# See https://spdx.org/licenses/ for list of possible licenses -# [possible values: any SPDX 3.11 short identifier (+ optional exception)]. -allow = ["Apache-2.0", "MIT"] +[licenses] +allow = [ +"Apache-2.0", +"MIT", +"BSD-3-Clause", +"Zlib", +"ISC", +"Unicode-3.0", +"CDLA-Permissive-2.0" +] confidence-threshold = 0.9 -exceptions = [] +exceptions = [ ] + [licenses.private] ignore = true -registries = [] +registries = [ ] + -# This section is considered when running `cargo deny check bans`. -# More documentation about the 'bans' section can be found here: -# https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html [bans] multiple-versions = "warn" wildcards = "allow" highlight = "all" workspace-default-features = "allow" external-default-features = "allow" -allow = [] -deny = [] +allow = [ ] +deny = [ ] +skip = [ ] +skip-tree = [ ] -# Certain crates/versions that will be skipped when doing duplicate detection. -skip = [] -skip-tree = [] -# This section is considered when running `cargo deny check sources`. -# More documentation about the 'sources' section can be found here: -# https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html [sources] unknown-registry = "deny" unknown-git = "deny" -allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-registry = [ "https://github.com/rust-lang/crates.io-index" ] allow-git = [ - # Internal dependency - "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", - # TODO: Verify if below personal fork is necessary, it could break if the original repository is updated or fork no longer maintained - "https://github.com/alexmohr/aide.git", - "https://github.com/alexmohr/flatbuffers.git", +"https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", +"https://github.com/alexmohr/aide.git", +"https://github.com/alexmohr/flatbuffers.git" ] + [sources.allow-org] -github = [] -gitlab = [] -bitbucket = [] +github = [ ] +gitlab = [ ] +bitbucket = [ ] diff --git a/proxy-core/Cargo.toml b/proxy-core/Cargo.toml new file mode 100644 index 0000000..8933b87 --- /dev/null +++ b/proxy-core/Cargo.toml @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License Version 2.0 which is available at +# https://www.apache.org/licenses/LICENSE-2.0 + +[package] +name = "proxy-core" +version.workspace = true +edition.workspace = true +publish = false +description = "Shared types, errors, MDD engine, and DiagHandler trait for the UDS2SOVD proxy" +homepage.workspace = true +license.workspace = true + +[dependencies] +cda-core = { workspace = true } +cda-database = { workspace = true } +cda-interfaces = { workspace = true } +cda-plugin-security = { workspace = true } +async-trait = { workspace = true } +thiserror = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["full"] } +tracing = { workspace = true } +toml = { workspace = true } + +[lints] +workspace = true diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs new file mode 100644 index 0000000..b5b3b43 --- /dev/null +++ b/proxy-core/src/config.rs @@ -0,0 +1,197 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::error::{ProxyError, Result}; + +/// Required byte length for EID and GID fields per ISO 13400-2. +const EID_GID_BYTE_LENGTH: usize = 6; + +fn default_true() -> bool { + true +} + +/// Top-level proxy configuration loaded from a TOML file. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Config { + /// `DoIP` server settings (port, bind address, source address). + pub server: ServerConfig, + /// SOVD gateway connection settings. + pub sovd: SovdConfig, + /// ECU identity and addressing settings. + pub ecu: EcuConfig, + /// Logging configuration. + pub logging: LoggingConfig, +} + +/// TODO: `DoIP` server configuration. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ServerConfig { + /// TCP port for the `DoIP` server (default: 13400). + pub doip_port: u16, + /// IP address to bind the server socket to. + pub bind_address: String, + /// Maximum number of concurrent connections. + pub max_connections: usize, + /// `DoIP` source address used in response messages. + pub source_address: u16, +} + +/// SOVD gateway connection configuration. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SovdConfig { + /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). + pub gateway_url: String, + /// `OAuth2` client ID for gateway authentication. + pub client_id: String, + /// `OAuth2` client secret for gateway authentication. + pub client_secret: String, + /// HTTP request timeout in milliseconds. + pub timeout_ms: u64, + /// SOVD API version path segment (e.g. `v15`). + pub api_version: String, + /// Whether to request inline schema in data responses. + #[serde(default = "default_true")] + pub include_schema: bool, + /// When `true`, bypass HTTP calls and generate synthetic responses. + #[serde(default)] + pub mock_gateway: bool, +} + +/// ECU identity and addressing configuration. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EcuConfig { + /// Default ECU name used for SOVD component path. + pub default_name: String, + /// ISO 13400 logical address of the target ECU. + pub logical_address: u16, + /// 6-byte Entity Identification (MAC address). + pub eid: Vec, + /// 6-byte Group Identification. + pub gid: Vec, +} + +/// Logging output configuration. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LoggingConfig { + /// Log level filter (e.g. `info`, `debug`, `trace`). + pub level: String, + /// Output format: `pretty` (default) or `json`. + pub format: String, +} + +impl Config { + /// Load configuration from TOML file + /// + /// # Errors + /// Returns an error if the file cannot be read or parsed. + pub fn from_file>(path: P) -> Result { + let content = std::fs::read_to_string(path) + .map_err(|e| ProxyError::Config(format!("Failed to read config file: {e}")))?; + + toml::from_str(&content) + .map_err(|e| ProxyError::Config(format!("Failed to parse config: {e}"))) + } + + /// Validate configuration + /// + /// # Errors + /// Returns an error if the configuration is invalid. + /// + /// TODO(config): Validate `gateway_url` is a well-formed URL, not just + /// non-empty. Consider using the `url` crate for parsing. + /// TODO(config): Validate `api_version` matches expected pattern (e.g. `v\\d+`). + pub fn validate(&self) -> Result<()> { + if self.server.doip_port == 0 { + return Err(ProxyError::Config("Invalid DoIP port".to_string())); + } + + if self.sovd.gateway_url.is_empty() && !self.sovd.mock_gateway { + return Err(ProxyError::Config("SOVD gateway URL is empty".to_string())); + } + + if self.ecu.eid.len() != EID_GID_BYTE_LENGTH { + return Err(ProxyError::Config("EID must be 6 bytes".to_string())); + } + + if self.ecu.gid.len() != EID_GID_BYTE_LENGTH { + return Err(ProxyError::Config("GID must be 6 bytes".to_string())); + } + + if self.server.max_connections == 0 { + return Err(ProxyError::Config( + "max_connections must be greater than 0".to_string(), + )); + } + + if self.ecu.logical_address == 0 { + return Err(ProxyError::Config( + "ECU logical address must not be 0x0000".to_string(), + )); + } + + Ok(()) + } +} + +impl Default for Config { + fn default() -> Self { + Self { + server: ServerConfig { + doip_port: 13400, + bind_address: "0.0.0.0".to_string(), + max_connections: 10, + source_address: 0x0E80, + }, + sovd: SovdConfig { + gateway_url: "http://localhost:20002".to_string(), + client_id: "uds2sovd_proxy".to_string(), + client_secret: "test_secret".to_string(), + timeout_ms: 5000, + api_version: "v15".to_string(), + include_schema: true, + mock_gateway: false, + }, + ecu: EcuConfig { + default_name: "ECU".to_string(), + logical_address: 0x0001, + eid: vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05], + gid: vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05], + }, + logging: LoggingConfig { + level: "info".to_string(), + format: "pretty".to_string(), + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_default_config() { + let config = Config::default(); + assert_eq!(config.server.doip_port, 13400); + assert_eq!(config.sovd.api_version, "v15"); + } + + #[test] + fn test_validate_config() { + let config = Config::default(); + assert!(config.validate().is_ok()); + } +} diff --git a/proxy-core/src/diag_handler.rs b/proxy-core/src/diag_handler.rs new file mode 100644 index 0000000..7db75a7 --- /dev/null +++ b/proxy-core/src/diag_handler.rs @@ -0,0 +1,35 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use async_trait::async_trait; + +use crate::error::Result; + +/// Trait for processing UDS diagnostic requests through a backend. +#[async_trait] +pub trait DiagHandler: Send + Sync { + /// Process a `ReadDataByIdentifier` (0x22) request. + /// + /// `did` is the extracted 16-bit Data Identifier. + /// `uds_request` is the full UDS request bytes including the SID byte. + /// + /// Returns the complete UDS response bytes (positive or negative). + async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result>; + + /// Process a `WriteDataByIdentifier` (0x2E) request. + /// + /// `did` is the extracted 16-bit Data Identifier. + /// `uds_request` is the full UDS request bytes including the SID byte. + /// + /// Returns the complete UDS response bytes (positive or negative). + async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result>; +} diff --git a/proxy-core/src/error.rs b/proxy-core/src/error.rs new file mode 100644 index 0000000..81b40d7 --- /dev/null +++ b/proxy-core/src/error.rs @@ -0,0 +1,302 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use thiserror::Error; + +/// Top-level error type for the UDS-to-SOVD proxy. +/// +/// Covers `DoIP` transport errors, UDS protocol errors, SOVD communication +/// failures, configuration issues, and MDD database problems. +#[derive(Error, Debug)] +pub enum ProxyError { + #[error("DoIP protocol error: {0}")] + DoIp(String), + + #[error("UDS service error: {0}")] + Uds(#[from] UdsError), + + #[error("SOVD communication error: {0}")] + Sovd(#[from] SovdError), + + #[error("Configuration error: {0}")] + Config(String), + + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), + + #[error("Invalid request: {0}")] + InvalidRequest(String), + + #[error("Timeout waiting for response")] + Timeout, + + #[error("Internal error: {0}")] + Internal(String), + + #[error("MDD database error: {0}")] + Mdd(String), +} + +/// UDS protocol errors (ISO 14229). +#[derive(Error, Debug)] +pub enum UdsError { + #[error("Invalid service ID: 0x{0:02X}")] + InvalidServiceId(u8), + + #[error("Invalid DID: 0x{0:04X}")] + InvalidDid(u16), + + #[error("Invalid message length: expected {expected}, got {actual}")] + InvalidLength { expected: usize, actual: usize }, + + #[error("Negative response: NRC 0x{nrc:02X} ({description})")] + NegativeResponse { nrc: u8, description: String }, + + #[error("Unsupported service: 0x{0:02X}")] + UnsupportedService(u8), +} + +/// SOVD gateway communication errors. +#[derive(Error, Debug)] +pub enum SovdError { + #[error("HTTP request failed: {0}")] + Http(String), + + #[error("Authentication failed: {0}")] + Auth(String), + + #[error("Component not found: {0}")] + ComponentNotFound(String), + + #[error("Data identifier not found: {0}")] + DataIdNotFound(String), + + #[error("JSON parsing error: {0}")] + Json(#[from] serde_json::Error), + + #[error("Schema mismatch: {0}")] + SchemaMismatch(String), +} + +/// Convenience result type using [`ProxyError`]. +pub type Result = std::result::Result; + +/// UDS Negative Response Codes per ISO 14229-1 Table A.1. +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Nrc { + /// General reject + GeneralReject = 0x10, + /// Service not supported + ServiceNotSupported = 0x11, + /// Sub-function not supported + SubFunctionNotSupported = 0x12, + /// Incorrect message length or invalid format + IncorrectMessageLengthOrInvalidFormat = 0x13, + /// Response too long + ResponseTooLong = 0x14, + /// Busy - repeat request + BusyRepeatRequest = 0x21, + /// Conditions not correct + ConditionsNotCorrect = 0x22, + /// Request sequence error + RequestSequenceError = 0x24, + /// Request out of range + RequestOutOfRange = 0x31, + /// Security access denied + SecurityAccessDenied = 0x33, + /// Invalid key + InvalidKey = 0x35, + /// Exceeded number of attempts + ExceededNumberOfAttempts = 0x36, + /// Required time delay not expired + RequiredTimeDelayNotExpired = 0x37, + /// General programming failure + GeneralProgrammingFailure = 0x72, +} + +impl Nrc { + /// Returns a human-readable description of this NRC. + #[must_use] + pub fn description(&self) -> &'static str { + match self { + Self::GeneralReject => "General reject", + Self::ServiceNotSupported => "Service not supported", + Self::SubFunctionNotSupported => "Sub-function not supported", + Self::IncorrectMessageLengthOrInvalidFormat => { + "Incorrect message length or invalid format" + } + Self::ResponseTooLong => "Response too long", + Self::BusyRepeatRequest => "Busy - repeat request", + Self::ConditionsNotCorrect => "Conditions not correct", + Self::RequestSequenceError => "Request sequence error", + Self::RequestOutOfRange => "Request out of range", + Self::SecurityAccessDenied => "Security access denied", + Self::InvalidKey => "Invalid key", + Self::ExceededNumberOfAttempts => "Exceeded number of attempts", + Self::RequiredTimeDelayNotExpired => "Required time delay not expired", + Self::GeneralProgrammingFailure => "General programming failure", + } + } + + /// Convert a raw `u8` NRC value to the corresponding enum variant. + /// + /// Returns `None` for unrecognised NRC values. + #[must_use] + pub fn from_u8(value: u8) -> Option { + match value { + 0x10 => Some(Self::GeneralReject), + 0x11 => Some(Self::ServiceNotSupported), + 0x12 => Some(Self::SubFunctionNotSupported), + 0x13 => Some(Self::IncorrectMessageLengthOrInvalidFormat), + 0x14 => Some(Self::ResponseTooLong), + 0x21 => Some(Self::BusyRepeatRequest), + 0x22 => Some(Self::ConditionsNotCorrect), + 0x24 => Some(Self::RequestSequenceError), + 0x31 => Some(Self::RequestOutOfRange), + 0x33 => Some(Self::SecurityAccessDenied), + 0x35 => Some(Self::InvalidKey), + 0x36 => Some(Self::ExceededNumberOfAttempts), + 0x37 => Some(Self::RequiredTimeDelayNotExpired), + 0x72 => Some(Self::GeneralProgrammingFailure), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_nrc_from_u8_known_codes() { + assert_eq!(Nrc::from_u8(0x10), Some(Nrc::GeneralReject)); + assert_eq!(Nrc::from_u8(0x11), Some(Nrc::ServiceNotSupported)); + assert_eq!( + Nrc::from_u8(0x13), + Some(Nrc::IncorrectMessageLengthOrInvalidFormat) + ); + assert_eq!(Nrc::from_u8(0x31), Some(Nrc::RequestOutOfRange)); + assert_eq!(Nrc::from_u8(0x33), Some(Nrc::SecurityAccessDenied)); + assert_eq!(Nrc::from_u8(0x72), Some(Nrc::GeneralProgrammingFailure)); + } + + #[test] + fn test_nrc_from_u8_unknown_codes() { + assert_eq!(Nrc::from_u8(0x00), None); + assert_eq!(Nrc::from_u8(0xFF), None); + assert_eq!(Nrc::from_u8(0x50), None); + } + + #[test] + fn test_nrc_description() { + assert_eq!(Nrc::GeneralReject.description(), "General reject"); + assert_eq!( + Nrc::ServiceNotSupported.description(), + "Service not supported" + ); + assert_eq!(Nrc::RequestOutOfRange.description(), "Request out of range"); + } + + #[test] + fn test_nrc_repr_values() { + assert_eq!(Nrc::GeneralReject as u8, 0x10); + assert_eq!(Nrc::ServiceNotSupported as u8, 0x11); + assert_eq!(Nrc::SubFunctionNotSupported as u8, 0x12); + assert_eq!(Nrc::IncorrectMessageLengthOrInvalidFormat as u8, 0x13); + assert_eq!(Nrc::RequestOutOfRange as u8, 0x31); + assert_eq!(Nrc::SecurityAccessDenied as u8, 0x33); + } + + #[test] + fn test_nrc_roundtrip() { + let all_nrcs = [ + Nrc::GeneralReject, + Nrc::ServiceNotSupported, + Nrc::SubFunctionNotSupported, + Nrc::IncorrectMessageLengthOrInvalidFormat, + Nrc::ResponseTooLong, + Nrc::BusyRepeatRequest, + Nrc::ConditionsNotCorrect, + Nrc::RequestSequenceError, + Nrc::RequestOutOfRange, + Nrc::SecurityAccessDenied, + Nrc::InvalidKey, + Nrc::ExceededNumberOfAttempts, + Nrc::RequiredTimeDelayNotExpired, + Nrc::GeneralProgrammingFailure, + ]; + for nrc in &all_nrcs { + let byte = *nrc as u8; + assert_eq!(Nrc::from_u8(byte), Some(*nrc)); + assert!(!nrc.description().is_empty()); + } + } + + #[test] + fn test_proxy_error_display() { + let err = ProxyError::DoIp("connection failed".into()); + assert!(err.to_string().contains("connection failed")); + + let err = ProxyError::Config("invalid port".into()); + assert!(err.to_string().contains("invalid port")); + + let err = ProxyError::Timeout; + assert!(err.to_string().contains("Timeout")); + } + + #[test] + fn test_uds_error_display() { + let err = UdsError::InvalidServiceId(0xFF); + assert!(err.to_string().contains("0xFF")); + + let err = UdsError::InvalidDid(0xF190); + assert!(err.to_string().contains("0xF190")); + + let err = UdsError::InvalidLength { + expected: 3, + actual: 1, + }; + assert!(err.to_string().contains('3')); + assert!(err.to_string().contains('1')); + } + + #[test] + fn test_sovd_error_display() { + let err = SovdError::Auth("invalid token".into()); + assert!(err.to_string().contains("invalid token")); + + let err = SovdError::ComponentNotFound("ecu1".into()); + assert!(err.to_string().contains("ecu1")); + } + + #[test] + fn test_proxy_error_from_io() { + let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing"); + let proxy_err: ProxyError = io_err.into(); + assert!(matches!(proxy_err, ProxyError::Io(_))); + } + + #[test] + fn test_proxy_error_from_uds() { + let uds_err = UdsError::InvalidServiceId(0x00); + let proxy_err: ProxyError = uds_err.into(); + assert!(matches!(proxy_err, ProxyError::Uds(_))); + } + + #[test] + fn test_proxy_error_from_sovd() { + let sovd_err = SovdError::Auth("expired".into()); + let proxy_err: ProxyError = sovd_err.into(); + assert!(matches!(proxy_err, ProxyError::Sovd(_))); + } +} diff --git a/proxy-core/src/lib.rs b/proxy-core/src/lib.rs new file mode 100644 index 0000000..c73cd7d --- /dev/null +++ b/proxy-core/src/lib.rs @@ -0,0 +1,27 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! Core types and traits shared across all proxy crates. +//! +//! Defines configuration, error types, the [`DiagHandler`] trait for +//! pluggable backend implementations, and the MDD-driven +//! [`ServiceResolver`] for UDS request/response processing. + +pub mod config; +pub mod diag_handler; +pub mod error; +pub mod service_resolver; + +pub use config::Config; +pub use diag_handler::DiagHandler; +pub use error::{ProxyError, Result}; +pub use service_resolver::ServiceResolver; diff --git a/proxy-core/src/service_resolver.rs b/proxy-core/src/service_resolver.rs new file mode 100644 index 0000000..4d8fd67 --- /dev/null +++ b/proxy-core/src/service_resolver.rs @@ -0,0 +1,1633 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! ECU Manager wrapper for MDD-driven UDS request/response processing. +//! +//! Provides a simplified interface to the CDA's +//! `EcuManager` for encoding/decoding UDS messages using the loaded MDD +//! diagnostic database. +//! +//! ## Service resolution +//! +//! When a UDS request arrives the proxy must identify which diagnostic service +//! from the MDD it belongs to (e.g. `WDBI_VIN` vs `WDBI_PLAIN` for SID 0x2E). +//! +//! Resolution uses `lookup_diagcomms_by_request_prefix` with the full +//! `[SID, DID_HI, DID_LO]` prefix, which directly matches services whose +//! sequential coded-const parameters match the request bytes. This handles +//! CODED-CONST DID services in a single call. +//! +//! For services where the DID is not a coded constant (`PhysConst` / Value), +//! the prefix lookup returns all SID-matching services and the resolver +//! confirms the DID via request parameter metadata: +//! +//! - **`CodedConst`**: exact DID match. +//! - **`PhysConst`**: resolved `coded_value` or `create_uds_payload` probe. +//! - **Value**: `coded_default_value` or `CompuScale` range match. +//! +//! If no service matches, an error is logged โ€” no fallback. + +use std::sync::Arc; + +use cda_core::{DiagServiceResponseStruct, EcuManager as CdaEcuManager}; +use cda_database::datatypes::DiagnosticDatabase; +use cda_interfaces::{ + DiagComm, DiagCommType, DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, + EcuManagerType, FunctionalDescriptionConfig, HashMap, MuxCaseInfo, Protocol, + ServiceParameterMetadata, ServicePayload, UDS_ID_RESPONSE_BITMASK, + datatypes::{ComParams, DatabaseNamingConvention, DiagnosticServiceAffixPosition}, + diagservices::{DiagServiceResponse, DiagServiceResponseType, UdsPayloadData}, + service_ids, +}; +use cda_plugin_security::DefaultSecurityPluginData; +use tokio::sync::RwLock; + +/// Minimum UDS negative response length: 0x7F + SID + NRC. +const UDS_NEGATIVE_RESPONSE_MIN_LEN: usize = 3; + +/// Minimum UDS positive response buffer size: response SID (1) + DID high (1) + DID low (1). +const UDS_POSITIVE_RESPONSE_MIN_SIZE: usize = 3; + +/// Wraps the CDA's [`EcuManager`] with async locking +/// to provide MDD-driven UDS encoding, decoding, and service resolution +/// for the proxy. +pub struct ServiceResolver { + manager: Arc>>, + ecu_name: String, +} + +impl ServiceResolver { + /// Create new ECU manager from MDD database. + /// + /// # Arguments + /// * `ecu_name` - Name of the ECU + /// * `db` - Loaded `DiagnosticDatabase` from MDD file + /// * `logical_address` - ECU logical address (e.g. 0x1000) + /// * `tester_address` - Tester logical address (e.g. 0x0E80) + /// + /// # Errors + /// Returns an error if the ECU manager cannot be initialized from the database. + pub async fn new( + ecu_name: String, + db: DiagnosticDatabase, + logical_address: u16, + tester_address: u16, + ) -> Result { + let com_params = Self::default_com_params(logical_address, tester_address); + + let func_config = FunctionalDescriptionConfig { + description_database: String::new(), + enabled_functional_groups: None, + protocol_position: DiagnosticServiceAffixPosition::Prefix, + protocol_case_sensitive: false, + }; + + let mut manager = CdaEcuManager::new( + db, + Protocol::DoIp, + &com_params, + DatabaseNamingConvention::default(), + EcuManagerType::Ecu, + &func_config, + true, + ) + .map_err(|e| { + tracing::error!("Failed to create EcuManager: {}", e); + e + })?; + + Self::activate_base_variant(&mut manager).await?; + + Ok(Self { + manager: Arc::new(RwLock::new(manager)), + ecu_name, + }) + } + + /// Activate the base (fallback) ECU variant. + /// + /// The CDA's diagnostic engine requires a variant to be selected before + /// service lookup, metadata queries, or UDS encoding/decoding work + /// correctly. When no specific variant is requested (or the requested + /// variant is not found), this method seeds the engine with a synthetic + /// dummy response so that `detect_variant` initialises the internal + /// state-chart and pins the engine to a determinate base state. + /// + /// #`TODO:` real variant detection + /// + /// Replace the dummy response with actual variant-identification DID + /// reads from a live ECU connection: + /// 1. Read variant-identification DIDs from the ECU. + /// 2. Call `detect_variant(responses)` with real data. + /// 3. The engine narrows the active variant and limits visible services. + /// + /// # Errors + /// Returns an error only when `detect_variant` fails **and** no variant + /// name was set (i.e. the engine did not activate at all). + async fn activate_base_variant( + manager: &mut CdaEcuManager, + ) -> Result<(), DiagServiceError> { + // `TODO:` replace this dummy response with real variant-identification + // DID reads from the ECU (see doc comment above). + let dummy_response = DiagServiceResponseStruct { + service: DiagComm { + name: String::new(), + type_: DiagCommType::Data, + lookup_name: None, + }, + data: vec![], + mapped_data: None, + response_type: DiagServiceResponseType::Positive, + }; + + let mut responses: HashMap = HashMap::default(); + responses.insert("__variant_init__".to_string(), dummy_response); + + match manager.detect_variant(responses).await { + Ok(()) => Ok(()), + Err(e) => { + let variant = manager.variant(); + if variant.name.is_some() { + tracing::info!( + "Base variant '{}' activated (state chart init skipped: {})", + variant.name.as_deref().unwrap_or("unknown"), + e + ); + Ok(()) + } else { + Err(e) + } + } + } + } + + /// Build UDS response bytes from SOVD JSON data using MDD response metadata. + /// + /// Queries the POS-RESPONSE parameter layout from the MDD to determine exact + /// byte positions and sizes for each parameter. Each parameter is encoded + /// at its MDD-defined position: + /// + /// - **CODED-CONST**: fixed value written directly (e.g. response SID). + /// - **`MatchingRequestParam`**: DID bytes from the original request. + /// - **VALUE**: SOVD data value encoded with the correct byte width; + /// defaults to 0 when the key is not present in the SOVD response. + /// + /// Falls back to naive encoding if response metadata is unavailable. + /// + /// # Errors + /// Returns an error if the response cannot be encoded. + /// + /// # TODO: + /// Once the SOVD server returns properly structured responses, the naive + /// encoding fallback and the MDD-based `encode_response_from_metadata` + /// path can be removed โ€” the proxy will forward pre-encoded UDS bytes. + pub async fn build_response( + &self, + service_name: &str, + sid: u8, + did: u16, + response_data: HashMap, + ) -> Result, DiagServiceError> { + tracing::debug!( + "[MDD] Building UDS response for '{}' SID 0x{:02X} DID 0x{:04X}", + service_name, + sid, + did, + ); + + let (response, effective_service) = if let Some((r, svc)) = self + .encode_response_from_metadata(service_name, sid, did, &response_data) + .await + { + (r, svc) + } else { + // Fallback: naive encoding โ€” used when no response metadata is available. + tracing::debug!( + "[MDD] No response metadata for '{}', using naive encoding", + service_name + ); + let response_sid = sid.wrapping_add(UDS_ID_RESPONSE_BITMASK); + #[allow(clippy::cast_possible_truncation)] + let mut response = vec![response_sid, (did >> 8) as u8, (did & 0xFF) as u8]; + + let entries: Vec<_> = response_data + .iter() + .filter(|(k, _)| !k.eq_ignore_ascii_case("sid")) + .collect(); + + for (key, value) in entries { + match value { + serde_json::Value::String(s) => { + response.extend_from_slice(s.as_bytes()); + } + serde_json::Value::Number(n) => { + if let Some(num) = n.as_u64() { + response.extend(encode_unsigned_be(num)); + } else if let Some(num) = n.as_i64() { + let unsigned = num.cast_unsigned(); + #[allow(clippy::cast_possible_truncation)] + if u8::try_from(unsigned).is_ok() { + response.push(unsigned as u8); + } else { + response.push((unsigned >> 8) as u8); + response.push((unsigned & 0xFF) as u8); + } + } + } + serde_json::Value::Array(arr) => { + for item in arr { + #[allow(clippy::cast_possible_truncation)] + if let Some(byte) = item.as_u64() { + response.push(byte as u8); + } + } + } + serde_json::Value::Bool(b) => { + response.push(u8::from(*b)); + } + _ => { + tracing::warn!( + "[MDD] Skipping unsupported value type for '{}': {:?}", + key, + value + ); + } + } + } + + tracing::debug!("[MDD] Built UDS response (naive): {:02X?}", response); + (response, service_name.to_string()) + }; + + // Debug-only round-trip validation: parse the built bytes back through + // the CDA to confirm the MDD layout produces a decodable + // response. Uses the effective service name (which may be an enriched + // MUX sibling) so the CDA parses against the same structure we + // encoded with. + if tracing::enabled!(tracing::Level::DEBUG) { + self.validate_response(&effective_service, sid, &response) + .await; + } + + Ok(response) + } + + /// Round-trip validate UDS response bytes by parsing them back through + /// the CDA. + /// + /// Called only when `tracing::Level::DEBUG` is enabled โ€” failures are logged + /// as warnings but never block the response (non-blocking). + async fn validate_response(&self, service_name: &str, request_sid: u8, uds_response: &[u8]) { + let diag_comm = self.make_diag_comm(service_name, request_sid); + let payload = make_service_payload(uds_response); + let manager = self.manager.read().await; + match manager.convert_from_uds(&diag_comm, &payload, true).await { + Ok(parsed) => match parsed.into_json() { + Ok(json) => tracing::trace!( + "[MDD] Round-trip validation OK for '{}': {:?}", + service_name, + json.data + ), + Err(e) => tracing::warn!( + "[MDD] Round-trip validation: JSON decode failed for '{}': {}", + service_name, + e + ), + }, + Err(e) => tracing::warn!( + "[MDD] Round-trip validation: parse failed for '{}': {}", + service_name, + e + ), + } + } + + /// Encode a UDS response using POS-RESPONSE parameter metadata from the MDD. + /// + /// For each parameter in the MDD response structure: + /// - CODED-CONST (e.g. response SID at byte 0): writes the const value. + /// - `MatchingRequestParam` (e.g. DID at bytes 1-2): writes the DID. + /// - VALUE: uses the SOVD response data keyed by the MDD parameter name; + /// falls back to `0` when the key is absent. + /// + /// Returns `None` when no response metadata is available for the service. + /// On success returns the encoded bytes and the effective service name + /// (which may differ from `service_name` when enriched MUX sibling metadata + /// is used). + async fn encode_response_from_metadata( + &self, + service_name: &str, + _sid: u8, + did: u16, + response_data: &HashMap, + ) -> Option<(Vec, String)> { + let (meta, effective_service) = self + .get_enriched_response_metadata_with_source(service_name, did) + .await + .ok()?; + if meta.is_empty() { + return None; + } + + // Find the MUX case matching this DID (if any) using floor-based matching. + let mux_case_prefix = find_mux_case_prefix(&meta, did); + + // Derive the matching marker name for total_size computation. + let mux_marker_name: Option = mux_case_prefix + .as_deref() + .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + // Filter: keep top-level params (no '/') + matching MUX case VALUE params + // + the matching case marker (for total_size). + let active_params: Vec<_> = meta + .iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = &mux_case_prefix { + p.name.starts_with(prefix.as_str()) + || mux_marker_name.as_deref() == Some(&p.name) + } else { + !p.name.starts_with("__mux_case__/") + } + }) + .collect(); + + // Resolve effective size for each active param. For VALUE params with + // `byte_size: None` (variable-length DOPs like EndOfPdu), the size is + // inferred from the actual response data. + let effective_sizes: Vec = active_params + .iter() + .map(|p| { + if let Some(s) = p.byte_size { + return s as usize; + } + // Variable-size VALUE param โ€” infer size from the data. + if !matches!( + &p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + ) { + return 0; + } + let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); + let value = response_data + .get(&p.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + value_to_bytes(value).len() + }) + .collect(); + + // Determine total response size from filtered params. + let total_size = active_params + .iter() + .zip(effective_sizes.iter()) + .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) + .max() + .unwrap_or(UDS_POSITIVE_RESPONSE_MIN_SIZE); + + let mut response = vec![0u8; total_size]; + + for (param, &eff_size) in active_params.iter().zip(effective_sizes.iter()) { + // Skip MUX case markers โ€” they're only used for total_size computation. + if param.name.starts_with("__mux_case__/") { + continue; + } + let pos = param.byte_position as usize; + + if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { + continue; + } + + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // The SID byte is stored as a decimal string (e.g. "98" for 0x62). + if let Ok(val) = coded_value.parse::() { + let bytes = encode_unsigned_be(val); + let copy_len = bytes.len().min(eff_size); + // Right-align in the field (big-endian convention). + let offset = eff_size.saturating_sub(copy_len); + let dst_start = pos.saturating_add(offset); + let dst_end = dst_start.saturating_add(copy_len); + let src_start = bytes.len().saturating_sub(copy_len); + if let (Some(dst), Some(src)) = + (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) + { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { + // DID bytes from the original request, big-endian. + let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; + let copy_len = did_bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + did_bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // For MUX case params, try the short name (after '/') as well. + let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); + let value = response_data + .get(¶m.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + + if param.byte_size.is_some() { + encode_value_at(&mut response, pos, eff_size, value); + } else { + // Variable-size param: write the raw byte representation. + let bytes = value_to_bytes(value); + let copy_len = bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} + } + } + + tracing::debug!( + "[MDD] Built UDS response via metadata for '{}'): {:02X?}", + service_name, + response + ); + Some((response, effective_service)) + } + + /// `TODO:` to be removed, used in examples and debugging until the SOVD server returns + /// fully decoded responses. + /// Parse UDS response bytes using the MDD POS-RESPONSE structure. + /// + /// Delegates to CDA's `convert_from_uds` for decoding. Used by example + /// clients for response inspection and debugging. + /// + /// # Errors + /// Returns an error if the response cannot be parsed. + pub async fn parse_response( + &self, + service_name: &str, + request_sid: u8, + uds_response: &[u8], + ) -> Result, DiagServiceError> { + let diag_comm = self.make_diag_comm(service_name, request_sid); + let payload = make_service_payload(uds_response); + let manager = self.manager.read().await; + let response = manager.convert_from_uds(&diag_comm, &payload, true).await?; + let json_response = response.into_json()?; + + match json_response.data { + serde_json::Value::Object(map) => Ok(map), + serde_json::Value::Null => Ok(serde_json::Map::new()), + other => Err(DiagServiceError::InvalidRequest(format!( + "Expected JSON object in response, got: {other:?}" + ))), + } + } + + /// Parse UDS request bytes using the MDD request structure. + /// + /// # Errors + /// Returns an error if the request cannot be parsed. + pub async fn parse_request( + &self, + service_name: &str, + uds_request: &[u8], + ) -> Result, DiagServiceError> { + let service_id = uds_request.first().copied().unwrap_or(0x00); + let diag_comm = self.make_diag_comm(service_name, service_id); + let payload = make_service_payload(uds_request); + + let manager = self.manager.read().await; + let response = manager + .convert_request_from_uds(&diag_comm, &payload, true) + .await?; + let json_response = response.into_json()?; + + if let serde_json::Value::Object(map) = json_response.data { + tracing::debug!( + "[MDD] Parsed request for '{}': {} fields", + service_name, + map.len() + ); + Ok(map) + } else { + tracing::error!( + "[MDD] Expected JSON object in request, got: {:?}", + json_response.data + ); + Err(DiagServiceError::InvalidRequest( + "Expected JSON object in request".to_string(), + )) + } + } + + /// Retrieve request parameter metadata for a service. + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_service_parameter_metadata( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_request_parameter_metadata(service_name) + } + + /// Retrieve POS-RESPONSE parameter metadata (byte positions, sizes, types). + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_response_parameter_metadata( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_response_parameter_metadata(service_name) + } + + /// Retrieve enriched POS-RESPONSE metadata for a service + DID. + /// + /// Some services have a direct POS-RESPONSE + /// that references a STRUCTURE as a single opaque VALUE param (`byte_size` = + /// None, no sub-fields). The CDA doesn't flatten the STRUCTURE children in the + /// metadata for these services. + /// + /// However, a shared MUX-based response used by + /// sibling services DOES flatten every DID's sub-fields. This method + /// detects the opaque-STRUCTURE case and transparently returns the richer + /// MUX-based metadata instead, so callers get per-field byte positions. + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_enriched_response_metadata( + &self, + service_name: &str, + did: u16, + ) -> Result, DiagServiceError> { + self.get_enriched_response_metadata_with_source(service_name, did) + .await + .map(|(meta, _source)| meta) + } + + /// Same as [`get_enriched_response_metadata`] but also returns the name of + /// the service that actually provided the metadata. When the response is + /// "opaque" (single STRUCTURE ref) and a MUX-based sibling is used, the + /// returned name is the sibling โ€” callers that need to validate via + /// `convert_from_uds` must use this name, not the original. + /// + async fn get_enriched_response_metadata_with_source( + &self, + service_name: &str, + did: u16, + ) -> Result<(Vec, String), DiagServiceError> { + let manager = self.manager.read().await; + let meta = manager.get_response_parameter_metadata(service_name)?; + + // Heuristic: the response is "opaque" when the only data param + // (after SID + DID) is a single VALUE with byte_size = None. + let data_params: Vec<_> = meta + .iter() + .filter(|p| { + matches!( + p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + | cda_interfaces::ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + + let Some(first_param) = data_params.first() else { + return Ok((meta, service_name.to_string())); + }; + let is_opaque = data_params.len() == 1 + && first_param.byte_size.is_none() + && !first_param.name.contains('/'); + + if !is_opaque { + return Ok((meta, service_name.to_string())); + } + + tracing::debug!( + "[MDD] Response metadata for '{}' is opaque (single STRUCTURE ref '{}'), searching \ + for MUX-based sibling", + service_name, + first_param.name, + ); + + let security_plugin: DynamicPlugin = Box::new(()); + + // Search READ services for a MUX-based sibling with a case for this DID. + let candidates: Vec = manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect(); + + for candidate in &candidates { + if candidate == service_name { + continue; + } + let sibling_meta = match manager.get_response_parameter_metadata(candidate) { + Ok(m) if m.len() > meta.len() => m, + _ => continue, + }; + // Check if this sibling has a MUX case matching our DID (exact match + // to avoid cross-DOP false positives from floor matching). + let has_mux_for_did = has_mux_case_for_did_exact(&sibling_meta, did); + if has_mux_for_did { + tracing::debug!( + "[MDD] Using MUX-based metadata from '{}' for DID 0x{:04X} ({} params instead \ + of {})", + candidate, + did, + sibling_meta.len(), + meta.len(), + ); + return Ok((sibling_meta, candidate.clone())); + } + } + + // No MUX sibling found โ€” use original metadata. + Ok((meta, service_name.to_string())) + } + + /// Look up service names by SID. + /// + /// # Errors + /// Returns an error if the lookup fails. + pub async fn lookup_service_names_by_sid( + &self, + sid: u8, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + let security_plugin: DynamicPlugin = Box::new(()); + let names = if sid == service_ids::READ_DATA_BY_IDENTIFIER { + manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect() + } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { + manager + .get_components_configurations_info(&security_plugin) + .map(|v| v.into_iter().map(|c| c.id).collect()) + .unwrap_or_default() + } else { + Vec::new() + }; + Ok(names) + } + + /// Retrieve MUX case information for a service. + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_mux_cases_for_service( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_mux_cases_for_service(service_name) + } + + /// Resolve the best-matching READ service for UDS request bytes. + pub async fn resolve_read_service( + &self, + did: u16, + uds_bytes: &[u8], + ) -> Option<(String, serde_json::Map)> { + self.resolve_service(service_ids::READ_DATA_BY_IDENTIFIER, did, uds_bytes, "READ") + .await + } + + /// Resolve the best-matching WRITE service for UDS request bytes. + pub async fn resolve_write_service( + &self, + did: u16, + uds_bytes: &[u8], + ) -> Option<(String, serde_json::Map)> { + self.resolve_service( + service_ids::WRITE_DATA_BY_IDENTIFIER, + did, + uds_bytes, + "WRITE", + ) + .await + } + + /// Probe a service DID via request encoding for symbolic PHYS-CONST cases. + async fn probe_service_did( + manager: &CdaEcuManager, + service_name: &str, + sid: u8, + params: &[ServiceParameterMetadata], + ) -> Option { + let mut param_map: HashMap = HashMap::default(); + for param in params { + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // `?` is intentional: if any CodedConst can't be parsed we cannot + // build a valid probe request, so abort the entire probe. + let parsed = parse_u64_literal(coded_value)?; + param_map.insert(param.name.clone(), serde_json::json!(parsed)); + } + cda_interfaces::ParameterTypeMetadata::PhysConst { + phys_constant_value, + .. + } => { + param_map.insert(param.name.clone(), serde_json::json!(phys_constant_value)); + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // Use string probe value for VALUE params to satisfy DOPs that + // parse textual values (TEXTTABLE / string-typed fields). + param_map.insert(param.name.clone(), serde_json::json!("0")); + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} + } + } + + let diag_comm = DiagComm { + name: service_name.to_string(), + type_: diag_comm_type(sid), + lookup_name: Some(service_name.to_string()), + }; + let security_plugin: DynamicPlugin = Box::new(()); + + let payload = manager + .create_uds_payload( + &diag_comm, + &security_plugin, + Some(UdsPayloadData::ParameterMap(param_map)), + ) + .await + .ok()?; + + let probed_did = extract_did_from_uds(&payload.data)?; + // ISO 14229-1 ยง7.3.2: DID 0x0000 is reserved. A zero result means the + // Payload encoding produced a degenerate output (e.g. a TEXTTABLE + // lookup silently failed), so treat it as unresolvable rather than a match. + if probed_did == 0 { + None + } else { + Some(probed_did) + } + } + + /// Resolve a DID to a service name using prefix lookup and metadata. + /// + /// Uses `lookup_diagcomms_by_request_prefix` with the full `[SID, DID_HI, + /// DID_LO]` prefix for direct matching of CODED-CONST DID services. For + /// `PhysConst` / Value DID services (where only the SID is a coded constant), + /// confirms the match via request parameter metadata. + /// + /// # Parameters + /// * `sid` - UDS service identifier (e.g. 0x22 for RDBI, 0x2E for WDBI). + /// * `did` - 16-bit Data Identifier to resolve. + /// * `uds_bytes` - Raw incoming UDS request bytes. + /// * `label` - Log prefix string (e.g. `"READ"`, `"WRITE"`). + #[allow(clippy::cast_possible_truncation)] + async fn resolve_service_did( + &self, + sid: u8, + did: u16, + _uds_bytes: &[u8], + label: &str, + ) -> Option { + let manager = self.manager.read().await; + + // Step 1: Prefix lookup with [SID, DID_HI, DID_LO]. + // + // The CDA matches sequential coded-const parameters against the prefix: + // - CODED-CONST DID services -> only exact DID matches pass. + // - PhysConst / Value DID services -> only the SID byte is coded-const, + // so all services with matching SID pass through. + let did_prefix = [sid, (did >> 8) as u8, (did & 0xFF) as u8]; + let prefix_matches = manager + .lookup_diagcomms_by_request_prefix(&did_prefix) + .unwrap_or_default(); + + // Fast path: single match from prefix lookup (common case: unique DID). + if let [only] = prefix_matches.as_slice() { + let name = only.lookup_name.as_deref().unwrap_or(&only.name); + tracing::info!( + "[resolve_did] {} DID 0x{:04X} -> '{}' (prefix match)", + label, + did, + name + ); + return Some(name.to_owned()); + } + + // Step 2: Build deduplicated candidate list from prefix matches + + // supplementary sources (bypass NOT-INHERITED-DIAG-COMMS filter). + let mut seen = std::collections::HashSet::new(); + let mut candidates: Vec = Vec::new(); + + for dc in &prefix_matches { + let name = dc.lookup_name.as_deref().unwrap_or(&dc.name); + if seen.insert(name.to_owned()) { + candidates.push(name.to_owned()); + } + } + + let security_plugin: DynamicPlugin = Box::new(()); + let extra_names: Vec = if sid == service_ids::READ_DATA_BY_IDENTIFIER { + manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect() + } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { + manager + .get_components_configurations_info(&security_plugin) + .map(|v| v.into_iter().map(|c| c.id).collect()) + .unwrap_or_default() + } else { + Vec::new() + }; + for name in extra_names { + if seen.insert(name.clone()) { + candidates.push(name); + } + } + + if candidates.is_empty() { + tracing::warn!( + "[resolve_did] {} no services for SID 0x{:02X} DID 0x{:04X}", + label, + sid, + did + ); + return None; + } + + tracing::debug!( + "[resolve_did] {} SID 0x{:02X} DID 0x{:04X}", + label, + sid, + did, + ); + + // Step 3: Match DID against each candidate's request metadata. + for name in &candidates { + let Ok(meta) = manager.get_request_parameter_metadata(name) else { + continue; + }; + + let did_param = find_did_param(&meta, sid); + + let matched = match did_param.map(|p| &p.param_type) { + Some(cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value }) => { + parse_u64_literal(coded_value) == Some(u64::from(did)) + } + + Some(cda_interfaces::ParameterTypeMetadata::PhysConst { coded_value, .. }) => { + let resolved = match coded_value { + Some(cv) => Some(*cv as u16), + None => Self::probe_service_did(&manager, name, sid, &meta).await, + }; + resolved == Some(did) + } + + Some(cda_interfaces::ParameterTypeMetadata::Value { + coded_default_value, + compu_scales, + .. + }) => { + let default_ok = coded_default_value + .map(|cd| cd as u16 == did) + .unwrap_or(false); + let scales_ok = + !compu_scales.is_empty() && did_matches_compu_scales(compu_scales, did); + + default_ok || scales_ok + } + + None | Some(cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. }) => { + false + } + }; + + if matched { + tracing::info!("[resolve_did] {} DID 0x{:04X} -> '{}'", label, did, name); + return Some(name.clone()); + } + } + + tracing::error!( + "[resolve_did] {} no service found for DID 0x{:04X} (checked {} candidates)", + label, + did, + candidates.len() + ); + None + } + + /// Find the correct service for a given SID + DID. + /// + /// Delegates DID -> service resolution to [`resolve_service_did`] which uses + /// MDD metadata and probing (`CodedConst`, `PhysConst`, Value+MUX). Then attempts + /// parse-validation via `convert_request_from_uds` for the matched service. + async fn resolve_service( + &self, + sid: u8, + did: u16, + uds_bytes: &[u8], + label: &str, + ) -> Option<(String, serde_json::Map)> { + tracing::debug!("[MDD] {} DID 0x{:04X}", label, did); + + let service_name = self.resolve_service_did(sid, did, uds_bytes, label).await?; + + // Attempt parse-validation to extract structured parameter data. + let manager = self.manager.read().await; + let payload = make_service_payload(uds_bytes); + let diag_comm = DiagComm { + name: service_name.clone(), + type_: diag_comm_type(sid), + lookup_name: Some(service_name.clone()), + }; + + if let Ok(parsed) = manager + .convert_request_from_uds(&diag_comm, &payload, true) + .await + && let Ok(json_resp) = parsed.into_json() + && let serde_json::Value::Object(map) = json_resp.data + { + tracing::debug!( + "[MDD] {} DID 0x{:04X} -> '{}' (parse verified)", + label, + did, + service_name + ); + return Some((service_name, map)); + } + + // Parse failed โ€” still return the metadata-resolved service with empty map. + tracing::debug!( + "[MDD] {} DID 0x{:04X} -> '{}' (metadata match, parse unavailable)", + label, + did, + service_name + ); + Some((service_name, serde_json::Map::new())) + } + + /// Check if a UDS response is negative (SID 0x7F). + #[must_use] + pub fn is_negative_response(uds_response: &[u8]) -> bool { + uds_response.len() >= UDS_NEGATIVE_RESPONSE_MIN_LEN + && uds_response.first().copied() == Some(service_ids::NEGATIVE_RESPONSE) + } + + /// Extract NRC (Negative Response Code) from a negative response. + #[must_use] + pub fn get_nrc(uds_response: &[u8]) -> Option { + if Self::is_negative_response(uds_response) { + uds_response.get(2).copied() + } else { + None + } + } + + #[allow(clippy::unused_self)] + fn make_diag_comm(&self, service_name: &str, service_id: u8) -> DiagComm { + DiagComm { + name: service_name.to_string(), + type_: diag_comm_type(service_id), + lookup_name: Some(service_name.to_string()), + } + } + + /// Get ECU name. + #[must_use] + pub fn ecu_name(&self) -> &str { + &self.ecu_name + } + + fn default_com_params(logical_address: u16, tester_address: u16) -> ComParams { + let mut com_params = ComParams::default(); + com_params.doip.logical_gateway_address.default = logical_address; + com_params.doip.logical_ecu_address.default = logical_address; + com_params.doip.logical_tester_address.default = tester_address; + com_params + } +} + +// Helper functions + +/// Extract the 16-bit DID from UDS payload bytes at offset 1โ€“2. +/// +/// Returns `None` if the slice has fewer than 3 bytes. +fn extract_did_from_uds(data: &[u8]) -> Option { + let b1 = *data.get(1)?; + let b2 = *data.get(2)?; + Some(u16::from_be_bytes([b1, b2])) +} + +/// Map a UDS service identifier to its [`DiagCommType`]. +/// +/// Falls back to [`DiagCommType::Data`] for unrecognised SIDs so that the +/// caller always receives a usable type rather than an error. +fn diag_comm_type(service_id: u8) -> DiagCommType { + DiagCommType::try_from(service_id).unwrap_or(DiagCommType::Data) +} + +/// Create a `ServicePayload` from raw UDS bytes with default addresses. +fn make_service_payload(data: &[u8]) -> ServicePayload { + ServicePayload { + data: data.to_vec(), + source_address: 0, + target_address: 0, + new_session: None, + new_security: None, + } +} + +/// Encode an unsigned integer as big-endian bytes using the minimum width needed. +/// +/// Always produces at least one byte; zero encodes as `[0x00]`. +fn encode_unsigned_be(num: u64) -> Vec { + if num == 0 { + return vec![0x00]; + } + // Skip leading zero bytes; safe because num != 0 guarantees a non-empty result. + num.to_be_bytes() + .iter() + .copied() + .skip_while(|&b| b == 0) + .collect() +} + +/// Parse a MUX case `coded_value` string as a numeric DID value. +/// +/// MDD stores MUX case limits as strings that may be float-formatted +/// (e.g. `"61699.0"`) or integer-formatted (e.g. `"61699"`). +#[must_use] +pub fn parse_mux_coded_value(coded_value: &str) -> Option { + let trimmed = coded_value.trim(); + if let Ok(v) = trimmed.parse::() { + return Some(v); + } + #[allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss + )] + if let Ok(v) = trimmed.parse::() + && v >= 0.0 + && v <= u64::MAX as f64 + { + return Some(v as u64); + } + None +} + +/// Find the MUX case prefix that covers a given DID in response metadata. +/// +/// MDD `__mux_case__` entries store only the **`lower_limit`** of their range +/// (e.g. a case with `coded_value: "61697"` covering DIDs 0xF101 +/// through 0xF140). A DID like 0xF103 (61699) has no exact match +/// but falls in that range. +/// +/// This function uses **floor-based matching**: collect all `__mux_case__` +/// lower bounds, sort them, and find the case with the largest lower bound +/// that does not exceed the DID. This correctly handles both single-value +/// MUX cases (e.g. 0x7007) and range cases (e.g. 0xD100โ€“0xD150). +#[must_use] +pub fn find_mux_case_prefix( + meta: &[cda_interfaces::ResponseParameterInfo], + did: u16, +) -> Option { + let did_val = u64::from(did); + + // Collect (lower_bound, case_name) for all MUX case entries. + let mut mux_entries: Vec<(u64, &str)> = meta + .iter() + .filter_map(|p| { + let case_name = p.name.strip_prefix("__mux_case__/")?; + if let cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } = &p.param_type + { + let lower = parse_mux_coded_value(coded_value)?; + Some((lower, case_name)) + } else { + None + } + }) + .collect(); + + if mux_entries.is_empty() { + return None; + } + + // Sort by lower bound ascending. + mux_entries.sort_by_key(|&(lb, _)| lb); + + // Floor match: largest lower_bound โ‰ค DID. + let matched = mux_entries.iter().rev().find(|&&(lb, _)| lb <= did_val)?; + + Some(format!("{}/", matched.1)) +} + +/// Check if ANY MUX case in the response metadata **exactly** matches the DID. +/// +/// Uses exact (not floor) matching because this is for cross-service sibling +/// selection where different MUX DOPs can have overlapping ranges. +#[must_use] +pub fn has_mux_case_for_did_exact( + meta: &[cda_interfaces::ResponseParameterInfo], + did: u16, +) -> bool { + let did_val = u64::from(did); + meta.iter().any(|p| { + if let Some(_case_name) = p.name.strip_prefix("__mux_case__/") + && let cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } = &p.param_type + { + return parse_mux_coded_value(coded_value) == Some(did_val); + } + false + }) +} + +/// Parse numeric literals in decimal or hexadecimal form. +fn parse_u64_literal(value: &str) -> Option { + let trimmed = value.trim(); + if let Some(hex) = trimmed + .strip_prefix("0x") + .or_else(|| trimmed.strip_prefix("0X")) + { + return u64::from_str_radix(hex, 16).ok(); + } + + trimmed + .parse::() + .ok() + .or_else(|| u64::from_str_radix(trimmed, 16).ok()) +} + +/// Find the DID-bearing parameter by position and type, not by name. +/// +/// In standard UDS requests parameters are stored in byte order: +/// - First `CodedConst` whose value matches the SID -> SID indicator (skip) +/// - Next `CodedConst` / `PhysConst` / `Value` -> DID parameter +/// +/// This avoids vendor-specific name or semantic string matching. +fn find_did_param( + metadata: &[ServiceParameterMetadata], + sid: u8, +) -> Option<&ServiceParameterMetadata> { + let mut skipped_sid = false; + for p in metadata { + match &p.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + if !skipped_sid + && let Some(val) = parse_u64_literal(coded_value) + && val == u64::from(sid) + { + skipped_sid = true; + continue; + } + // Non-SID CodedConst -> DID param + return Some(p); + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } + | cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // PhysConst / Value -> DID param + return Some(p); + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} + } + } + None +} + +/// Check if a DID falls within any `CompuScale` range from the DOP metadata. +/// +/// For TEXTTABLE DOPs each scale defines a coded (internal) DID range. +/// Returns `true` if `did` falls in `[lower_limit, upper_limit]` of any scale. +fn did_matches_compu_scales(scales: &[cda_interfaces::CompuScaleInfo], did: u16) -> bool { + let did_val = u64::from(did); + scales.iter().any(|s| match (s.lower_limit, s.upper_limit) { + (Some(lo), Some(hi)) => did_val >= lo && did_val <= hi, + (Some(lo), None) => did_val == lo, + _ => false, + }) +} + +/// Encode a JSON value into `buf[pos..pos+size]` using big-endian representation. +/// +/// Handles numbers, strings, byte arrays, and booleans. Fills the entire +/// `size` field, zero-padding on the left for numbers shorter than `size`. +fn encode_value_at(buf: &mut [u8], pos: usize, size: usize, value: Option<&serde_json::Value>) { + if size == 0 { + return; + } + let Some(end) = pos.checked_add(size) else { + return; + }; + if end > buf.len() { + return; + } + let Some(value) = value else { + // No value provided โ€” leave as zero (already initialised). + return; + }; + match value { + serde_json::Value::Number(n) => { + let raw = n + .as_u64() + .unwrap_or_else(|| n.as_i64().unwrap_or(0).cast_unsigned()); + let be = raw.to_be_bytes(); + // Right-align in the field. + let u64_size = std::mem::size_of::(); + let start = u64_size.saturating_sub(size); + let copy = size.min(u64_size); + // end = pos + size; dst_start = end - copy = pos + (size - copy). + // copy <= size so no underflow. + let dst_start = end.saturating_sub(copy); + if let (Some(dst), Some(src)) = ( + buf.get_mut(dst_start..end), + be.get(start..start.saturating_add(copy)), + ) { + dst.copy_from_slice(src); + } + } + serde_json::Value::String(s) => { + let bytes = s.as_bytes(); + let copy = bytes.len().min(size); + if let (Some(dst), Some(src)) = ( + buf.get_mut(pos..pos.saturating_add(copy)), + bytes.get(..copy), + ) { + dst.copy_from_slice(src); + } + } + serde_json::Value::Array(arr) => { + for (i, item) in arr.iter().enumerate() { + if i >= size { + break; + } + if let Some(byte) = item.as_u64() + && let Some(slot) = buf.get_mut(pos.saturating_add(i)) + { + #[allow(clippy::cast_possible_truncation)] + { + *slot = byte as u8; + } + } + } + } + serde_json::Value::Bool(b) => { + if let Some(slot) = buf.get_mut(pos) { + *slot = u8::from(*b); + } + } + _ => {} + } +} + +/// Serialize a JSON value into raw bytes for UDS encoding. +/// +/// Returns an empty Vec when the value is None or cannot be serialized. +fn value_to_bytes(value: Option<&serde_json::Value>) -> Vec { + let Some(value) = value else { + return Vec::new(); + }; + match value { + serde_json::Value::Number(n) => { + let raw = n + .as_u64() + .unwrap_or_else(|| n.as_i64().unwrap_or(0).cast_unsigned()); + encode_unsigned_be(raw) + } + serde_json::Value::String(s) => s.as_bytes().to_vec(), + serde_json::Value::Array(arr) => arr + .iter() + .filter_map(|item| { + #[allow(clippy::cast_possible_truncation)] + item.as_u64().map(|b| b as u8) + }) + .collect(), + serde_json::Value::Bool(b) => vec![u8::from(*b)], + _ => Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_is_negative_response() { + assert!(!ServiceResolver::is_negative_response(&[0x62, 0xF1, 0x90])); + assert!(!ServiceResolver::is_negative_response(&[0x50, 0x01])); + assert!(ServiceResolver::is_negative_response(&[0x7F, 0x22, 0x31])); + assert!(!ServiceResolver::is_negative_response(&[0x7F])); + assert!(!ServiceResolver::is_negative_response(&[0x7F, 0x22])); + } + + #[test] + fn test_get_nrc() { + assert_eq!(ServiceResolver::get_nrc(&[0x62, 0xF1, 0x90]), None); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x31]), Some(0x31)); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x10, 0x11]), Some(0x11)); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x22]), Some(0x22)); + assert_eq!(ServiceResolver::get_nrc(&[0x7F]), None); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22]), None); + } + + #[test] + fn test_nrc_codes() { + let cases: &[(u8, u8, u8)] = &[ + (0x22, 0x11, 0x11), + (0x22, 0x12, 0x12), + (0x22, 0x13, 0x13), + (0x22, 0x22, 0x22), + (0x22, 0x31, 0x31), + (0x27, 0x33, 0x33), + (0x27, 0x35, 0x35), + (0x22, 0x78, 0x78), + ]; + for &(sid, nrc, expected) in cases { + assert_eq!(ServiceResolver::get_nrc(&[0x7F, sid, nrc]), Some(expected)); + } + } + + #[test] + fn test_positive_response_sids() { + assert!(!ServiceResolver::is_negative_response(&[ + 0x50, 0x01, 0x00, 0x32 + ])); + assert!(!ServiceResolver::is_negative_response(&[ + 0x62, 0xF1, 0x90, 0x57 + ])); + assert!(!ServiceResolver::is_negative_response(&[ + 0x67, 0x01, 0x12, 0x34 + ])); + assert!(!ServiceResolver::is_negative_response(&[0x6E, 0xF1, 0x90])); + assert!(!ServiceResolver::is_negative_response(&[0x7E, 0x00])); + } + + #[test] + fn test_default_com_params() { + let com_params = ServiceResolver::default_com_params(0x1000, 0x0E80); + assert_eq!(com_params.doip.logical_gateway_address.default, 0x1000); + assert_eq!(com_params.doip.logical_ecu_address.default, 0x1000); + assert_eq!(com_params.doip.logical_tester_address.default, 0x0E80); + assert_eq!( + com_params.doip.logical_gateway_address.name, + "CP_DoIPLogicalGatewayAddress" + ); + assert_eq!( + com_params.doip.logical_ecu_address.name, + "CP_DoIPLogicalEcuAddress" + ); + assert_eq!( + com_params.doip.logical_response_id_table_name, + "CP_UniqueRespIdTable" + ); + } + + #[test] + fn test_diag_comm_type() { + assert!(matches!( + diag_comm_type(service_ids::WRITE_DATA_BY_IDENTIFIER), + DiagCommType::Configurations + )); + assert!(matches!( + diag_comm_type(service_ids::READ_DATA_BY_IDENTIFIER), + DiagCommType::Data + )); + assert!(matches!( + diag_comm_type(service_ids::SESSION_CONTROL), + DiagCommType::Modes + )); + assert!(matches!( + diag_comm_type(service_ids::TESTER_PRESENT), + DiagCommType::Data + )); + assert!(matches!( + diag_comm_type(service_ids::ROUTINE_CONTROL), + DiagCommType::Operations + )); + assert!(matches!( + diag_comm_type(service_ids::CLEAR_DIAGNOSTIC_INFORMATION), + DiagCommType::Faults + )); + } + + #[test] + fn test_encode_unsigned_be() { + assert_eq!(encode_unsigned_be(0), vec![0x00]); + assert_eq!(encode_unsigned_be(0xFF), vec![0xFF]); + assert_eq!(encode_unsigned_be(0x0100), vec![0x01, 0x00]); + assert_eq!(encode_unsigned_be(0xF190), vec![0xF1, 0x90]); + assert_eq!(encode_unsigned_be(0xFFFF), vec![0xFF, 0xFF]); + assert_eq!(encode_unsigned_be(0x01_0000), vec![0x01, 0x00, 0x00]); + assert_eq!(encode_unsigned_be(0xFF_FFFF), vec![0xFF, 0xFF, 0xFF]); + assert_eq!( + encode_unsigned_be(0x0100_0000), + vec![0x01, 0x00, 0x00, 0x00] + ); + assert_eq!( + encode_unsigned_be(0xDEAD_BEEF), + vec![0xDE, 0xAD, 0xBE, 0xEF] + ); + } + + #[test] + fn test_make_service_payload() { + let data = &[0x62, 0xF1, 0x90, 0x57]; + let payload = make_service_payload(data); + assert_eq!(payload.data, vec![0x62, 0xF1, 0x90, 0x57]); + assert_eq!(payload.source_address, 0); + assert_eq!(payload.target_address, 0); + assert!(payload.new_session.is_none()); + assert!(payload.new_security.is_none()); + } + + #[test] + fn test_empty_response() { + assert!(!ServiceResolver::is_negative_response(&[])); + assert_eq!(ServiceResolver::get_nrc(&[]), None); + } + + #[test] + fn test_find_did_param() { + use cda_interfaces::ParameterTypeMetadata; + + // Standard RDBI: CodedConst SID + PhysConst DID + let meta = vec![ + ServiceParameterMetadata { + name: "RDBI".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), // 0x22 + }, + }, + ServiceParameterMetadata { + name: "VIN".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::PhysConst { + phys_constant_value: "VIN".to_string(), + coded_value: Some(0xF190), + }, + }, + ]; + let did = find_did_param(&meta, 0x22); + assert!(did.is_some()); + assert_eq!(did.expect("DID param not found").name, "VIN"); + + // Value-type service: SID + Value DID + let meta2 = vec![ + ServiceParameterMetadata { + name: "SID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), + }, + }, + ServiceParameterMetadata { + name: "DynamicDID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + }, + ]; + let did = find_did_param(&meta2, 0x22); + assert!(did.is_some()); + assert!(matches!( + did.expect("DID param not found").param_type, + ParameterTypeMetadata::Value { .. } + )); + + // SID-only service: no DID param + let meta3 = vec![ServiceParameterMetadata { + name: "SID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), + }, + }]; + assert!(find_did_param(&meta3, 0x22).is_none()); + } + + #[test] + fn test_parse_mux_coded_value() { + assert_eq!(parse_mux_coded_value("61699"), Some(61699)); + assert_eq!(parse_mux_coded_value("32776"), Some(32776)); + assert_eq!(parse_mux_coded_value("61699.0"), Some(61699)); + assert_eq!(parse_mux_coded_value(" 61699 "), Some(61699)); + assert_eq!(parse_mux_coded_value("non_numeric_text"), None); + assert_eq!(parse_mux_coded_value(""), None); + } + + #[test] + fn test_find_mux_case_prefix_floor_match() { + use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; + + // Simulate real RDBI_RESP metadata with range-based and point MUX cases. + let meta = vec![ + // Point case: DID_POINT_8008 covers only DID 0x8008 (32776) + ResponseParameterInfo { + name: "__mux_case__/DID_POINT_8008".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "32776".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + // Range case: DID_RANGE_F101_F140 covers 0xF101 (61697) through 0xF140 (61760) + ResponseParameterInfo { + name: "__mux_case__/DID_RANGE_F101_F140".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61697".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + // Point case: DID_POINT_F141 covers only 0xF141 (61761) + ResponseParameterInfo { + name: "__mux_case__/DID_POINT_F141".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61761".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + ]; + + // Exact match + assert_eq!( + find_mux_case_prefix(&meta, 0x8008), + Some("DID_POINT_8008/".to_string()) + ); + assert_eq!( + find_mux_case_prefix(&meta, 0xF101), + Some("DID_RANGE_F101_F140/".to_string()) + ); + assert_eq!( + find_mux_case_prefix(&meta, 0xF141), + Some("DID_POINT_F141/".to_string()) + ); + + // Floor match within range + assert_eq!( + find_mux_case_prefix(&meta, 0xF103), // 61699 -> floor to 61697 + Some("DID_RANGE_F101_F140/".to_string()) + ); + assert_eq!( + find_mux_case_prefix(&meta, 0xF140), // 61760 -> floor to 61697 + Some("DID_RANGE_F101_F140/".to_string()) + ); + + // Float-formatted coded_value + let meta_float = vec![ResponseParameterInfo { + name: "__mux_case__/case_a".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61697.0".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }]; + assert_eq!( + find_mux_case_prefix(&meta_float, 0xF103), + Some("case_a/".to_string()) + ); + + // No MUX entries -> None + assert_eq!(find_mux_case_prefix(&[], 0xF103), None); + } +} diff --git a/testcontainer/mdd/FLXC1000.mdd b/testcontainer/mdd/FLXC1000.mdd new file mode 100644 index 0000000000000000000000000000000000000000..cee0703d01eb5cb9788e166af99c53effefd1ef5 GIT binary patch literal 4891 zcmV+$6XfhoL_{EVWpZZ?GB7eVEio}IF*H;#IXW^kIx{dXI5;yfGdEf)777M) zZ*_8GWfBZVOjtuPFfcGKaAbHY4GITuaCB*JZgUa>dwnvMB@zfmOjtuPFfcGG1Z;Y3 zVKDG!LjNRP004jh|NsC0|NsC001N;#K?ALr#sz*Nj})EuOMfZr(EB~N{+Nkg#YT|I z)=-&Kc9N&3VVcjxNyIox{JSb>8+T*Y+P2MHiZn;JgtrZcow{{U8veZ^47U74*lGv7 z5Xk;t)~GF!nj4XV8ufmK9@01Zv7Oy;l%{hPG1&@#pR`nTMHfyj44S-BF^O6Yt@6SG zN0~Ir;SB=0Fgl=SE+gc|{luYsXoUQc4osSv8ZC!c%U5L0!>vam*k{W0P{ScL*>Isc~tAu#?`S7+jl zPAU=GgidCr-nW$T>dxFAPx&r@-$Zv-Oeg~aARPO)B8wQ+qWlFlfVjSn1ef`5hMR!x^e<{Fe&;m? z@ddq()0$h8vrjlJ?X+|&v~wq=VfRQxJE}Qs-$d~_RPoHqpPuHD)!gu@Q!FC*SC*C5 zQpt8^YELZY-J0f09-^LL5?=EBN;2hhXV##kE4t41bnv}`I&rT=54B(Dycd~O$zr`8p>n~0n2bi2${G^ z1%g%h77PC+PwG-M;Jrpr35md+RVN3D3*V<0=m`HiKKmPnw-6cg5X}i-Lk$CJ+nFqG z1G9rd71he?tdf67FL>VNApA$Xm@6;=aedn_hugc~wy&}hB1{+ige8P5%}B&$m)HqZ zo6gFjCWxSnRZbG|H}my~aN{3nJ}sM#`i-j`PM)@Bu2gpZkfRdk3|Il6RY6nn@*++(C36b&4RMyQdc|Tp+fdu_KI@QOtI|}=L-~n@#ZDdPWOv3`_SHh+-AdPRs zM|v`wk+ih)?!r@8Ei5WW% zUjqC$W;`fiCaHoC7Od-H=fWqYd5MI5{bY!?u!?$p{La$2&(Wn)O@M_9seB%E*I;S$ zI4Y$liDP`Jnm3fOYgTKe@V(|=tYEh>K5j5CwDWZdx{h_rz-#AjtTcNMRx@ks@4M*fqI2Ukf$rw`gt{VyA>8xMS{C#F1m0jHjO zjy<>CTv~g4SVcU@pjD}PG3d3!#Q!S2kL!o(;47!-$Y!sI4if3>5*AfDnt z91G0{B$K!<7N*YJKAq%*)l_OPc$3ffGSW}z{?bQ;^A52Q7dTNXidmLZ%@FRQQjF(G z`Z{3Ii8b?%v2>Q3c|wqw+r)o#YKhFcK6KJXwnj- z%pt_pH;4`@5=_aPqp0}N0ptj%)yiK6dWtCU|9~}!MOJ$V1gjm?nTnT|nrt8}puvA@ z^kQE5^6ORY{YOAB+m4v9CXR8X@U8u%whX+3TgqS9E-?52PZH z-|Z5qxV%F)q1X>Qh`<~w zj64{bNq&eN%N<)@3h;pi;vMe%s3|>XV77dEV+3RaaxrNOHBq=tQ}dM>Po)BdywA6L zdK0Jq=8sW4W8-^iARVvZqp~Od)$FSwR?@$O_W^vqEi?NQttJBEsg%C1K++mh$2zGG zr93d9$iV#Y%?$;kRz4-KvLLMPV+6<_a!>njUa-BE)txb#l)=$9rmY_NK3G#=WU7;kOxSz4UFoE;D)a?lHh@ z>q=Wuh!Z<-0ikA!h|kn2{G2}iEttO=q_Y5G4332K1sFMTn1Sq08s%$_lj{}L_CdrH z?qI#)kYR`txeD|mgo}+^Wgu{p9qxd)KkpopaRP$WZv!c`i%^Ji)!kju92?HrRyx61 zvb&c`gEOObpf+g~Jn*Zc?+ItcKUV~8Ho&61-1}6}%u~zeT`Tr_`Wbx8BWIatqxO79 z*|*N(-i76iZQsiLoTYgdoSx>$tdmjkU42YlllKu6eqd@zJ z-00MTH#-Y4Hs1ax1a0zF4^o&u)wwQ4B(ive;Rf^92~bPk+f2zwSC7|3>dGroG_iaP~2Sl@P&%o0qMC-yvv!%a3q={B$NT736pWV zQ?xyM>?TDM&A4tZ_(M!xc35|zTDsFY2Y%+$jTLetFY)Ks08)+%>)Ca38i5fQ4@}0X z{UmJBRp2tQ{Fe5X0Si4aRcb<=#opqP z$Cn}XEH(37viJ2n79;o32PvRVc3wcabG)X|ir_{bek@ z2ygq`4g8gzhc9Xywej=G+EaT(=G*Eh3I835q%$#Uw|SOgdq*}}jC23Q-kS3(5|!AV zk;#vBOQ5wQgmQ9^*Q@Blt@bc>NYkm(7`9&&)O_;(sZaI4ae3q5(zT_Md250)cux)} zA5XI=vHK2iXYR;cNY((fK-)xV$RMP`PxNJBI?gpP+U9g129Ksmri#3m3E7Qsd!jUko#@wvUY`0^*&6j;AGrDcct9D{$DVW9!O}Oz{p6oY zs&PlF#;3>rPjJu5Z022p;L?U;kMd3wb|pWS?ZO3n-n1vlixLsI3e_Re3rnO6`E_7C z0Q6+U_f9?`2upDV_4y~922v=XeLH4<@YL415MW*k%6#u zD_jtTHCEmxjm7h)M`hlx1ej#!9sG}Obl)@ilCZW$qV-(gbLY~*YoKPhX9-NB5#87}HLB0J1Qzh` zA*#uY#Qq(k-*vqHA=)c``7AgyoDj9;(P>6&uuO^bea_9g;8A?#GDz;U5BsmxAz7C6Hhk4+WZ zVV)W?f3`f|60}z=9ZV6*NK|_85&7V19Mjxaf2!J(q-M?Z5Y(2r8mOM>9%L7g^(d@l ztd;p0&UGIubIG-#HMY~{@B3foeZV2X=As`PHRfcQa`ER5=#**}oRkOts03zED`(C@ z;+Zd~-QGV?U?I_!PH>%c%%b~E#k&A^VPOV(Oy8C|C${Sm{|zmx1giGA8Af7Q$~MlK z%jsqA^ysYu-&bAg;L#7XjZ^6?x~W#1zH{pTD1_$Y#Q*Yfs;S(i`(5Anrvu;xJpprr zS|M@?r#vTs7lwbv7z&sx4Udr*80ZLmTEJSH+L@@O`?%p=mrQ|aSo&ZAWXW9iO;tjz zjQVqn(iM#D3|eo(;Qdi_RetB;Cn)XQu}oR-SktY~eEcK%*`J&lJH%p+)w`7ws?|ma z5ACDoAbftQQm*hi1{~q(=Li*_Pot|rF3zC1$yfddA^F5ZnAnaniDN(2U5tHGKzxn4 zREiGN3qQG*BvSKhM3aKW)4qs=ZY+2H-cs)04Sncm9{3$9p)c(f|+Gm0n>c^t}_ z;^sk$X3KxI!a%sR3+wN(!SP-rp&yL_QgR3-%wq4&m>W6(=Av6t`Ee`fQI z;tb4+nlow1j(oqW$JE&TTV?{&y~A7;N`nS=^e^L#-$zy*VA|g(pCC!N^sesH18Z*) zF`!xtXV2z^+)FUUdG&_p8;kU?YkdQTH5lk2^qKrTo^CU^%JuOLQF-;r8-1b5+-7QO}^UBQl=IHbMYD#r?g&P*Pm0=AdabVPWK5FHJd zHv(T?RD3d45sEaS#dnptyXu2u66l|u~uQZ0t3u(%hu@7xVG#8TgMMk#bl64=~GM7PL`RI*v z=zny1BvZUxO$@!%QRj(u%hp!Z9apCZu40E(_1zr0u~Y>j1Z>(s1E|HiEt462wQN|k z|EOxMW{+7P4lP0(6Ipg1@whEqbgc8akz^&>NrHvF{Vh&!T&K81|gLfD`+bi^z9;zz{{0OoN>pR5Ofp_egC4>QEo)0F1KlTs*Bjs>5cUj NjceH Date: Wed, 22 Apr 2026 09:51:45 +0200 Subject: [PATCH 02/33] PR1: Add proxy-core to workspace members --- Cargo.lock | 882 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 864 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 42f3cf3..e29a9a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,12 @@ dependencies = [ "syn", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.0" @@ -299,6 +305,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + [[package]] name = "chrono" version = "0.4.44" @@ -340,7 +352,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", - "rand_core", + "rand_core 0.6.4", "subtle", "zeroize", ] @@ -414,6 +426,17 @@ dependencies = [ "subtle", ] +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "dyn-clone" version = "1.0.20" @@ -479,7 +502,7 @@ dependencies = [ "hkdf", "pem-rfc7468", "pkcs8", - "rand_core", + "rand_core 0.6.4", "sec1", "subtle", "zeroize", @@ -498,7 +521,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -513,7 +536,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -556,6 +579,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures" version = "0.3.32" @@ -662,8 +694,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", ] [[package]] @@ -674,7 +722,7 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", "wasip2", "wasip3", ] @@ -686,7 +734,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -798,12 +846,77 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "httparse" +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 = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -828,12 +941,115 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + [[package]] name = "id-arena" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indexmap" version = "2.14.0" @@ -846,6 +1062,22 @@ dependencies = [ "serde_core", ] +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "itertools" version = "0.14.0" @@ -867,6 +1099,8 @@ version = "0.3.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" dependencies = [ + "cfg-if", + "futures-util", "once_cell", "wasm-bindgen", ] @@ -885,7 +1119,7 @@ dependencies = [ "p256", "p384", "pem", - "rand", + "rand 0.8.6", "rsa", "serde", "serde_json", @@ -927,6 +1161,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + [[package]] name = "lock_api" version = "0.4.14" @@ -942,6 +1182,12 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "lzma-sys" version = "0.1.20" @@ -988,7 +1234,7 @@ checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1018,7 +1264,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand", + "rand 0.8.6", "smallvec", "zeroize", ] @@ -1205,6 +1451,15 @@ version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -1329,6 +1584,75 @@ dependencies = [ "tracing", ] +[[package]] +name = "proxy-sovd" +version = "0.1.0" +dependencies = [ + "async-trait", + "cda-interfaces", + "proxy-core", + "reqwest", + "serde", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.4", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + [[package]] name = "quote" version = "1.0.45" @@ -1338,6 +1662,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -1351,8 +1681,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", ] [[package]] @@ -1362,7 +1702,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -1374,6 +1724,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1432,6 +1791,44 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -1442,6 +1839,20 @@ dependencies = [ "subtle", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rsa" version = "0.9.10" @@ -1455,13 +1866,19 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", "signature", "spki", "subtle", "zeroize", ] +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + [[package]] name = "rustc_version" version = "0.4.1" @@ -1481,7 +1898,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f9466fb2c14ea04357e91413efb882e2a6d4a406e625449bc0a5d360d53a21" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -1637,6 +2089,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1" version = "0.10.6" @@ -1682,7 +2146,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1716,7 +2180,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1748,6 +2212,12 @@ dependencies = [ "der", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "static_assertions" version = "1.1.0" @@ -1797,6 +2267,20 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "tempfile" @@ -1808,7 +2292,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1862,6 +2346,31 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" version = "1.52.1" @@ -1876,7 +2385,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1890,6 +2399,16 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -1939,6 +2458,25 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", "tower-layer", "tower-service", ] @@ -1986,6 +2524,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.0" @@ -2004,6 +2548,30 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "uuid" version = "1.23.1" @@ -2021,6 +2589,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2058,6 +2635,16 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.118" @@ -2124,6 +2711,35 @@ dependencies = [ "semver", ] +[[package]] +name = "web-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -2183,6 +2799,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -2192,6 +2826,135 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.7.15" @@ -2298,6 +3061,12 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + [[package]] name = "xz2" version = "0.1.7" @@ -2313,6 +3082,29 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.48" @@ -2333,12 +3125,66 @@ dependencies = [ "syn", ] +[[package]] +name = "zerofrom" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + [[package]] name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zmij" version = "1.0.21" From da5fa2c75bd42d3964fa2a10f62f77f32ed949cc Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Wed, 22 Apr 2026 10:58:06 +0200 Subject: [PATCH 03/33] Restore comments and original structure to Cargo.toml and deny.toml --- Cargo.lock | 882 ++--------------------------------------------------- Cargo.toml | 18 +- deny.toml | 33 ++ 3 files changed, 67 insertions(+), 866 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e29a9a5..42f3cf3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,12 +63,6 @@ dependencies = [ "syn", ] -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - [[package]] name = "autocfg" version = "1.5.0" @@ -305,12 +299,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - [[package]] name = "chrono" version = "0.4.44" @@ -352,7 +340,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", - "rand_core 0.6.4", + "rand_core", "subtle", "zeroize", ] @@ -426,17 +414,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "dyn-clone" version = "1.0.20" @@ -502,7 +479,7 @@ dependencies = [ "hkdf", "pem-rfc7468", "pkcs8", - "rand_core 0.6.4", + "rand_core", "sec1", "subtle", "zeroize", @@ -521,7 +498,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -536,7 +513,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "rand_core 0.6.4", + "rand_core", "subtle", ] @@ -579,15 +556,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - [[package]] name = "futures" version = "0.3.32" @@ -694,24 +662,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", - "js-sys", "libc", "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 5.3.0", - "wasip2", - "wasm-bindgen", ] [[package]] @@ -722,7 +674,7 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", - "r-efi 6.0.0", + "r-efi", "wasip2", "wasip3", ] @@ -734,7 +686,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", - "rand_core 0.6.4", + "rand_core", "subtle", ] @@ -846,77 +798,12 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "httparse" -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 = "hyper" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "http", - "http-body", - "httparse", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "tokio", - "tokio-rustls", - "tower-service", - "webpki-roots", -] - -[[package]] -name = "hyper-util" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" -dependencies = [ - "base64", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - [[package]] name = "iana-time-zone" version = "0.1.65" @@ -941,115 +828,12 @@ dependencies = [ "cc", ] -[[package]] -name = "icu_collections" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" - -[[package]] -name = "icu_properties" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - [[package]] name = "id-arena" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - [[package]] name = "indexmap" version = "2.14.0" @@ -1062,22 +846,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "ipnet" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" - -[[package]] -name = "iri-string" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "itertools" version = "0.14.0" @@ -1099,8 +867,6 @@ version = "0.3.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" dependencies = [ - "cfg-if", - "futures-util", "once_cell", "wasm-bindgen", ] @@ -1119,7 +885,7 @@ dependencies = [ "p256", "p384", "pem", - "rand 0.8.6", + "rand", "rsa", "serde", "serde_json", @@ -1161,12 +927,6 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - [[package]] name = "lock_api" version = "0.4.14" @@ -1182,12 +942,6 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" -[[package]] -name = "lru-slab" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" - [[package]] name = "lzma-sys" version = "0.1.20" @@ -1234,7 +988,7 @@ checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -1264,7 +1018,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand 0.8.6", + "rand", "smallvec", "zeroize", ] @@ -1451,15 +1205,6 @@ version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "zerovec", -] - [[package]] name = "powerfmt" version = "0.2.0" @@ -1584,75 +1329,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "proxy-sovd" -version = "0.1.0" -dependencies = [ - "async-trait", - "cda-interfaces", - "proxy-core", - "reqwest", - "serde", - "serde_json", - "tokio", - "tracing", -] - -[[package]] -name = "quinn" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" -dependencies = [ - "bytes", - "cfg_aliases", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash", - "rustls", - "socket2", - "thiserror", - "tokio", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-proto" -version = "0.11.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" -dependencies = [ - "bytes", - "getrandom 0.3.4", - "lru-slab", - "rand 0.9.4", - "ring", - "rustc-hash", - "rustls", - "rustls-pki-types", - "slab", - "thiserror", - "tinyvec", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-udp" -version = "0.5.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" -dependencies = [ - "cfg_aliases", - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.60.2", -] - [[package]] name = "quote" version = "1.0.45" @@ -1662,12 +1338,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - [[package]] name = "r-efi" version = "6.0.0" @@ -1681,18 +1351,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", + "rand_chacha", + "rand_core", ] [[package]] @@ -1702,17 +1362,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", + "rand_core", ] [[package]] @@ -1724,15 +1374,6 @@ dependencies = [ "getrandom 0.2.17", ] -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - [[package]] name = "redox_syscall" version = "0.5.18" @@ -1791,44 +1432,6 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" -[[package]] -name = "reqwest" -version = "0.12.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" -dependencies = [ - "base64", - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "webpki-roots", -] - [[package]] name = "rfc6979" version = "0.4.0" @@ -1839,20 +1442,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - [[package]] name = "rsa" version = "0.9.10" @@ -1866,19 +1455,13 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core 0.6.4", + "rand_core", "signature", "spki", "subtle", "zeroize", ] -[[package]] -name = "rustc-hash" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" - [[package]] name = "rustc_version" version = "0.4.1" @@ -1898,42 +1481,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69f9466fb2c14ea04357e91413efb882e2a6d4a406e625449bc0a5d360d53a21" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" -dependencies = [ - "web-time", - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", + "windows-sys", ] [[package]] @@ -2089,18 +1637,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - [[package]] name = "sha1" version = "0.10.6" @@ -2146,7 +1682,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core 0.6.4", + "rand_core", ] [[package]] @@ -2180,7 +1716,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2212,12 +1748,6 @@ dependencies = [ "der", ] -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - [[package]] name = "static_assertions" version = "1.1.0" @@ -2267,20 +1797,6 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] [[package]] name = "tempfile" @@ -2292,7 +1808,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2346,31 +1862,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - [[package]] name = "tokio" version = "1.52.1" @@ -2385,7 +1876,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2399,16 +1890,6 @@ dependencies = [ "syn", ] -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -2458,25 +1939,6 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" -dependencies = [ - "bitflags", - "bytes", - "futures-util", - "http", - "http-body", - "iri-string", - "pin-project-lite", - "tower", "tower-layer", "tower-service", ] @@ -2524,12 +1986,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - [[package]] name = "typenum" version = "1.20.0" @@ -2548,30 +2004,6 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - [[package]] name = "uuid" version = "1.23.1" @@ -2589,15 +2021,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2635,16 +2058,6 @@ dependencies = [ "wasm-bindgen-shared", ] -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.68" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "wasm-bindgen-macro" version = "0.2.118" @@ -2711,35 +2124,6 @@ dependencies = [ "semver", ] -[[package]] -name = "web-sys" -version = "0.3.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "windows-core" version = "0.62.2" @@ -2799,24 +2183,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -2826,135 +2192,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winnow" version = "0.7.15" @@ -3061,12 +2298,6 @@ dependencies = [ "wasmparser", ] -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - [[package]] name = "xz2" version = "0.1.7" @@ -3082,29 +2313,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" -[[package]] -name = "yoke" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - [[package]] name = "zerocopy" version = "0.8.48" @@ -3125,66 +2333,12 @@ dependencies = [ "syn", ] -[[package]] -name = "zerofrom" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - [[package]] name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index 05bfb6f..ba5b619 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,17 +46,31 @@ reqwest = { version = "0.12.24", default-features = false } tracing = "0.1.41" tracing-subscriber = { version = "0.3.20", default-features = false } +# Lints are aligned with shared-lints.toml from: +# https://github.com/eclipse-opensovd/cicd-workflows/tree/main/shared-lints [workspace.lints.clippy] # enable pedantic pedantic = { level = "warn", priority = -1 } ## exclude some too pedantic lints for now similar_names = "allow" -# additional lints -clone_on_ref_ptr = "warn" +## lints related to runtime panic behavior +# enforce only checked access to slices to avoid runtime panics indexing_slicing = "deny" +# disallow any unwraps in the production code +# (unwrap in test code is explicitly allowed) unwrap_used = "deny" +# enforce that arithmetic operations that can produce side effects always use +# either checked or explicit versions of the operations. eg. `.checked_add(...)` +# or `.saturating_sub(...)` to avoid unexpected runtime behavior or panics. arithmetic_side_effects = "deny" + +## lints related to readability of code +# enforce that references are cloned via eg. `Arc::clone` instead of `.clone()` +# making it explicit that a reference is cloned here and not the underlying data. +clone_on_ref_ptr = "warn" +# enforce that the type suffix of a literal is always appended directly +# eg. 12u8 instead of 12_u8 separated_literal_suffix = "deny" [workspace.lints.rust] diff --git a/deny.toml b/deny.toml index 639d194..2bd186f 100644 --- a/deny.toml +++ b/deny.toml @@ -1,4 +1,18 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License Version 2.0 which is available at +# https://www.apache.org/licenses/LICENSE-2.0 + [graph] +# TODO: add targets once the officially supported platforms are known. +# Leaving targets empty means cargo-deny checks all platforms in the dependency +# graph, which is the safest default. + all-features = false no-default-features = false @@ -7,11 +21,20 @@ no-default-features = false feature-depth = 1 +# This section is considered when running `cargo deny check advisories` +# More documentation for the advisories section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html [advisories] ignore = [ "RUSTSEC-2023-0071" ] +# This section is considered when running `cargo deny check licenses` +# More documentation for the licenses section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html [licenses] +# List of explicitly allowed licenses +# See https://spdx.org/licenses/ for list of possible licenses +# [possible values: any SPDX 3.11 short identifier (+ optional exception)]. allow = [ "Apache-2.0", "MIT", @@ -30,6 +53,9 @@ ignore = true registries = [ ] +# This section is considered when running `cargo deny check bans`. +# More documentation about the 'bans' section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html [bans] multiple-versions = "warn" wildcards = "allow" @@ -38,16 +64,23 @@ workspace-default-features = "allow" external-default-features = "allow" allow = [ ] deny = [ ] + +# Certain crates/versions that will be skipped when doing duplicate detection. skip = [ ] skip-tree = [ ] +# This section is considered when running `cargo deny check sources`. +# More documentation about the 'sources' section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html [sources] unknown-registry = "deny" unknown-git = "deny" allow-registry = [ "https://github.com/rust-lang/crates.io-index" ] allow-git = [ +# Internal dependency "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", +# TODO: Verify if below personal fork is necessary, it could break if the original repository is updated or fork no longer maintained "https://github.com/alexmohr/aide.git", "https://github.com/alexmohr/flatbuffers.git" ] From 4af1e6a6dd3fefffdc49821d8e0e3e29dc764d97 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 23 Apr 2026 11:10:18 +0200 Subject: [PATCH 04/33] fix: remove unused Serialize & parse_response fct Signed-off-by: Arvind Rathod --- proxy-core/src/config.rs | 12 ++++++------ proxy-core/src/service_resolver.rs | 30 ------------------------------ 2 files changed, 6 insertions(+), 36 deletions(-) diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index b5b3b43..016a11b 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -12,7 +12,7 @@ use std::path::Path; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; use crate::error::{ProxyError, Result}; @@ -24,7 +24,7 @@ fn default_true() -> bool { } /// Top-level proxy configuration loaded from a TOML file. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Deserialize)] pub struct Config { /// `DoIP` server settings (port, bind address, source address). pub server: ServerConfig, @@ -37,7 +37,7 @@ pub struct Config { } /// TODO: `DoIP` server configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Deserialize)] pub struct ServerConfig { /// TCP port for the `DoIP` server (default: 13400). pub doip_port: u16, @@ -50,7 +50,7 @@ pub struct ServerConfig { } /// SOVD gateway connection configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Deserialize)] pub struct SovdConfig { /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). pub gateway_url: String, @@ -71,7 +71,7 @@ pub struct SovdConfig { } /// ECU identity and addressing configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Deserialize)] pub struct EcuConfig { /// Default ECU name used for SOVD component path. pub default_name: String, @@ -84,7 +84,7 @@ pub struct EcuConfig { } /// Logging output configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Deserialize)] pub struct LoggingConfig { /// Log level filter (e.g. `info`, `debug`, `trace`). pub level: String, diff --git a/proxy-core/src/service_resolver.rs b/proxy-core/src/service_resolver.rs index 4d8fd67..1d62dfe 100644 --- a/proxy-core/src/service_resolver.rs +++ b/proxy-core/src/service_resolver.rs @@ -475,36 +475,6 @@ impl ServiceResolver { Some((response, effective_service)) } - /// `TODO:` to be removed, used in examples and debugging until the SOVD server returns - /// fully decoded responses. - /// Parse UDS response bytes using the MDD POS-RESPONSE structure. - /// - /// Delegates to CDA's `convert_from_uds` for decoding. Used by example - /// clients for response inspection and debugging. - /// - /// # Errors - /// Returns an error if the response cannot be parsed. - pub async fn parse_response( - &self, - service_name: &str, - request_sid: u8, - uds_response: &[u8], - ) -> Result, DiagServiceError> { - let diag_comm = self.make_diag_comm(service_name, request_sid); - let payload = make_service_payload(uds_response); - let manager = self.manager.read().await; - let response = manager.convert_from_uds(&diag_comm, &payload, true).await?; - let json_response = response.into_json()?; - - match json_response.data { - serde_json::Value::Object(map) => Ok(map), - serde_json::Value::Null => Ok(serde_json::Map::new()), - other => Err(DiagServiceError::InvalidRequest(format!( - "Expected JSON object in response, got: {other:?}" - ))), - } - } - /// Parse UDS request bytes using the MDD request structure. /// /// # Errors From b0c39a0ed1ae1be072c95a5edfb488f33eea2d87 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 23 Apr 2026 14:14:18 +0200 Subject: [PATCH 05/33] fix: review comments & split service_resolver Signed-off-by: Arvind Rathod --- Cargo.toml | 4 +- README.md | 6 +- config.toml | 27 - deny.toml | 46 +- docs/service_resolver_class.puml | 155 ++ examples/config.toml | 37 + proxy-core/src/config.rs | 328 +++- proxy-core/src/diag_handler.rs | 2 +- proxy-core/src/service_resolver.rs | 1603 ----------------- proxy-core/src/service_resolver/metadata.rs | 194 ++ proxy-core/src/service_resolver/mod.rs | 308 ++++ proxy-core/src/service_resolver/resolve.rs | 355 ++++ proxy-core/src/service_resolver/response.rs | 336 ++++ .../src/service_resolver/uds_helpers.rs | 539 ++++++ testcontainer/mdd/FLXC1000.mdd.license | 9 + 15 files changed, 2219 insertions(+), 1730 deletions(-) delete mode 100644 config.toml create mode 100644 docs/service_resolver_class.puml create mode 100644 examples/config.toml delete mode 100644 proxy-core/src/service_resolver.rs create mode 100644 proxy-core/src/service_resolver/metadata.rs create mode 100644 proxy-core/src/service_resolver/mod.rs create mode 100644 proxy-core/src/service_resolver/resolve.rs create mode 100644 proxy-core/src/service_resolver/response.rs create mode 100644 proxy-core/src/service_resolver/uds_helpers.rs create mode 100644 testcontainer/mdd/FLXC1000.mdd.license diff --git a/Cargo.toml b/Cargo.toml index ba5b619..4f247af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,9 +16,7 @@ homepage = "https://github.com/eclipse-opensovd/uds2sovd-proxy" [workspace] resolver = "3" -members = [ - "proxy-core", -] +members = ["proxy-core"] [workspace.dependencies] proxy-core = { path = "proxy-core" } diff --git a/README.md b/README.md index b1f9528..6454936 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ cargo build --release ### running -Ensure that the config (`config.toml`) fits your setup: +Ensure that the config (`examples/config.toml`) fits your setup: - `doip_port` is set to the desired DoIP server port (default: `13400`) - `gateway_url` points to the SOVD gateway (CDA or mock) @@ -77,7 +77,7 @@ cargo run --release -- --mdd-file FLXC1000.mdd ### running with SOVD Server -To use the proxy with a real SOVD Server instance, set `mock_gateway = false` in `config.toml` and point `gateway_url` to the SOVD Server endpoint. +To use the proxy with a real SOVD Server instance, set `mock_gateway = false` in `examples/config.toml` and point `gateway_url` to the SOVD Server endpoint. ## architecture @@ -104,7 +104,7 @@ DoIP Client ## configuration -Edit `config.toml`: +Edit `examples/config.toml`: - `doip_port = 13_400`: DoIP server port - `mock_gateway = true`: Use built-in mock responses diff --git a/config.toml b/config.toml deleted file mode 100644 index 8d6a2da..0000000 --- a/config.toml +++ /dev/null @@ -1,27 +0,0 @@ -[server] -doip_port = 13_400 -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3_712 - - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "uds2sovd_proxy" -client_secret = "test_secret" -timeout_ms = 5_000 -mock_gateway = true -include_schema = false -api_version = "v15" - - -[ecu] -default_name = "AUTO_DETECT" -logical_address = 1 -eid = [ 0, 1, 2, 3, 4, 5 ] -gid = [ 0, 1, 2, 3, 4, 5 ] - - -[logging] -level = "debug" -format = "pretty" diff --git a/deny.toml b/deny.toml index 2bd186f..4c2ae1a 100644 --- a/deny.toml +++ b/deny.toml @@ -25,7 +25,7 @@ feature-depth = 1 # More documentation for the advisories section can be found here: # https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html [advisories] -ignore = [ "RUSTSEC-2023-0071" ] +ignore = ["RUSTSEC-2023-0071"] # This section is considered when running `cargo deny check licenses` @@ -36,21 +36,21 @@ ignore = [ "RUSTSEC-2023-0071" ] # See https://spdx.org/licenses/ for list of possible licenses # [possible values: any SPDX 3.11 short identifier (+ optional exception)]. allow = [ -"Apache-2.0", -"MIT", -"BSD-3-Clause", -"Zlib", -"ISC", -"Unicode-3.0", -"CDLA-Permissive-2.0" + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "Zlib", + "ISC", + "Unicode-3.0", + "CDLA-Permissive-2.0", ] confidence-threshold = 0.9 -exceptions = [ ] +exceptions = [] [licenses.private] ignore = true -registries = [ ] +registries = [] # This section is considered when running `cargo deny check bans`. @@ -62,12 +62,12 @@ wildcards = "allow" highlight = "all" workspace-default-features = "allow" external-default-features = "allow" -allow = [ ] -deny = [ ] +allow = [] +deny = [] # Certain crates/versions that will be skipped when doing duplicate detection. -skip = [ ] -skip-tree = [ ] +skip = [] +skip-tree = [] # This section is considered when running `cargo deny check sources`. @@ -76,17 +76,17 @@ skip-tree = [ ] [sources] unknown-registry = "deny" unknown-git = "deny" -allow-registry = [ "https://github.com/rust-lang/crates.io-index" ] +allow-registry = ["https://github.com/rust-lang/crates.io-index"] allow-git = [ -# Internal dependency -"https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", -# TODO: Verify if below personal fork is necessary, it could break if the original repository is updated or fork no longer maintained -"https://github.com/alexmohr/aide.git", -"https://github.com/alexmohr/flatbuffers.git" + # Internal dependency + "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", + # TODO: Verify if below personal fork is necessary, it could break if the original repository is updated or fork no longer maintained + "https://github.com/alexmohr/aide.git", + "https://github.com/alexmohr/flatbuffers.git", ] [sources.allow-org] -github = [ ] -gitlab = [ ] -bitbucket = [ ] +github = [] +gitlab = [] +bitbucket = [] diff --git a/docs/service_resolver_class.puml b/docs/service_resolver_class.puml new file mode 100644 index 0000000..6d18faf --- /dev/null +++ b/docs/service_resolver_class.puml @@ -0,0 +1,155 @@ +' SPDX-License-Identifier: Apache-2.0 +' SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +' +' See the NOTICE file(s) distributed with this work for additional +' information regarding copyright ownership. +' +' This program and the accompanying materials are made available under the +' terms of the Apache License Version 2.0 which is available at +' https://www.apache.org/licenses/LICENSE-2.0 + +@startuml service_resolver_class +!pragma layout smetana + +title Service Resolver โ€“ Class Diagram\nproxy-core::service_resolver โ€” MDD-driven UDS encoding / decoding +skinparam classAttributeIconSize 0 +skinparam packageStyle rectangle +skinparam noteFontSize 11 +skinparam classFontSize 12 + +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +' proxy-core::service_resolver +' One struct (ServiceResolver) whose impl blocks are split across +' four source files for readability. uds_helpers is a separate +' module of free (non-method) functions. +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +package "proxy-core::service_resolver" { + + class ServiceResolver { + - manager : Arc> + - ecu_name : String + == mod.rs โ€” construction & UDS helpers == + + {static} new(ecu_name, db, logical, tester) : Result + + ecu_name() : &str + + {static} is_negative_response(uds) : bool + + {static} get_nrc(uds) : Option + == resolve.rs โ€” DID โ†’ service name == + + <> resolve_read_service(did, uds) : Option<(String, Map)> + + <> resolve_write_service(did, uds) : Option<(String, Map)> + + <> parse_request(name, uds) : Result + == response.rs โ€” encode UDS response == + + <> build_response(name, sid, did, data) : Result> + == metadata.rs โ€” MDD parameter queries == + + <> get_service_parameter_metadata(name) : Result> + + <> get_response_parameter_metadata(name) : Result> + + <> get_enriched_response_metadata(name, did) : Result> + + <> lookup_service_names_by_sid(sid) : Result> + + <> get_mux_cases_for_service(name) : Result> + } + + note right of ServiceResolver + + Service resolution algorithm (resolve.rs): + 1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO]) + 2. Single match โ†’ service name found (fast path) + 3. Multiple candidates โ†’ inspect request parameter metadata: + โ€ข CodedConst โ€” exact DID value match + โ€ข PhysConst โ€” coded_value or create_uds_payload probe + โ€ข Value โ€” coded_default or CompuScale range match + 4. No match โ†’ log error, return None (no fallback) + + Response encoding (response.rs): + Walk MDD POS-RESPONSE parameters: + โ€ข CODED-CONST โ†’ fixed byte (e.g. response SID 0x62) + โ€ข MatchingRequestParam โ†’ echo DID bytes from request + โ€ข VALUE โ†’ SOVD JSON value at MDD-defined offset + Opaque STRUCTURE types trigger MUX sibling lookup. + end note + + class uds_helpers <> { + ' โ”€โ”€ pub re-exports (used by proxy-sovd) โ”€โ”€ + + parse_mux_coded_value(coded) : Option + + find_mux_case_prefix(meta, did) : Option + + has_mux_case_for_did_exact(meta, did) : bool + == internal helpers == + ~ extract_did_from_uds(data) : Option + ~ diag_comm_type(sid) : DiagCommType + ~ make_service_payload(data) : ServicePayload + ~ encode_unsigned_be(num) : Vec + ~ parse_u64_literal(value) : Option + ~ find_did_param(meta, sid) : Option + ~ did_matches_compu_scales(scales, did) : bool + ~ encode_value_at(buf, pos, size, value) : () + ~ value_to_bytes(value) : Vec + } + + note bottom of uds_helpers + Top 3 are pub re-exported from mod.rs + and used by proxy-sovd for MUX matching. + end note + + ServiceResolver ..> uds_helpers : uses +} + +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +' CDA (external dependency โ€” cda-core / cda-interfaces) +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +package "cda-core (external path dep)" #LightGray { + + interface EcuManagerTrait <> { + ' โ€” resolution โ€” + + lookup_diagcomms_by_request_prefix(prefix) + + get_request_parameter_metadata(service) + ' โ€” response building โ€” + + get_response_parameter_metadata(service) + + get_components_data_info(service) + ' โ€” encoding / decoding โ€” + + create_uds_payload(service, params) + + convert_from_uds(service, bytes) + + convert_request_from_uds(service, bytes) + ' โ€” variant selection โ€” + + detect_variant() + } + + class "CdaEcuManager\n" as CdaEcuManager { + ' Loads an MDD file (DiagnosticDatabase) and + ' implements EcuManagerTrait for UDS โ†” MDD ops. + } + + CdaEcuManager ..|> EcuManagerTrait +} + +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +' proxy-core public API consumed by proxy-sovd / proxy-doip +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +package "proxy-core (public API)" #LightYellow { + + interface DiagHandler <> { + ' Implemented by SovdDiagHandler in proxy-sovd. + ' ServiceResolver is a field of SovdDiagHandler โ€” + ' not a DiagHandler implementor itself. + + <> handle_read_did(did, uds) : Result> + + <> handle_write_did(did, uds) : Result> + } + + class Config { + + server : ServerConfig + + sovd : SovdConfig + + ecu : EcuConfig + + logging : LoggingConfig + -- + + {static} from_file(path) : Result + } +} + +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +' Relationships +' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +ServiceResolver *--> CdaEcuManager : owns via Arc\n(shared with callers) + +note on link + Async RwLock allows concurrent + read access across Tokio tasks. +end note + +@enduml diff --git a/examples/config.toml b/examples/config.toml new file mode 100644 index 0000000..002fac0 --- /dev/null +++ b/examples/config.toml @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License Version 2.0 which is available at +# https://www.apache.org/licenses/LICENSE-2.0 + +[server] +doip_port = 13_400 +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3_712 + + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "uds2sovd_proxy" +client_secret = "test_secret" +timeout_ms = 5_000 +mock_gateway = true +include_schema = false +api_version = "v15" + + +[ecu] +default_name = "AUTO_DETECT" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + + +[logging] +level = "debug" +format = "pretty" diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index 016a11b..8a9d699 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -12,19 +12,48 @@ use std::path::Path; -use serde::Deserialize; +use serde::{Deserialize, Deserializer, de}; use crate::error::{ProxyError, Result}; /// Required byte length for EID and GID fields per ISO 13400-2. const EID_GID_BYTE_LENGTH: usize = 6; -fn default_true() -> bool { - true +/// Reject zero during deserialization so invalid values never enter the config. +fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let v = u16::deserialize(deserializer)?; + if v == 0 { + return Err(de::Error::custom("value must not be zero")); + } + Ok(v) +} + +/// Reject zero during deserialization for `usize` fields. +fn deserialize_positive_usize<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let v = usize::deserialize(deserializer)?; + if v == 0 { + return Err(de::Error::custom("value must be greater than zero")); + } + Ok(v) +} + +/// Reject empty strings during deserialization. +fn deserialize_nonempty_str<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let s = String::deserialize(deserializer)?; + if s.is_empty() { + return Err(de::Error::custom("value must not be empty")); + } + Ok(s) } /// Top-level proxy configuration loaded from a TOML file. -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Default)] pub struct Config { /// `DoIP` server settings (port, bind address, source address). pub server: ServerConfig, @@ -36,14 +65,16 @@ pub struct Config { pub logging: LoggingConfig, } -/// TODO: `DoIP` server configuration. +/// `DoIP` server configuration. #[derive(Debug, Clone, Deserialize)] pub struct ServerConfig { /// TCP port for the `DoIP` server (default: 13400). + #[serde(deserialize_with = "deserialize_nonzero_u16")] pub doip_port: u16, /// IP address to bind the server socket to. pub bind_address: String, /// Maximum number of concurrent connections. + #[serde(deserialize_with = "deserialize_positive_usize")] pub max_connections: usize, /// `DoIP` source address used in response messages. pub source_address: u16, @@ -53,6 +84,7 @@ pub struct ServerConfig { #[derive(Debug, Clone, Deserialize)] pub struct SovdConfig { /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). + #[serde(deserialize_with = "deserialize_nonempty_str")] pub gateway_url: String, /// `OAuth2` client ID for gateway authentication. pub client_id: String, @@ -63,24 +95,31 @@ pub struct SovdConfig { /// SOVD API version path segment (e.g. `v15`). pub api_version: String, /// Whether to request inline schema in data responses. - #[serde(default = "default_true")] + #[serde(default = "SovdConfig::default_include_schema")] pub include_schema: bool, /// When `true`, bypass HTTP calls and generate synthetic responses. #[serde(default)] pub mock_gateway: bool, } +impl SovdConfig { + fn default_include_schema() -> bool { + true + } +} + /// ECU identity and addressing configuration. #[derive(Debug, Clone, Deserialize)] pub struct EcuConfig { /// Default ECU name used for SOVD component path. pub default_name: String, /// ISO 13400 logical address of the target ECU. + #[serde(deserialize_with = "deserialize_nonzero_u16")] pub logical_address: u16, /// 6-byte Entity Identification (MAC address). - pub eid: Vec, + pub eid: [u8; EID_GID_BYTE_LENGTH], /// 6-byte Group Identification. - pub gid: Vec, + pub gid: [u8; EID_GID_BYTE_LENGTH], } /// Logging output configuration. @@ -104,76 +143,49 @@ impl Config { toml::from_str(&content) .map_err(|e| ProxyError::Config(format!("Failed to parse config: {e}"))) } +} - /// Validate configuration - /// - /// # Errors - /// Returns an error if the configuration is invalid. - /// - /// TODO(config): Validate `gateway_url` is a well-formed URL, not just - /// non-empty. Consider using the `url` crate for parsing. - /// TODO(config): Validate `api_version` matches expected pattern (e.g. `v\\d+`). - pub fn validate(&self) -> Result<()> { - if self.server.doip_port == 0 { - return Err(ProxyError::Config("Invalid DoIP port".to_string())); - } - - if self.sovd.gateway_url.is_empty() && !self.sovd.mock_gateway { - return Err(ProxyError::Config("SOVD gateway URL is empty".to_string())); - } - - if self.ecu.eid.len() != EID_GID_BYTE_LENGTH { - return Err(ProxyError::Config("EID must be 6 bytes".to_string())); - } - - if self.ecu.gid.len() != EID_GID_BYTE_LENGTH { - return Err(ProxyError::Config("GID must be 6 bytes".to_string())); +impl Default for ServerConfig { + fn default() -> Self { + Self { + doip_port: 13400, + bind_address: "0.0.0.0".to_string(), + max_connections: 10, + source_address: 0x0E80, } + } +} - if self.server.max_connections == 0 { - return Err(ProxyError::Config( - "max_connections must be greater than 0".to_string(), - )); +impl Default for SovdConfig { + fn default() -> Self { + Self { + gateway_url: "http://localhost:20002".to_string(), + client_id: "uds2sovd_proxy".to_string(), + client_secret: "test_secret".to_string(), + timeout_ms: 5000, + api_version: "v15".to_string(), + include_schema: true, + mock_gateway: false, } + } +} - if self.ecu.logical_address == 0 { - return Err(ProxyError::Config( - "ECU logical address must not be 0x0000".to_string(), - )); +impl Default for EcuConfig { + fn default() -> Self { + Self { + default_name: "ECU".to_string(), + logical_address: 0x0001, + eid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], + gid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], } - - Ok(()) } } -impl Default for Config { +impl Default for LoggingConfig { fn default() -> Self { Self { - server: ServerConfig { - doip_port: 13400, - bind_address: "0.0.0.0".to_string(), - max_connections: 10, - source_address: 0x0E80, - }, - sovd: SovdConfig { - gateway_url: "http://localhost:20002".to_string(), - client_id: "uds2sovd_proxy".to_string(), - client_secret: "test_secret".to_string(), - timeout_ms: 5000, - api_version: "v15".to_string(), - include_schema: true, - mock_gateway: false, - }, - ecu: EcuConfig { - default_name: "ECU".to_string(), - logical_address: 0x0001, - eid: vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05], - gid: vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05], - }, - logging: LoggingConfig { - level: "info".to_string(), - format: "pretty".to_string(), - }, + level: "info".to_string(), + format: "pretty".to_string(), } } } @@ -187,11 +199,187 @@ mod tests { let config = Config::default(); assert_eq!(config.server.doip_port, 13400); assert_eq!(config.sovd.api_version, "v15"); + assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); } #[test] - fn test_validate_config() { - let config = Config::default(); - assert!(config.validate().is_ok()); + fn test_deserialize_valid_config() { + let toml_str = r#" + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let config: Config = toml::from_str(toml_str).expect("valid config should parse"); + assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); + assert_eq!(config.server.doip_port, 13400); + } + + #[test] + fn test_deserialize_rejects_zero_port() { + let toml_str = r#" + [server] + doip_port = 0 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "doip_port=0 should be rejected"); + } + + #[test] + fn test_deserialize_rejects_zero_max_connections() { + let toml_str = r#" + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 0 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "max_connections=0 should be rejected"); + } + + #[test] + fn test_deserialize_rejects_zero_logical_address() { + let toml_str = r#" + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 0 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "logical_address=0 should be rejected"); + } + + #[test] + fn test_deserialize_rejects_wrong_eid_length() { + let toml_str = r#" + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "eid with wrong length should be rejected"); + } + + #[test] + fn test_deserialize_rejects_empty_gateway_url() { + let toml_str = r#" + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "empty gateway_url should be rejected"); } } diff --git a/proxy-core/src/diag_handler.rs b/proxy-core/src/diag_handler.rs index 7db75a7..adaace9 100644 --- a/proxy-core/src/diag_handler.rs +++ b/proxy-core/src/diag_handler.rs @@ -16,7 +16,7 @@ use crate::error::Result; /// Trait for processing UDS diagnostic requests through a backend. #[async_trait] -pub trait DiagHandler: Send + Sync { +pub trait DiagHandler { /// Process a `ReadDataByIdentifier` (0x22) request. /// /// `did` is the extracted 16-bit Data Identifier. diff --git a/proxy-core/src/service_resolver.rs b/proxy-core/src/service_resolver.rs deleted file mode 100644 index 1d62dfe..0000000 --- a/proxy-core/src/service_resolver.rs +++ /dev/null @@ -1,1603 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License Version 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0 - */ - -//! ECU Manager wrapper for MDD-driven UDS request/response processing. -//! -//! Provides a simplified interface to the CDA's -//! `EcuManager` for encoding/decoding UDS messages using the loaded MDD -//! diagnostic database. -//! -//! ## Service resolution -//! -//! When a UDS request arrives the proxy must identify which diagnostic service -//! from the MDD it belongs to (e.g. `WDBI_VIN` vs `WDBI_PLAIN` for SID 0x2E). -//! -//! Resolution uses `lookup_diagcomms_by_request_prefix` with the full -//! `[SID, DID_HI, DID_LO]` prefix, which directly matches services whose -//! sequential coded-const parameters match the request bytes. This handles -//! CODED-CONST DID services in a single call. -//! -//! For services where the DID is not a coded constant (`PhysConst` / Value), -//! the prefix lookup returns all SID-matching services and the resolver -//! confirms the DID via request parameter metadata: -//! -//! - **`CodedConst`**: exact DID match. -//! - **`PhysConst`**: resolved `coded_value` or `create_uds_payload` probe. -//! - **Value**: `coded_default_value` or `CompuScale` range match. -//! -//! If no service matches, an error is logged โ€” no fallback. - -use std::sync::Arc; - -use cda_core::{DiagServiceResponseStruct, EcuManager as CdaEcuManager}; -use cda_database::datatypes::DiagnosticDatabase; -use cda_interfaces::{ - DiagComm, DiagCommType, DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, - EcuManagerType, FunctionalDescriptionConfig, HashMap, MuxCaseInfo, Protocol, - ServiceParameterMetadata, ServicePayload, UDS_ID_RESPONSE_BITMASK, - datatypes::{ComParams, DatabaseNamingConvention, DiagnosticServiceAffixPosition}, - diagservices::{DiagServiceResponse, DiagServiceResponseType, UdsPayloadData}, - service_ids, -}; -use cda_plugin_security::DefaultSecurityPluginData; -use tokio::sync::RwLock; - -/// Minimum UDS negative response length: 0x7F + SID + NRC. -const UDS_NEGATIVE_RESPONSE_MIN_LEN: usize = 3; - -/// Minimum UDS positive response buffer size: response SID (1) + DID high (1) + DID low (1). -const UDS_POSITIVE_RESPONSE_MIN_SIZE: usize = 3; - -/// Wraps the CDA's [`EcuManager`] with async locking -/// to provide MDD-driven UDS encoding, decoding, and service resolution -/// for the proxy. -pub struct ServiceResolver { - manager: Arc>>, - ecu_name: String, -} - -impl ServiceResolver { - /// Create new ECU manager from MDD database. - /// - /// # Arguments - /// * `ecu_name` - Name of the ECU - /// * `db` - Loaded `DiagnosticDatabase` from MDD file - /// * `logical_address` - ECU logical address (e.g. 0x1000) - /// * `tester_address` - Tester logical address (e.g. 0x0E80) - /// - /// # Errors - /// Returns an error if the ECU manager cannot be initialized from the database. - pub async fn new( - ecu_name: String, - db: DiagnosticDatabase, - logical_address: u16, - tester_address: u16, - ) -> Result { - let com_params = Self::default_com_params(logical_address, tester_address); - - let func_config = FunctionalDescriptionConfig { - description_database: String::new(), - enabled_functional_groups: None, - protocol_position: DiagnosticServiceAffixPosition::Prefix, - protocol_case_sensitive: false, - }; - - let mut manager = CdaEcuManager::new( - db, - Protocol::DoIp, - &com_params, - DatabaseNamingConvention::default(), - EcuManagerType::Ecu, - &func_config, - true, - ) - .map_err(|e| { - tracing::error!("Failed to create EcuManager: {}", e); - e - })?; - - Self::activate_base_variant(&mut manager).await?; - - Ok(Self { - manager: Arc::new(RwLock::new(manager)), - ecu_name, - }) - } - - /// Activate the base (fallback) ECU variant. - /// - /// The CDA's diagnostic engine requires a variant to be selected before - /// service lookup, metadata queries, or UDS encoding/decoding work - /// correctly. When no specific variant is requested (or the requested - /// variant is not found), this method seeds the engine with a synthetic - /// dummy response so that `detect_variant` initialises the internal - /// state-chart and pins the engine to a determinate base state. - /// - /// #`TODO:` real variant detection - /// - /// Replace the dummy response with actual variant-identification DID - /// reads from a live ECU connection: - /// 1. Read variant-identification DIDs from the ECU. - /// 2. Call `detect_variant(responses)` with real data. - /// 3. The engine narrows the active variant and limits visible services. - /// - /// # Errors - /// Returns an error only when `detect_variant` fails **and** no variant - /// name was set (i.e. the engine did not activate at all). - async fn activate_base_variant( - manager: &mut CdaEcuManager, - ) -> Result<(), DiagServiceError> { - // `TODO:` replace this dummy response with real variant-identification - // DID reads from the ECU (see doc comment above). - let dummy_response = DiagServiceResponseStruct { - service: DiagComm { - name: String::new(), - type_: DiagCommType::Data, - lookup_name: None, - }, - data: vec![], - mapped_data: None, - response_type: DiagServiceResponseType::Positive, - }; - - let mut responses: HashMap = HashMap::default(); - responses.insert("__variant_init__".to_string(), dummy_response); - - match manager.detect_variant(responses).await { - Ok(()) => Ok(()), - Err(e) => { - let variant = manager.variant(); - if variant.name.is_some() { - tracing::info!( - "Base variant '{}' activated (state chart init skipped: {})", - variant.name.as_deref().unwrap_or("unknown"), - e - ); - Ok(()) - } else { - Err(e) - } - } - } - } - - /// Build UDS response bytes from SOVD JSON data using MDD response metadata. - /// - /// Queries the POS-RESPONSE parameter layout from the MDD to determine exact - /// byte positions and sizes for each parameter. Each parameter is encoded - /// at its MDD-defined position: - /// - /// - **CODED-CONST**: fixed value written directly (e.g. response SID). - /// - **`MatchingRequestParam`**: DID bytes from the original request. - /// - **VALUE**: SOVD data value encoded with the correct byte width; - /// defaults to 0 when the key is not present in the SOVD response. - /// - /// Falls back to naive encoding if response metadata is unavailable. - /// - /// # Errors - /// Returns an error if the response cannot be encoded. - /// - /// # TODO: - /// Once the SOVD server returns properly structured responses, the naive - /// encoding fallback and the MDD-based `encode_response_from_metadata` - /// path can be removed โ€” the proxy will forward pre-encoded UDS bytes. - pub async fn build_response( - &self, - service_name: &str, - sid: u8, - did: u16, - response_data: HashMap, - ) -> Result, DiagServiceError> { - tracing::debug!( - "[MDD] Building UDS response for '{}' SID 0x{:02X} DID 0x{:04X}", - service_name, - sid, - did, - ); - - let (response, effective_service) = if let Some((r, svc)) = self - .encode_response_from_metadata(service_name, sid, did, &response_data) - .await - { - (r, svc) - } else { - // Fallback: naive encoding โ€” used when no response metadata is available. - tracing::debug!( - "[MDD] No response metadata for '{}', using naive encoding", - service_name - ); - let response_sid = sid.wrapping_add(UDS_ID_RESPONSE_BITMASK); - #[allow(clippy::cast_possible_truncation)] - let mut response = vec![response_sid, (did >> 8) as u8, (did & 0xFF) as u8]; - - let entries: Vec<_> = response_data - .iter() - .filter(|(k, _)| !k.eq_ignore_ascii_case("sid")) - .collect(); - - for (key, value) in entries { - match value { - serde_json::Value::String(s) => { - response.extend_from_slice(s.as_bytes()); - } - serde_json::Value::Number(n) => { - if let Some(num) = n.as_u64() { - response.extend(encode_unsigned_be(num)); - } else if let Some(num) = n.as_i64() { - let unsigned = num.cast_unsigned(); - #[allow(clippy::cast_possible_truncation)] - if u8::try_from(unsigned).is_ok() { - response.push(unsigned as u8); - } else { - response.push((unsigned >> 8) as u8); - response.push((unsigned & 0xFF) as u8); - } - } - } - serde_json::Value::Array(arr) => { - for item in arr { - #[allow(clippy::cast_possible_truncation)] - if let Some(byte) = item.as_u64() { - response.push(byte as u8); - } - } - } - serde_json::Value::Bool(b) => { - response.push(u8::from(*b)); - } - _ => { - tracing::warn!( - "[MDD] Skipping unsupported value type for '{}': {:?}", - key, - value - ); - } - } - } - - tracing::debug!("[MDD] Built UDS response (naive): {:02X?}", response); - (response, service_name.to_string()) - }; - - // Debug-only round-trip validation: parse the built bytes back through - // the CDA to confirm the MDD layout produces a decodable - // response. Uses the effective service name (which may be an enriched - // MUX sibling) so the CDA parses against the same structure we - // encoded with. - if tracing::enabled!(tracing::Level::DEBUG) { - self.validate_response(&effective_service, sid, &response) - .await; - } - - Ok(response) - } - - /// Round-trip validate UDS response bytes by parsing them back through - /// the CDA. - /// - /// Called only when `tracing::Level::DEBUG` is enabled โ€” failures are logged - /// as warnings but never block the response (non-blocking). - async fn validate_response(&self, service_name: &str, request_sid: u8, uds_response: &[u8]) { - let diag_comm = self.make_diag_comm(service_name, request_sid); - let payload = make_service_payload(uds_response); - let manager = self.manager.read().await; - match manager.convert_from_uds(&diag_comm, &payload, true).await { - Ok(parsed) => match parsed.into_json() { - Ok(json) => tracing::trace!( - "[MDD] Round-trip validation OK for '{}': {:?}", - service_name, - json.data - ), - Err(e) => tracing::warn!( - "[MDD] Round-trip validation: JSON decode failed for '{}': {}", - service_name, - e - ), - }, - Err(e) => tracing::warn!( - "[MDD] Round-trip validation: parse failed for '{}': {}", - service_name, - e - ), - } - } - - /// Encode a UDS response using POS-RESPONSE parameter metadata from the MDD. - /// - /// For each parameter in the MDD response structure: - /// - CODED-CONST (e.g. response SID at byte 0): writes the const value. - /// - `MatchingRequestParam` (e.g. DID at bytes 1-2): writes the DID. - /// - VALUE: uses the SOVD response data keyed by the MDD parameter name; - /// falls back to `0` when the key is absent. - /// - /// Returns `None` when no response metadata is available for the service. - /// On success returns the encoded bytes and the effective service name - /// (which may differ from `service_name` when enriched MUX sibling metadata - /// is used). - async fn encode_response_from_metadata( - &self, - service_name: &str, - _sid: u8, - did: u16, - response_data: &HashMap, - ) -> Option<(Vec, String)> { - let (meta, effective_service) = self - .get_enriched_response_metadata_with_source(service_name, did) - .await - .ok()?; - if meta.is_empty() { - return None; - } - - // Find the MUX case matching this DID (if any) using floor-based matching. - let mux_case_prefix = find_mux_case_prefix(&meta, did); - - // Derive the matching marker name for total_size computation. - let mux_marker_name: Option = mux_case_prefix - .as_deref() - .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - - // Filter: keep top-level params (no '/') + matching MUX case VALUE params - // + the matching case marker (for total_size). - let active_params: Vec<_> = meta - .iter() - .filter(|p| { - if !p.name.contains('/') { - true - } else if let Some(prefix) = &mux_case_prefix { - p.name.starts_with(prefix.as_str()) - || mux_marker_name.as_deref() == Some(&p.name) - } else { - !p.name.starts_with("__mux_case__/") - } - }) - .collect(); - - // Resolve effective size for each active param. For VALUE params with - // `byte_size: None` (variable-length DOPs like EndOfPdu), the size is - // inferred from the actual response data. - let effective_sizes: Vec = active_params - .iter() - .map(|p| { - if let Some(s) = p.byte_size { - return s as usize; - } - // Variable-size VALUE param โ€” infer size from the data. - if !matches!( - &p.param_type, - cda_interfaces::ParameterTypeMetadata::Value { .. } - ) { - return 0; - } - let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); - let value = response_data - .get(&p.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - value_to_bytes(value).len() - }) - .collect(); - - // Determine total response size from filtered params. - let total_size = active_params - .iter() - .zip(effective_sizes.iter()) - .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) - .max() - .unwrap_or(UDS_POSITIVE_RESPONSE_MIN_SIZE); - - let mut response = vec![0u8; total_size]; - - for (param, &eff_size) in active_params.iter().zip(effective_sizes.iter()) { - // Skip MUX case markers โ€” they're only used for total_size computation. - if param.name.starts_with("__mux_case__/") { - continue; - } - let pos = param.byte_position as usize; - - if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { - continue; - } - - match ¶m.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - // The SID byte is stored as a decimal string (e.g. "98" for 0x62). - if let Ok(val) = coded_value.parse::() { - let bytes = encode_unsigned_be(val); - let copy_len = bytes.len().min(eff_size); - // Right-align in the field (big-endian convention). - let offset = eff_size.saturating_sub(copy_len); - let dst_start = pos.saturating_add(offset); - let dst_end = dst_start.saturating_add(copy_len); - let src_start = bytes.len().saturating_sub(copy_len); - if let (Some(dst), Some(src)) = - (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) - { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { - // DID bytes from the original request, big-endian. - let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; - let copy_len = did_bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - did_bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // For MUX case params, try the short name (after '/') as well. - let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); - let value = response_data - .get(¶m.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - - if param.byte_size.is_some() { - encode_value_at(&mut response, pos, eff_size, value); - } else { - // Variable-size param: write the raw byte representation. - let bytes = value_to_bytes(value); - let copy_len = bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} - } - } - - tracing::debug!( - "[MDD] Built UDS response via metadata for '{}'): {:02X?}", - service_name, - response - ); - Some((response, effective_service)) - } - - /// Parse UDS request bytes using the MDD request structure. - /// - /// # Errors - /// Returns an error if the request cannot be parsed. - pub async fn parse_request( - &self, - service_name: &str, - uds_request: &[u8], - ) -> Result, DiagServiceError> { - let service_id = uds_request.first().copied().unwrap_or(0x00); - let diag_comm = self.make_diag_comm(service_name, service_id); - let payload = make_service_payload(uds_request); - - let manager = self.manager.read().await; - let response = manager - .convert_request_from_uds(&diag_comm, &payload, true) - .await?; - let json_response = response.into_json()?; - - if let serde_json::Value::Object(map) = json_response.data { - tracing::debug!( - "[MDD] Parsed request for '{}': {} fields", - service_name, - map.len() - ); - Ok(map) - } else { - tracing::error!( - "[MDD] Expected JSON object in request, got: {:?}", - json_response.data - ); - Err(DiagServiceError::InvalidRequest( - "Expected JSON object in request".to_string(), - )) - } - } - - /// Retrieve request parameter metadata for a service. - /// - /// # Errors - /// Returns an error if the metadata is not available. - pub async fn get_service_parameter_metadata( - &self, - service_name: &str, - ) -> Result, DiagServiceError> { - let manager = self.manager.read().await; - manager.get_request_parameter_metadata(service_name) - } - - /// Retrieve POS-RESPONSE parameter metadata (byte positions, sizes, types). - /// - /// # Errors - /// Returns an error if the metadata is not available. - pub async fn get_response_parameter_metadata( - &self, - service_name: &str, - ) -> Result, DiagServiceError> { - let manager = self.manager.read().await; - manager.get_response_parameter_metadata(service_name) - } - - /// Retrieve enriched POS-RESPONSE metadata for a service + DID. - /// - /// Some services have a direct POS-RESPONSE - /// that references a STRUCTURE as a single opaque VALUE param (`byte_size` = - /// None, no sub-fields). The CDA doesn't flatten the STRUCTURE children in the - /// metadata for these services. - /// - /// However, a shared MUX-based response used by - /// sibling services DOES flatten every DID's sub-fields. This method - /// detects the opaque-STRUCTURE case and transparently returns the richer - /// MUX-based metadata instead, so callers get per-field byte positions. - /// - /// # Errors - /// Returns an error if the metadata is not available. - pub async fn get_enriched_response_metadata( - &self, - service_name: &str, - did: u16, - ) -> Result, DiagServiceError> { - self.get_enriched_response_metadata_with_source(service_name, did) - .await - .map(|(meta, _source)| meta) - } - - /// Same as [`get_enriched_response_metadata`] but also returns the name of - /// the service that actually provided the metadata. When the response is - /// "opaque" (single STRUCTURE ref) and a MUX-based sibling is used, the - /// returned name is the sibling โ€” callers that need to validate via - /// `convert_from_uds` must use this name, not the original. - /// - async fn get_enriched_response_metadata_with_source( - &self, - service_name: &str, - did: u16, - ) -> Result<(Vec, String), DiagServiceError> { - let manager = self.manager.read().await; - let meta = manager.get_response_parameter_metadata(service_name)?; - - // Heuristic: the response is "opaque" when the only data param - // (after SID + DID) is a single VALUE with byte_size = None. - let data_params: Vec<_> = meta - .iter() - .filter(|p| { - matches!( - p.param_type, - cda_interfaces::ParameterTypeMetadata::Value { .. } - | cda_interfaces::ParameterTypeMetadata::PhysConst { .. } - ) - }) - .collect(); - - let Some(first_param) = data_params.first() else { - return Ok((meta, service_name.to_string())); - }; - let is_opaque = data_params.len() == 1 - && first_param.byte_size.is_none() - && !first_param.name.contains('/'); - - if !is_opaque { - return Ok((meta, service_name.to_string())); - } - - tracing::debug!( - "[MDD] Response metadata for '{}' is opaque (single STRUCTURE ref '{}'), searching \ - for MUX-based sibling", - service_name, - first_param.name, - ); - - let security_plugin: DynamicPlugin = Box::new(()); - - // Search READ services for a MUX-based sibling with a case for this DID. - let candidates: Vec = manager - .get_components_data_info(&security_plugin) - .into_iter() - .map(|c| c.id) - .collect(); - - for candidate in &candidates { - if candidate == service_name { - continue; - } - let sibling_meta = match manager.get_response_parameter_metadata(candidate) { - Ok(m) if m.len() > meta.len() => m, - _ => continue, - }; - // Check if this sibling has a MUX case matching our DID (exact match - // to avoid cross-DOP false positives from floor matching). - let has_mux_for_did = has_mux_case_for_did_exact(&sibling_meta, did); - if has_mux_for_did { - tracing::debug!( - "[MDD] Using MUX-based metadata from '{}' for DID 0x{:04X} ({} params instead \ - of {})", - candidate, - did, - sibling_meta.len(), - meta.len(), - ); - return Ok((sibling_meta, candidate.clone())); - } - } - - // No MUX sibling found โ€” use original metadata. - Ok((meta, service_name.to_string())) - } - - /// Look up service names by SID. - /// - /// # Errors - /// Returns an error if the lookup fails. - pub async fn lookup_service_names_by_sid( - &self, - sid: u8, - ) -> Result, DiagServiceError> { - let manager = self.manager.read().await; - let security_plugin: DynamicPlugin = Box::new(()); - let names = if sid == service_ids::READ_DATA_BY_IDENTIFIER { - manager - .get_components_data_info(&security_plugin) - .into_iter() - .map(|c| c.id) - .collect() - } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { - manager - .get_components_configurations_info(&security_plugin) - .map(|v| v.into_iter().map(|c| c.id).collect()) - .unwrap_or_default() - } else { - Vec::new() - }; - Ok(names) - } - - /// Retrieve MUX case information for a service. - /// - /// # Errors - /// Returns an error if the metadata is not available. - pub async fn get_mux_cases_for_service( - &self, - service_name: &str, - ) -> Result, DiagServiceError> { - let manager = self.manager.read().await; - manager.get_mux_cases_for_service(service_name) - } - - /// Resolve the best-matching READ service for UDS request bytes. - pub async fn resolve_read_service( - &self, - did: u16, - uds_bytes: &[u8], - ) -> Option<(String, serde_json::Map)> { - self.resolve_service(service_ids::READ_DATA_BY_IDENTIFIER, did, uds_bytes, "READ") - .await - } - - /// Resolve the best-matching WRITE service for UDS request bytes. - pub async fn resolve_write_service( - &self, - did: u16, - uds_bytes: &[u8], - ) -> Option<(String, serde_json::Map)> { - self.resolve_service( - service_ids::WRITE_DATA_BY_IDENTIFIER, - did, - uds_bytes, - "WRITE", - ) - .await - } - - /// Probe a service DID via request encoding for symbolic PHYS-CONST cases. - async fn probe_service_did( - manager: &CdaEcuManager, - service_name: &str, - sid: u8, - params: &[ServiceParameterMetadata], - ) -> Option { - let mut param_map: HashMap = HashMap::default(); - for param in params { - match ¶m.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - // `?` is intentional: if any CodedConst can't be parsed we cannot - // build a valid probe request, so abort the entire probe. - let parsed = parse_u64_literal(coded_value)?; - param_map.insert(param.name.clone(), serde_json::json!(parsed)); - } - cda_interfaces::ParameterTypeMetadata::PhysConst { - phys_constant_value, - .. - } => { - param_map.insert(param.name.clone(), serde_json::json!(phys_constant_value)); - } - cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // Use string probe value for VALUE params to satisfy DOPs that - // parse textual values (TEXTTABLE / string-typed fields). - param_map.insert(param.name.clone(), serde_json::json!("0")); - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} - } - } - - let diag_comm = DiagComm { - name: service_name.to_string(), - type_: diag_comm_type(sid), - lookup_name: Some(service_name.to_string()), - }; - let security_plugin: DynamicPlugin = Box::new(()); - - let payload = manager - .create_uds_payload( - &diag_comm, - &security_plugin, - Some(UdsPayloadData::ParameterMap(param_map)), - ) - .await - .ok()?; - - let probed_did = extract_did_from_uds(&payload.data)?; - // ISO 14229-1 ยง7.3.2: DID 0x0000 is reserved. A zero result means the - // Payload encoding produced a degenerate output (e.g. a TEXTTABLE - // lookup silently failed), so treat it as unresolvable rather than a match. - if probed_did == 0 { - None - } else { - Some(probed_did) - } - } - - /// Resolve a DID to a service name using prefix lookup and metadata. - /// - /// Uses `lookup_diagcomms_by_request_prefix` with the full `[SID, DID_HI, - /// DID_LO]` prefix for direct matching of CODED-CONST DID services. For - /// `PhysConst` / Value DID services (where only the SID is a coded constant), - /// confirms the match via request parameter metadata. - /// - /// # Parameters - /// * `sid` - UDS service identifier (e.g. 0x22 for RDBI, 0x2E for WDBI). - /// * `did` - 16-bit Data Identifier to resolve. - /// * `uds_bytes` - Raw incoming UDS request bytes. - /// * `label` - Log prefix string (e.g. `"READ"`, `"WRITE"`). - #[allow(clippy::cast_possible_truncation)] - async fn resolve_service_did( - &self, - sid: u8, - did: u16, - _uds_bytes: &[u8], - label: &str, - ) -> Option { - let manager = self.manager.read().await; - - // Step 1: Prefix lookup with [SID, DID_HI, DID_LO]. - // - // The CDA matches sequential coded-const parameters against the prefix: - // - CODED-CONST DID services -> only exact DID matches pass. - // - PhysConst / Value DID services -> only the SID byte is coded-const, - // so all services with matching SID pass through. - let did_prefix = [sid, (did >> 8) as u8, (did & 0xFF) as u8]; - let prefix_matches = manager - .lookup_diagcomms_by_request_prefix(&did_prefix) - .unwrap_or_default(); - - // Fast path: single match from prefix lookup (common case: unique DID). - if let [only] = prefix_matches.as_slice() { - let name = only.lookup_name.as_deref().unwrap_or(&only.name); - tracing::info!( - "[resolve_did] {} DID 0x{:04X} -> '{}' (prefix match)", - label, - did, - name - ); - return Some(name.to_owned()); - } - - // Step 2: Build deduplicated candidate list from prefix matches + - // supplementary sources (bypass NOT-INHERITED-DIAG-COMMS filter). - let mut seen = std::collections::HashSet::new(); - let mut candidates: Vec = Vec::new(); - - for dc in &prefix_matches { - let name = dc.lookup_name.as_deref().unwrap_or(&dc.name); - if seen.insert(name.to_owned()) { - candidates.push(name.to_owned()); - } - } - - let security_plugin: DynamicPlugin = Box::new(()); - let extra_names: Vec = if sid == service_ids::READ_DATA_BY_IDENTIFIER { - manager - .get_components_data_info(&security_plugin) - .into_iter() - .map(|c| c.id) - .collect() - } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { - manager - .get_components_configurations_info(&security_plugin) - .map(|v| v.into_iter().map(|c| c.id).collect()) - .unwrap_or_default() - } else { - Vec::new() - }; - for name in extra_names { - if seen.insert(name.clone()) { - candidates.push(name); - } - } - - if candidates.is_empty() { - tracing::warn!( - "[resolve_did] {} no services for SID 0x{:02X} DID 0x{:04X}", - label, - sid, - did - ); - return None; - } - - tracing::debug!( - "[resolve_did] {} SID 0x{:02X} DID 0x{:04X}", - label, - sid, - did, - ); - - // Step 3: Match DID against each candidate's request metadata. - for name in &candidates { - let Ok(meta) = manager.get_request_parameter_metadata(name) else { - continue; - }; - - let did_param = find_did_param(&meta, sid); - - let matched = match did_param.map(|p| &p.param_type) { - Some(cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value }) => { - parse_u64_literal(coded_value) == Some(u64::from(did)) - } - - Some(cda_interfaces::ParameterTypeMetadata::PhysConst { coded_value, .. }) => { - let resolved = match coded_value { - Some(cv) => Some(*cv as u16), - None => Self::probe_service_did(&manager, name, sid, &meta).await, - }; - resolved == Some(did) - } - - Some(cda_interfaces::ParameterTypeMetadata::Value { - coded_default_value, - compu_scales, - .. - }) => { - let default_ok = coded_default_value - .map(|cd| cd as u16 == did) - .unwrap_or(false); - let scales_ok = - !compu_scales.is_empty() && did_matches_compu_scales(compu_scales, did); - - default_ok || scales_ok - } - - None | Some(cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. }) => { - false - } - }; - - if matched { - tracing::info!("[resolve_did] {} DID 0x{:04X} -> '{}'", label, did, name); - return Some(name.clone()); - } - } - - tracing::error!( - "[resolve_did] {} no service found for DID 0x{:04X} (checked {} candidates)", - label, - did, - candidates.len() - ); - None - } - - /// Find the correct service for a given SID + DID. - /// - /// Delegates DID -> service resolution to [`resolve_service_did`] which uses - /// MDD metadata and probing (`CodedConst`, `PhysConst`, Value+MUX). Then attempts - /// parse-validation via `convert_request_from_uds` for the matched service. - async fn resolve_service( - &self, - sid: u8, - did: u16, - uds_bytes: &[u8], - label: &str, - ) -> Option<(String, serde_json::Map)> { - tracing::debug!("[MDD] {} DID 0x{:04X}", label, did); - - let service_name = self.resolve_service_did(sid, did, uds_bytes, label).await?; - - // Attempt parse-validation to extract structured parameter data. - let manager = self.manager.read().await; - let payload = make_service_payload(uds_bytes); - let diag_comm = DiagComm { - name: service_name.clone(), - type_: diag_comm_type(sid), - lookup_name: Some(service_name.clone()), - }; - - if let Ok(parsed) = manager - .convert_request_from_uds(&diag_comm, &payload, true) - .await - && let Ok(json_resp) = parsed.into_json() - && let serde_json::Value::Object(map) = json_resp.data - { - tracing::debug!( - "[MDD] {} DID 0x{:04X} -> '{}' (parse verified)", - label, - did, - service_name - ); - return Some((service_name, map)); - } - - // Parse failed โ€” still return the metadata-resolved service with empty map. - tracing::debug!( - "[MDD] {} DID 0x{:04X} -> '{}' (metadata match, parse unavailable)", - label, - did, - service_name - ); - Some((service_name, serde_json::Map::new())) - } - - /// Check if a UDS response is negative (SID 0x7F). - #[must_use] - pub fn is_negative_response(uds_response: &[u8]) -> bool { - uds_response.len() >= UDS_NEGATIVE_RESPONSE_MIN_LEN - && uds_response.first().copied() == Some(service_ids::NEGATIVE_RESPONSE) - } - - /// Extract NRC (Negative Response Code) from a negative response. - #[must_use] - pub fn get_nrc(uds_response: &[u8]) -> Option { - if Self::is_negative_response(uds_response) { - uds_response.get(2).copied() - } else { - None - } - } - - #[allow(clippy::unused_self)] - fn make_diag_comm(&self, service_name: &str, service_id: u8) -> DiagComm { - DiagComm { - name: service_name.to_string(), - type_: diag_comm_type(service_id), - lookup_name: Some(service_name.to_string()), - } - } - - /// Get ECU name. - #[must_use] - pub fn ecu_name(&self) -> &str { - &self.ecu_name - } - - fn default_com_params(logical_address: u16, tester_address: u16) -> ComParams { - let mut com_params = ComParams::default(); - com_params.doip.logical_gateway_address.default = logical_address; - com_params.doip.logical_ecu_address.default = logical_address; - com_params.doip.logical_tester_address.default = tester_address; - com_params - } -} - -// Helper functions - -/// Extract the 16-bit DID from UDS payload bytes at offset 1โ€“2. -/// -/// Returns `None` if the slice has fewer than 3 bytes. -fn extract_did_from_uds(data: &[u8]) -> Option { - let b1 = *data.get(1)?; - let b2 = *data.get(2)?; - Some(u16::from_be_bytes([b1, b2])) -} - -/// Map a UDS service identifier to its [`DiagCommType`]. -/// -/// Falls back to [`DiagCommType::Data`] for unrecognised SIDs so that the -/// caller always receives a usable type rather than an error. -fn diag_comm_type(service_id: u8) -> DiagCommType { - DiagCommType::try_from(service_id).unwrap_or(DiagCommType::Data) -} - -/// Create a `ServicePayload` from raw UDS bytes with default addresses. -fn make_service_payload(data: &[u8]) -> ServicePayload { - ServicePayload { - data: data.to_vec(), - source_address: 0, - target_address: 0, - new_session: None, - new_security: None, - } -} - -/// Encode an unsigned integer as big-endian bytes using the minimum width needed. -/// -/// Always produces at least one byte; zero encodes as `[0x00]`. -fn encode_unsigned_be(num: u64) -> Vec { - if num == 0 { - return vec![0x00]; - } - // Skip leading zero bytes; safe because num != 0 guarantees a non-empty result. - num.to_be_bytes() - .iter() - .copied() - .skip_while(|&b| b == 0) - .collect() -} - -/// Parse a MUX case `coded_value` string as a numeric DID value. -/// -/// MDD stores MUX case limits as strings that may be float-formatted -/// (e.g. `"61699.0"`) or integer-formatted (e.g. `"61699"`). -#[must_use] -pub fn parse_mux_coded_value(coded_value: &str) -> Option { - let trimmed = coded_value.trim(); - if let Ok(v) = trimmed.parse::() { - return Some(v); - } - #[allow( - clippy::cast_precision_loss, - clippy::cast_possible_truncation, - clippy::cast_sign_loss - )] - if let Ok(v) = trimmed.parse::() - && v >= 0.0 - && v <= u64::MAX as f64 - { - return Some(v as u64); - } - None -} - -/// Find the MUX case prefix that covers a given DID in response metadata. -/// -/// MDD `__mux_case__` entries store only the **`lower_limit`** of their range -/// (e.g. a case with `coded_value: "61697"` covering DIDs 0xF101 -/// through 0xF140). A DID like 0xF103 (61699) has no exact match -/// but falls in that range. -/// -/// This function uses **floor-based matching**: collect all `__mux_case__` -/// lower bounds, sort them, and find the case with the largest lower bound -/// that does not exceed the DID. This correctly handles both single-value -/// MUX cases (e.g. 0x7007) and range cases (e.g. 0xD100โ€“0xD150). -#[must_use] -pub fn find_mux_case_prefix( - meta: &[cda_interfaces::ResponseParameterInfo], - did: u16, -) -> Option { - let did_val = u64::from(did); - - // Collect (lower_bound, case_name) for all MUX case entries. - let mut mux_entries: Vec<(u64, &str)> = meta - .iter() - .filter_map(|p| { - let case_name = p.name.strip_prefix("__mux_case__/")?; - if let cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } = &p.param_type - { - let lower = parse_mux_coded_value(coded_value)?; - Some((lower, case_name)) - } else { - None - } - }) - .collect(); - - if mux_entries.is_empty() { - return None; - } - - // Sort by lower bound ascending. - mux_entries.sort_by_key(|&(lb, _)| lb); - - // Floor match: largest lower_bound โ‰ค DID. - let matched = mux_entries.iter().rev().find(|&&(lb, _)| lb <= did_val)?; - - Some(format!("{}/", matched.1)) -} - -/// Check if ANY MUX case in the response metadata **exactly** matches the DID. -/// -/// Uses exact (not floor) matching because this is for cross-service sibling -/// selection where different MUX DOPs can have overlapping ranges. -#[must_use] -pub fn has_mux_case_for_did_exact( - meta: &[cda_interfaces::ResponseParameterInfo], - did: u16, -) -> bool { - let did_val = u64::from(did); - meta.iter().any(|p| { - if let Some(_case_name) = p.name.strip_prefix("__mux_case__/") - && let cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } = &p.param_type - { - return parse_mux_coded_value(coded_value) == Some(did_val); - } - false - }) -} - -/// Parse numeric literals in decimal or hexadecimal form. -fn parse_u64_literal(value: &str) -> Option { - let trimmed = value.trim(); - if let Some(hex) = trimmed - .strip_prefix("0x") - .or_else(|| trimmed.strip_prefix("0X")) - { - return u64::from_str_radix(hex, 16).ok(); - } - - trimmed - .parse::() - .ok() - .or_else(|| u64::from_str_radix(trimmed, 16).ok()) -} - -/// Find the DID-bearing parameter by position and type, not by name. -/// -/// In standard UDS requests parameters are stored in byte order: -/// - First `CodedConst` whose value matches the SID -> SID indicator (skip) -/// - Next `CodedConst` / `PhysConst` / `Value` -> DID parameter -/// -/// This avoids vendor-specific name or semantic string matching. -fn find_did_param( - metadata: &[ServiceParameterMetadata], - sid: u8, -) -> Option<&ServiceParameterMetadata> { - let mut skipped_sid = false; - for p in metadata { - match &p.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - if !skipped_sid - && let Some(val) = parse_u64_literal(coded_value) - && val == u64::from(sid) - { - skipped_sid = true; - continue; - } - // Non-SID CodedConst -> DID param - return Some(p); - } - cda_interfaces::ParameterTypeMetadata::PhysConst { .. } - | cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // PhysConst / Value -> DID param - return Some(p); - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} - } - } - None -} - -/// Check if a DID falls within any `CompuScale` range from the DOP metadata. -/// -/// For TEXTTABLE DOPs each scale defines a coded (internal) DID range. -/// Returns `true` if `did` falls in `[lower_limit, upper_limit]` of any scale. -fn did_matches_compu_scales(scales: &[cda_interfaces::CompuScaleInfo], did: u16) -> bool { - let did_val = u64::from(did); - scales.iter().any(|s| match (s.lower_limit, s.upper_limit) { - (Some(lo), Some(hi)) => did_val >= lo && did_val <= hi, - (Some(lo), None) => did_val == lo, - _ => false, - }) -} - -/// Encode a JSON value into `buf[pos..pos+size]` using big-endian representation. -/// -/// Handles numbers, strings, byte arrays, and booleans. Fills the entire -/// `size` field, zero-padding on the left for numbers shorter than `size`. -fn encode_value_at(buf: &mut [u8], pos: usize, size: usize, value: Option<&serde_json::Value>) { - if size == 0 { - return; - } - let Some(end) = pos.checked_add(size) else { - return; - }; - if end > buf.len() { - return; - } - let Some(value) = value else { - // No value provided โ€” leave as zero (already initialised). - return; - }; - match value { - serde_json::Value::Number(n) => { - let raw = n - .as_u64() - .unwrap_or_else(|| n.as_i64().unwrap_or(0).cast_unsigned()); - let be = raw.to_be_bytes(); - // Right-align in the field. - let u64_size = std::mem::size_of::(); - let start = u64_size.saturating_sub(size); - let copy = size.min(u64_size); - // end = pos + size; dst_start = end - copy = pos + (size - copy). - // copy <= size so no underflow. - let dst_start = end.saturating_sub(copy); - if let (Some(dst), Some(src)) = ( - buf.get_mut(dst_start..end), - be.get(start..start.saturating_add(copy)), - ) { - dst.copy_from_slice(src); - } - } - serde_json::Value::String(s) => { - let bytes = s.as_bytes(); - let copy = bytes.len().min(size); - if let (Some(dst), Some(src)) = ( - buf.get_mut(pos..pos.saturating_add(copy)), - bytes.get(..copy), - ) { - dst.copy_from_slice(src); - } - } - serde_json::Value::Array(arr) => { - for (i, item) in arr.iter().enumerate() { - if i >= size { - break; - } - if let Some(byte) = item.as_u64() - && let Some(slot) = buf.get_mut(pos.saturating_add(i)) - { - #[allow(clippy::cast_possible_truncation)] - { - *slot = byte as u8; - } - } - } - } - serde_json::Value::Bool(b) => { - if let Some(slot) = buf.get_mut(pos) { - *slot = u8::from(*b); - } - } - _ => {} - } -} - -/// Serialize a JSON value into raw bytes for UDS encoding. -/// -/// Returns an empty Vec when the value is None or cannot be serialized. -fn value_to_bytes(value: Option<&serde_json::Value>) -> Vec { - let Some(value) = value else { - return Vec::new(); - }; - match value { - serde_json::Value::Number(n) => { - let raw = n - .as_u64() - .unwrap_or_else(|| n.as_i64().unwrap_or(0).cast_unsigned()); - encode_unsigned_be(raw) - } - serde_json::Value::String(s) => s.as_bytes().to_vec(), - serde_json::Value::Array(arr) => arr - .iter() - .filter_map(|item| { - #[allow(clippy::cast_possible_truncation)] - item.as_u64().map(|b| b as u8) - }) - .collect(), - serde_json::Value::Bool(b) => vec![u8::from(*b)], - _ => Vec::new(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_is_negative_response() { - assert!(!ServiceResolver::is_negative_response(&[0x62, 0xF1, 0x90])); - assert!(!ServiceResolver::is_negative_response(&[0x50, 0x01])); - assert!(ServiceResolver::is_negative_response(&[0x7F, 0x22, 0x31])); - assert!(!ServiceResolver::is_negative_response(&[0x7F])); - assert!(!ServiceResolver::is_negative_response(&[0x7F, 0x22])); - } - - #[test] - fn test_get_nrc() { - assert_eq!(ServiceResolver::get_nrc(&[0x62, 0xF1, 0x90]), None); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x31]), Some(0x31)); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x10, 0x11]), Some(0x11)); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x22]), Some(0x22)); - assert_eq!(ServiceResolver::get_nrc(&[0x7F]), None); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22]), None); - } - - #[test] - fn test_nrc_codes() { - let cases: &[(u8, u8, u8)] = &[ - (0x22, 0x11, 0x11), - (0x22, 0x12, 0x12), - (0x22, 0x13, 0x13), - (0x22, 0x22, 0x22), - (0x22, 0x31, 0x31), - (0x27, 0x33, 0x33), - (0x27, 0x35, 0x35), - (0x22, 0x78, 0x78), - ]; - for &(sid, nrc, expected) in cases { - assert_eq!(ServiceResolver::get_nrc(&[0x7F, sid, nrc]), Some(expected)); - } - } - - #[test] - fn test_positive_response_sids() { - assert!(!ServiceResolver::is_negative_response(&[ - 0x50, 0x01, 0x00, 0x32 - ])); - assert!(!ServiceResolver::is_negative_response(&[ - 0x62, 0xF1, 0x90, 0x57 - ])); - assert!(!ServiceResolver::is_negative_response(&[ - 0x67, 0x01, 0x12, 0x34 - ])); - assert!(!ServiceResolver::is_negative_response(&[0x6E, 0xF1, 0x90])); - assert!(!ServiceResolver::is_negative_response(&[0x7E, 0x00])); - } - - #[test] - fn test_default_com_params() { - let com_params = ServiceResolver::default_com_params(0x1000, 0x0E80); - assert_eq!(com_params.doip.logical_gateway_address.default, 0x1000); - assert_eq!(com_params.doip.logical_ecu_address.default, 0x1000); - assert_eq!(com_params.doip.logical_tester_address.default, 0x0E80); - assert_eq!( - com_params.doip.logical_gateway_address.name, - "CP_DoIPLogicalGatewayAddress" - ); - assert_eq!( - com_params.doip.logical_ecu_address.name, - "CP_DoIPLogicalEcuAddress" - ); - assert_eq!( - com_params.doip.logical_response_id_table_name, - "CP_UniqueRespIdTable" - ); - } - - #[test] - fn test_diag_comm_type() { - assert!(matches!( - diag_comm_type(service_ids::WRITE_DATA_BY_IDENTIFIER), - DiagCommType::Configurations - )); - assert!(matches!( - diag_comm_type(service_ids::READ_DATA_BY_IDENTIFIER), - DiagCommType::Data - )); - assert!(matches!( - diag_comm_type(service_ids::SESSION_CONTROL), - DiagCommType::Modes - )); - assert!(matches!( - diag_comm_type(service_ids::TESTER_PRESENT), - DiagCommType::Data - )); - assert!(matches!( - diag_comm_type(service_ids::ROUTINE_CONTROL), - DiagCommType::Operations - )); - assert!(matches!( - diag_comm_type(service_ids::CLEAR_DIAGNOSTIC_INFORMATION), - DiagCommType::Faults - )); - } - - #[test] - fn test_encode_unsigned_be() { - assert_eq!(encode_unsigned_be(0), vec![0x00]); - assert_eq!(encode_unsigned_be(0xFF), vec![0xFF]); - assert_eq!(encode_unsigned_be(0x0100), vec![0x01, 0x00]); - assert_eq!(encode_unsigned_be(0xF190), vec![0xF1, 0x90]); - assert_eq!(encode_unsigned_be(0xFFFF), vec![0xFF, 0xFF]); - assert_eq!(encode_unsigned_be(0x01_0000), vec![0x01, 0x00, 0x00]); - assert_eq!(encode_unsigned_be(0xFF_FFFF), vec![0xFF, 0xFF, 0xFF]); - assert_eq!( - encode_unsigned_be(0x0100_0000), - vec![0x01, 0x00, 0x00, 0x00] - ); - assert_eq!( - encode_unsigned_be(0xDEAD_BEEF), - vec![0xDE, 0xAD, 0xBE, 0xEF] - ); - } - - #[test] - fn test_make_service_payload() { - let data = &[0x62, 0xF1, 0x90, 0x57]; - let payload = make_service_payload(data); - assert_eq!(payload.data, vec![0x62, 0xF1, 0x90, 0x57]); - assert_eq!(payload.source_address, 0); - assert_eq!(payload.target_address, 0); - assert!(payload.new_session.is_none()); - assert!(payload.new_security.is_none()); - } - - #[test] - fn test_empty_response() { - assert!(!ServiceResolver::is_negative_response(&[])); - assert_eq!(ServiceResolver::get_nrc(&[]), None); - } - - #[test] - fn test_find_did_param() { - use cda_interfaces::ParameterTypeMetadata; - - // Standard RDBI: CodedConst SID + PhysConst DID - let meta = vec![ - ServiceParameterMetadata { - name: "RDBI".to_string(), - semantic: None, - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "34".to_string(), // 0x22 - }, - }, - ServiceParameterMetadata { - name: "VIN".to_string(), - semantic: None, - param_type: ParameterTypeMetadata::PhysConst { - phys_constant_value: "VIN".to_string(), - coded_value: Some(0xF190), - }, - }, - ]; - let did = find_did_param(&meta, 0x22); - assert!(did.is_some()); - assert_eq!(did.expect("DID param not found").name, "VIN"); - - // Value-type service: SID + Value DID - let meta2 = vec![ - ServiceParameterMetadata { - name: "SID".to_string(), - semantic: None, - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "34".to_string(), - }, - }, - ServiceParameterMetadata { - name: "DynamicDID".to_string(), - semantic: None, - param_type: ParameterTypeMetadata::Value { - physical_default_value: None, - coded_default_value: None, - compu_scales: vec![], - }, - }, - ]; - let did = find_did_param(&meta2, 0x22); - assert!(did.is_some()); - assert!(matches!( - did.expect("DID param not found").param_type, - ParameterTypeMetadata::Value { .. } - )); - - // SID-only service: no DID param - let meta3 = vec![ServiceParameterMetadata { - name: "SID".to_string(), - semantic: None, - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "34".to_string(), - }, - }]; - assert!(find_did_param(&meta3, 0x22).is_none()); - } - - #[test] - fn test_parse_mux_coded_value() { - assert_eq!(parse_mux_coded_value("61699"), Some(61699)); - assert_eq!(parse_mux_coded_value("32776"), Some(32776)); - assert_eq!(parse_mux_coded_value("61699.0"), Some(61699)); - assert_eq!(parse_mux_coded_value(" 61699 "), Some(61699)); - assert_eq!(parse_mux_coded_value("non_numeric_text"), None); - assert_eq!(parse_mux_coded_value(""), None); - } - - #[test] - fn test_find_mux_case_prefix_floor_match() { - use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; - - // Simulate real RDBI_RESP metadata with range-based and point MUX cases. - let meta = vec![ - // Point case: DID_POINT_8008 covers only DID 0x8008 (32776) - ResponseParameterInfo { - name: "__mux_case__/DID_POINT_8008".to_string(), - semantic: Some("MUX-CASE".to_string()), - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "32776".to_string(), - }, - byte_position: 3, - bit_position: 0, - byte_size: None, - }, - // Range case: DID_RANGE_F101_F140 covers 0xF101 (61697) through 0xF140 (61760) - ResponseParameterInfo { - name: "__mux_case__/DID_RANGE_F101_F140".to_string(), - semantic: Some("MUX-CASE".to_string()), - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "61697".to_string(), - }, - byte_position: 3, - bit_position: 0, - byte_size: None, - }, - // Point case: DID_POINT_F141 covers only 0xF141 (61761) - ResponseParameterInfo { - name: "__mux_case__/DID_POINT_F141".to_string(), - semantic: Some("MUX-CASE".to_string()), - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "61761".to_string(), - }, - byte_position: 3, - bit_position: 0, - byte_size: None, - }, - ]; - - // Exact match - assert_eq!( - find_mux_case_prefix(&meta, 0x8008), - Some("DID_POINT_8008/".to_string()) - ); - assert_eq!( - find_mux_case_prefix(&meta, 0xF101), - Some("DID_RANGE_F101_F140/".to_string()) - ); - assert_eq!( - find_mux_case_prefix(&meta, 0xF141), - Some("DID_POINT_F141/".to_string()) - ); - - // Floor match within range - assert_eq!( - find_mux_case_prefix(&meta, 0xF103), // 61699 -> floor to 61697 - Some("DID_RANGE_F101_F140/".to_string()) - ); - assert_eq!( - find_mux_case_prefix(&meta, 0xF140), // 61760 -> floor to 61697 - Some("DID_RANGE_F101_F140/".to_string()) - ); - - // Float-formatted coded_value - let meta_float = vec![ResponseParameterInfo { - name: "__mux_case__/case_a".to_string(), - semantic: Some("MUX-CASE".to_string()), - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "61697.0".to_string(), - }, - byte_position: 3, - bit_position: 0, - byte_size: None, - }]; - assert_eq!( - find_mux_case_prefix(&meta_float, 0xF103), - Some("case_a/".to_string()) - ); - - // No MUX entries -> None - assert_eq!(find_mux_case_prefix(&[], 0xF103), None); - } -} diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs new file mode 100644 index 0000000..5bf5d3f --- /dev/null +++ b/proxy-core/src/service_resolver/metadata.rs @@ -0,0 +1,194 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! Service metadata queries and lookup. +//! +//! Methods for querying request/response parameter metadata from the MDD, +//! looking up services by SID, and retrieving MUX case information. + +use cda_interfaces::{ + DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, MuxCaseInfo, + ServiceParameterMetadata, service_ids, +}; + +use super::{ServiceResolver, uds_helpers::has_mux_case_for_did_exact}; + +impl ServiceResolver { + /// Retrieve request parameter metadata for a service. + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_service_parameter_metadata( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_request_parameter_metadata(service_name) + } + + /// Retrieve POS-RESPONSE parameter metadata (byte positions, sizes, types). + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_response_parameter_metadata( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_response_parameter_metadata(service_name) + } + + /// Retrieve enriched POS-RESPONSE metadata for a service + DID. + /// + /// Some services have a direct POS-RESPONSE + /// that references a STRUCTURE as a single opaque VALUE param (`byte_size` = + /// None, no sub-fields). The CDA doesn't flatten the STRUCTURE children in the + /// metadata for these services. + /// + /// However, a shared MUX-based response used by + /// sibling services DOES flatten every DID's sub-fields. This method + /// detects the opaque-STRUCTURE case and transparently returns the richer + /// MUX-based metadata instead, so callers get per-field byte positions. + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_enriched_response_metadata( + &self, + service_name: &str, + did: u16, + ) -> Result, DiagServiceError> { + self.get_enriched_response_metadata_with_source(service_name, did) + .await + .map(|(meta, _source)| meta) + } + + /// Same as [`get_enriched_response_metadata`] but also returns the name of + /// the service that actually provided the metadata. When the response is + /// "opaque" (single STRUCTURE ref) and a MUX-based sibling is used, the + /// returned name is the sibling โ€” callers that need to validate via + /// `convert_from_uds` must use this name, not the original. + /// + pub(super) async fn get_enriched_response_metadata_with_source( + &self, + service_name: &str, + did: u16, + ) -> Result<(Vec, String), DiagServiceError> { + let manager = self.manager.read().await; + let meta = manager.get_response_parameter_metadata(service_name)?; + + // Heuristic: the response is "opaque" when the only data param + // (after SID + DID) is a single VALUE with byte_size = None. + let data_params: Vec<_> = meta + .iter() + .filter(|p| { + matches!( + p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + | cda_interfaces::ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + + let Some(first_param) = data_params.first() else { + return Ok((meta, service_name.to_string())); + }; + let is_opaque = data_params.len() == 1 + && first_param.byte_size.is_none() + && !first_param.name.contains('/'); + + if !is_opaque { + return Ok((meta, service_name.to_string())); + } + + tracing::debug!( + "[MDD] Response metadata for '{}' is opaque (single STRUCTURE ref '{}'), searching \ + for MUX-based sibling", + service_name, + first_param.name, + ); + + let security_plugin: DynamicPlugin = Box::new(()); + + // Search READ services for a MUX-based sibling with a case for this DID. + let candidates: Vec = manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect(); + + for candidate in &candidates { + if candidate == service_name { + continue; + } + let sibling_meta = match manager.get_response_parameter_metadata(candidate) { + Ok(m) if m.len() > meta.len() => m, + _ => continue, + }; + // Check if this sibling has a MUX case matching our DID (exact match + // to avoid cross-DOP false positives from floor matching). + let has_mux_for_did = has_mux_case_for_did_exact(&sibling_meta, did); + if has_mux_for_did { + tracing::debug!( + "[MDD] Using MUX-based metadata from '{}' for DID 0x{:04X} ({} params instead \ + of {})", + candidate, + did, + sibling_meta.len(), + meta.len(), + ); + return Ok((sibling_meta, candidate.clone())); + } + } + + // No MUX sibling found โ€” use original metadata. + Ok((meta, service_name.to_string())) + } + + /// Look up service names by SID. + /// + /// # Errors + /// Returns an error if the lookup fails. + pub async fn lookup_service_names_by_sid( + &self, + sid: u8, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + let security_plugin: DynamicPlugin = Box::new(()); + let names = if sid == service_ids::READ_DATA_BY_IDENTIFIER { + manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect() + } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { + manager + .get_components_configurations_info(&security_plugin) + .map(|v| v.into_iter().map(|c| c.id).collect()) + .unwrap_or_default() + } else { + Vec::new() + }; + Ok(names) + } + + /// Retrieve MUX case information for a service. + /// + /// # Errors + /// Returns an error if the metadata is not available. + pub async fn get_mux_cases_for_service( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_mux_cases_for_service(service_name) + } +} diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs new file mode 100644 index 0000000..2afc900 --- /dev/null +++ b/proxy-core/src/service_resolver/mod.rs @@ -0,0 +1,308 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! ECU Manager wrapper for MDD-driven UDS request/response processing. +//! +//! Provides a simplified interface to the CDA's +//! `EcuManager` for encoding/decoding UDS messages using the loaded MDD +//! diagnostic database. +//! +//! ## Module layout +//! +//! - [`uds_helpers`]: Pure helper functions for UDS encoding, decoding, MUX +//! matching, and payload construction. +//! - [`response`]: UDS response building and round-trip validation. +//! - [`metadata`]: Service metadata queries and MUX-sibling enrichment. +//! - [`resolve`]: DID-to-service resolution, request parsing, and probing. +//! +//! ## Service resolution +//! +//! When a UDS request arrives the proxy must identify which diagnostic service +//! from the MDD it belongs to (e.g. `WDBI_VIN` vs `WDBI_PLAIN` for SID 0x2E). +//! +//! Resolution uses `lookup_diagcomms_by_request_prefix` with the full +//! `[SID, DID_HI, DID_LO]` prefix, which directly matches services whose +//! sequential coded-const parameters match the request bytes. This handles +//! CODED-CONST DID services in a single call. +//! +//! For services where the DID is not a coded constant (`PhysConst` / Value), +//! the prefix lookup returns all SID-matching services and the resolver +//! confirms the DID via request parameter metadata: +//! +//! - **`CodedConst`**: exact DID match. +//! - **`PhysConst`**: resolved `coded_value` or `create_uds_payload` probe. +//! - **Value**: `coded_default_value` or `CompuScale` range match. +//! +//! If no service matches, an error is logged โ€” no fallback. + +mod metadata; +mod resolve; +mod response; +pub mod uds_helpers; + +use std::sync::Arc; + +use cda_core::{DiagServiceResponseStruct, EcuManager as CdaEcuManager}; +use cda_database::datatypes::DiagnosticDatabase; +use cda_interfaces::{ + DiagComm, DiagCommType, DiagServiceError, EcuManager as EcuManagerTrait, EcuManagerType, + FunctionalDescriptionConfig, HashMap, Protocol, + datatypes::{ComParams, DatabaseNamingConvention, DiagnosticServiceAffixPosition}, + diagservices::DiagServiceResponseType, + service_ids, +}; +use cda_plugin_security::DefaultSecurityPluginData; +use tokio::sync::RwLock; +use uds_helpers::diag_comm_type; +pub use uds_helpers::{find_mux_case_prefix, has_mux_case_for_did_exact, parse_mux_coded_value}; + +/// Minimum UDS negative response length: 0x7F + SID + NRC. +const UDS_NEGATIVE_RESPONSE_MIN_LEN: usize = 3; + +/// Minimum UDS positive response buffer size: response SID (1) + DID high (1) + DID low (1). +const UDS_POSITIVE_RESPONSE_MIN_SIZE: usize = 3; + +/// Wraps the CDA's [`EcuManager`] with async locking +/// to provide MDD-driven UDS encoding, decoding, and service resolution +/// for the proxy. +pub struct ServiceResolver { + manager: Arc>>, + ecu_name: String, +} + +impl ServiceResolver { + /// Create new ECU manager from MDD database. + /// + /// # Arguments + /// * `ecu_name` - Name of the ECU + /// * `db` - Loaded `DiagnosticDatabase` from MDD file + /// * `logical_address` - ECU logical address (e.g. 0x1000) + /// * `tester_address` - Tester logical address (e.g. 0x0E80) + /// + /// # Errors + /// Returns an error if the ECU manager cannot be initialized from the database. + pub async fn new( + ecu_name: String, + db: DiagnosticDatabase, + logical_address: u16, + tester_address: u16, + ) -> Result { + let com_params = Self::default_com_params(logical_address, tester_address); + + let func_config = FunctionalDescriptionConfig { + description_database: String::new(), + enabled_functional_groups: None, + protocol_position: DiagnosticServiceAffixPosition::Prefix, + protocol_case_sensitive: false, + }; + + let mut manager = CdaEcuManager::new( + db, + Protocol::DoIp, + &com_params, + DatabaseNamingConvention::default(), + EcuManagerType::Ecu, + &func_config, + true, + ) + .map_err(|e| { + tracing::error!("Failed to create EcuManager: {}", e); + e + })?; + + Self::activate_base_variant(&mut manager).await?; + + Ok(Self { + manager: Arc::new(RwLock::new(manager)), + ecu_name, + }) + } + + /// Activate the base (fallback) ECU variant. + /// + /// The CDA's diagnostic engine requires a variant to be selected before + /// service lookup, metadata queries, or UDS encoding/decoding work + /// correctly. When no specific variant is requested (or the requested + /// variant is not found), this method seeds the engine with a synthetic + /// dummy response so that `detect_variant` initialises the internal + /// state-chart and pins the engine to a determinate base state. + /// + /// #`TODO:` real variant detection + /// + /// Replace the dummy response with actual variant-identification DID + /// reads from a live ECU connection: + /// 1. Read variant-identification DIDs from the ECU. + /// 2. Call `detect_variant(responses)` with real data. + /// 3. The engine narrows the active variant and limits visible services. + /// + /// # Errors + /// Returns an error only when `detect_variant` fails **and** no variant + /// name was set (i.e. the engine did not activate at all). + async fn activate_base_variant( + manager: &mut CdaEcuManager, + ) -> Result<(), DiagServiceError> { + // `TODO:` replace this dummy response with real variant-identification + // DID reads from the ECU (see doc comment above). + let dummy_response = DiagServiceResponseStruct { + service: DiagComm { + name: String::new(), + type_: DiagCommType::Data, + lookup_name: None, + }, + data: vec![], + mapped_data: None, + response_type: DiagServiceResponseType::Positive, + }; + + let mut responses: HashMap = HashMap::default(); + responses.insert("__variant_init__".to_string(), dummy_response); + + match manager.detect_variant(responses).await { + Ok(()) => Ok(()), + Err(e) => { + let variant = manager.variant(); + if variant.name.is_some() { + tracing::info!( + "Base variant '{}' activated (state chart init skipped: {})", + variant.name.as_deref().unwrap_or("unknown"), + e + ); + Ok(()) + } else { + Err(e) + } + } + } + } + + /// Check if a UDS response is negative (SID 0x7F). + #[must_use] + pub fn is_negative_response(uds_response: &[u8]) -> bool { + uds_response.len() >= UDS_NEGATIVE_RESPONSE_MIN_LEN + && uds_response.first().copied() == Some(service_ids::NEGATIVE_RESPONSE) + } + + /// Extract NRC (Negative Response Code) from a negative response. + #[must_use] + pub fn get_nrc(uds_response: &[u8]) -> Option { + if Self::is_negative_response(uds_response) { + uds_response.get(2).copied() + } else { + None + } + } + + #[allow(clippy::unused_self)] + pub(super) fn make_diag_comm(&self, service_name: &str, service_id: u8) -> DiagComm { + DiagComm { + name: service_name.to_string(), + type_: diag_comm_type(service_id), + lookup_name: Some(service_name.to_string()), + } + } + + /// Get ECU name. + #[must_use] + pub fn ecu_name(&self) -> &str { + &self.ecu_name + } + + fn default_com_params(logical_address: u16, tester_address: u16) -> ComParams { + let mut com_params = ComParams::default(); + com_params.doip.logical_gateway_address.default = logical_address; + com_params.doip.logical_ecu_address.default = logical_address; + com_params.doip.logical_tester_address.default = tester_address; + com_params + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_is_negative_response() { + assert!(!ServiceResolver::is_negative_response(&[0x62, 0xF1, 0x90])); + assert!(!ServiceResolver::is_negative_response(&[0x50, 0x01])); + assert!(ServiceResolver::is_negative_response(&[0x7F, 0x22, 0x31])); + assert!(!ServiceResolver::is_negative_response(&[0x7F])); + assert!(!ServiceResolver::is_negative_response(&[0x7F, 0x22])); + } + + #[test] + fn test_get_nrc() { + assert_eq!(ServiceResolver::get_nrc(&[0x62, 0xF1, 0x90]), None); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x31]), Some(0x31)); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x10, 0x11]), Some(0x11)); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x22]), Some(0x22)); + assert_eq!(ServiceResolver::get_nrc(&[0x7F]), None); + assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22]), None); + } + + #[test] + fn test_nrc_codes() { + let cases: &[(u8, u8, u8)] = &[ + (0x22, 0x11, 0x11), + (0x22, 0x12, 0x12), + (0x22, 0x13, 0x13), + (0x22, 0x22, 0x22), + (0x22, 0x31, 0x31), + (0x27, 0x33, 0x33), + (0x27, 0x35, 0x35), + (0x22, 0x78, 0x78), + ]; + for &(sid, nrc, expected) in cases { + assert_eq!(ServiceResolver::get_nrc(&[0x7F, sid, nrc]), Some(expected)); + } + } + + #[test] + fn test_positive_response_sids() { + assert!(!ServiceResolver::is_negative_response(&[ + 0x50, 0x01, 0x00, 0x32 + ])); + assert!(!ServiceResolver::is_negative_response(&[ + 0x62, 0xF1, 0x90, 0x57 + ])); + assert!(!ServiceResolver::is_negative_response(&[ + 0x67, 0x01, 0x12, 0x34 + ])); + assert!(!ServiceResolver::is_negative_response(&[0x6E, 0xF1, 0x90])); + assert!(!ServiceResolver::is_negative_response(&[0x7E, 0x00])); + } + + #[test] + fn test_default_com_params() { + let com_params = ServiceResolver::default_com_params(0x1000, 0x0E80); + assert_eq!(com_params.doip.logical_gateway_address.default, 0x1000); + assert_eq!(com_params.doip.logical_ecu_address.default, 0x1000); + assert_eq!(com_params.doip.logical_tester_address.default, 0x0E80); + assert_eq!( + com_params.doip.logical_gateway_address.name, + "CP_DoIPLogicalGatewayAddress" + ); + assert_eq!( + com_params.doip.logical_ecu_address.name, + "CP_DoIPLogicalEcuAddress" + ); + assert_eq!( + com_params.doip.logical_response_id_table_name, + "CP_UniqueRespIdTable" + ); + } + + #[test] + fn test_empty_response() { + assert!(!ServiceResolver::is_negative_response(&[])); + assert_eq!(ServiceResolver::get_nrc(&[]), None); + } +} diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs new file mode 100644 index 0000000..4c000c4 --- /dev/null +++ b/proxy-core/src/service_resolver/resolve.rs @@ -0,0 +1,355 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! DID-to-service resolution. +//! +//! Resolves incoming UDS DID values to the correct MDD service name using +//! prefix lookup, request parameter metadata, and encoding probes. + +use cda_core::EcuManager as CdaEcuManager; +use cda_interfaces::{ + DiagComm, DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, HashMap, + ServiceParameterMetadata, + diagservices::{DiagServiceResponse, UdsPayloadData}, + service_ids, +}; +use cda_plugin_security::DefaultSecurityPluginData; + +use super::{ + ServiceResolver, + uds_helpers::{ + diag_comm_type, did_matches_compu_scales, extract_did_from_uds, find_did_param, + make_service_payload, parse_u64_literal, + }, +}; + +impl ServiceResolver { + /// Resolve the best-matching READ service for UDS request bytes. + pub async fn resolve_read_service( + &self, + did: u16, + uds_bytes: &[u8], + ) -> Option<(String, serde_json::Map)> { + self.resolve_service(service_ids::READ_DATA_BY_IDENTIFIER, did, uds_bytes, "READ") + .await + } + + /// Resolve the best-matching WRITE service for UDS request bytes. + pub async fn resolve_write_service( + &self, + did: u16, + uds_bytes: &[u8], + ) -> Option<(String, serde_json::Map)> { + self.resolve_service( + service_ids::WRITE_DATA_BY_IDENTIFIER, + did, + uds_bytes, + "WRITE", + ) + .await + } + + /// Probe a service DID via request encoding for symbolic PHYS-CONST cases. + async fn probe_service_did( + manager: &CdaEcuManager, + service_name: &str, + sid: u8, + params: &[ServiceParameterMetadata], + ) -> Option { + let mut param_map: HashMap = HashMap::default(); + for param in params { + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // `?` is intentional: if any CodedConst can't be parsed we cannot + // build a valid probe request, so abort the entire probe. + let parsed = parse_u64_literal(coded_value)?; + param_map.insert(param.name.clone(), serde_json::json!(parsed)); + } + cda_interfaces::ParameterTypeMetadata::PhysConst { + phys_constant_value, + .. + } => { + param_map.insert(param.name.clone(), serde_json::json!(phys_constant_value)); + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // Use string probe value for VALUE params to satisfy DOPs that + // parse textual values (TEXTTABLE / string-typed fields). + param_map.insert(param.name.clone(), serde_json::json!("0")); + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} + } + } + + let diag_comm = DiagComm { + name: service_name.to_string(), + type_: diag_comm_type(sid), + lookup_name: Some(service_name.to_string()), + }; + let security_plugin: DynamicPlugin = Box::new(()); + + let payload = manager + .create_uds_payload( + &diag_comm, + &security_plugin, + Some(UdsPayloadData::ParameterMap(param_map)), + ) + .await + .ok()?; + + let probed_did = extract_did_from_uds(&payload.data)?; + // ISO 14229-1 ยง7.3.2: DID 0x0000 is reserved. A zero result means the + // Payload encoding produced a degenerate output (e.g. a TEXTTABLE + // lookup silently failed), so treat it as unresolvable rather than a match. + if probed_did == 0 { + None + } else { + Some(probed_did) + } + } + + /// Resolve a DID to a service name using prefix lookup and metadata. + /// + /// Uses `lookup_diagcomms_by_request_prefix` with the full `[SID, DID_HI, + /// DID_LO]` prefix for direct matching of CODED-CONST DID services. For + /// `PhysConst` / Value DID services (where only the SID is a coded constant), + /// confirms the match via request parameter metadata. + /// + /// # Parameters + /// * `sid` - UDS service identifier (e.g. 0x22 for RDBI, 0x2E for WDBI). + /// * `did` - 16-bit Data Identifier to resolve. + /// * `uds_bytes` - Raw incoming UDS request bytes. + /// * `label` - Log prefix string (e.g. `"READ"`, `"WRITE"`). + #[allow(clippy::cast_possible_truncation)] + async fn resolve_service_did( + &self, + sid: u8, + did: u16, + _uds_bytes: &[u8], + label: &str, + ) -> Option { + let manager = self.manager.read().await; + + // Step 1: Prefix lookup with [SID, DID_HI, DID_LO]. + // + // The CDA matches sequential coded-const parameters against the prefix: + // - CODED-CONST DID services -> only exact DID matches pass. + // - PhysConst / Value DID services -> only the SID byte is coded-const, + // so all services with matching SID pass through. + let did_prefix = [sid, (did >> 8) as u8, (did & 0xFF) as u8]; + let prefix_matches = manager + .lookup_diagcomms_by_request_prefix(&did_prefix) + .unwrap_or_default(); + + // Fast path: single match from prefix lookup (common case: unique DID). + if let [only] = prefix_matches.as_slice() { + let name = only.lookup_name.as_deref().unwrap_or(&only.name); + tracing::info!( + "[resolve_did] {} DID 0x{:04X} -> '{}' (prefix match)", + label, + did, + name + ); + return Some(name.to_owned()); + } + + // Step 2: Build deduplicated candidate list from prefix matches + + // supplementary sources (bypass NOT-INHERITED-DIAG-COMMS filter). + let mut seen = std::collections::HashSet::new(); + let mut candidates: Vec = Vec::new(); + + for dc in &prefix_matches { + let name = dc.lookup_name.as_deref().unwrap_or(&dc.name); + if seen.insert(name.to_owned()) { + candidates.push(name.to_owned()); + } + } + + let security_plugin: DynamicPlugin = Box::new(()); + let extra_names: Vec = if sid == service_ids::READ_DATA_BY_IDENTIFIER { + manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect() + } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { + manager + .get_components_configurations_info(&security_plugin) + .map(|v| v.into_iter().map(|c| c.id).collect()) + .unwrap_or_default() + } else { + Vec::new() + }; + for name in extra_names { + if seen.insert(name.clone()) { + candidates.push(name); + } + } + + if candidates.is_empty() { + tracing::warn!( + "[resolve_did] {} no services for SID 0x{:02X} DID 0x{:04X}", + label, + sid, + did + ); + return None; + } + + tracing::debug!( + "[resolve_did] {} SID 0x{:02X} DID 0x{:04X}", + label, + sid, + did, + ); + + // Step 3: Match DID against each candidate's request metadata. + for name in &candidates { + let Ok(meta) = manager.get_request_parameter_metadata(name) else { + continue; + }; + + let did_param = find_did_param(&meta, sid); + + let matched = match did_param.map(|p| &p.param_type) { + Some(cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value }) => { + parse_u64_literal(coded_value) == Some(u64::from(did)) + } + + Some(cda_interfaces::ParameterTypeMetadata::PhysConst { coded_value, .. }) => { + let resolved = match coded_value { + Some(cv) => Some(*cv as u16), + None => Self::probe_service_did(&manager, name, sid, &meta).await, + }; + resolved == Some(did) + } + + Some(cda_interfaces::ParameterTypeMetadata::Value { + coded_default_value, + compu_scales, + .. + }) => { + let default_ok = coded_default_value + .map(|cd| cd as u16 == did) + .unwrap_or(false); + let scales_ok = + !compu_scales.is_empty() && did_matches_compu_scales(compu_scales, did); + + default_ok || scales_ok + } + + None | Some(cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. }) => { + false + } + }; + + if matched { + tracing::info!("[resolve_did] {} DID 0x{:04X} -> '{}'", label, did, name); + return Some(name.clone()); + } + } + + tracing::error!( + "[resolve_did] {} no service found for DID 0x{:04X} (checked {} candidates)", + label, + did, + candidates.len() + ); + None + } + + /// Find the correct service for a given SID + DID. + /// + /// Delegates DID -> service resolution to [`resolve_service_did`] which uses + /// MDD metadata and probing (`CodedConst`, `PhysConst`, Value+MUX). Then attempts + /// parse-validation via `convert_request_from_uds` for the matched service. + async fn resolve_service( + &self, + sid: u8, + did: u16, + uds_bytes: &[u8], + label: &str, + ) -> Option<(String, serde_json::Map)> { + tracing::debug!("[MDD] {} DID 0x{:04X}", label, did); + + let service_name = self.resolve_service_did(sid, did, uds_bytes, label).await?; + + // Attempt parse-validation to extract structured parameter data. + let manager = self.manager.read().await; + let payload = make_service_payload(uds_bytes); + let diag_comm = DiagComm { + name: service_name.clone(), + type_: diag_comm_type(sid), + lookup_name: Some(service_name.clone()), + }; + + if let Ok(parsed) = manager + .convert_request_from_uds(&diag_comm, &payload, true) + .await + && let Ok(json_resp) = parsed.into_json() + && let serde_json::Value::Object(map) = json_resp.data + { + tracing::debug!( + "[MDD] {} DID 0x{:04X} -> '{}' (parse verified)", + label, + did, + service_name + ); + return Some((service_name, map)); + } + + // Parse failed โ€” still return the metadata-resolved service with empty map. + tracing::debug!( + "[MDD] {} DID 0x{:04X} -> '{}' (metadata match, parse unavailable)", + label, + did, + service_name + ); + Some((service_name, serde_json::Map::new())) + } + + /// Parse UDS request bytes using the MDD request structure. + /// + /// # Errors + /// Returns an error if the request cannot be parsed. + pub async fn parse_request( + &self, + service_name: &str, + uds_request: &[u8], + ) -> Result, DiagServiceError> { + let service_id = uds_request.first().copied().unwrap_or(0x00); + let diag_comm = self.make_diag_comm(service_name, service_id); + let payload = make_service_payload(uds_request); + + let manager = self.manager.read().await; + let response = manager + .convert_request_from_uds(&diag_comm, &payload, true) + .await?; + let json_response = response.into_json()?; + + if let serde_json::Value::Object(map) = json_response.data { + tracing::debug!( + "[MDD] Parsed request for '{}': {} fields", + service_name, + map.len() + ); + Ok(map) + } else { + tracing::error!( + "[MDD] Expected JSON object in request, got: {:?}", + json_response.data + ); + Err(DiagServiceError::InvalidRequest( + "Expected JSON object in request".to_string(), + )) + } + } +} diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs new file mode 100644 index 0000000..6bec4fa --- /dev/null +++ b/proxy-core/src/service_resolver/response.rs @@ -0,0 +1,336 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! UDS response building and validation. +//! +//! Implements [`ServiceResolver::build_response`] which encodes SOVD JSON +//! data into UDS response bytes using MDD parameter metadata. + +use cda_interfaces::{ + DiagServiceError, EcuManager as EcuManagerTrait, HashMap, UDS_ID_RESPONSE_BITMASK, + diagservices::DiagServiceResponse, +}; + +use super::{ + ServiceResolver, UDS_POSITIVE_RESPONSE_MIN_SIZE, + uds_helpers::{ + encode_unsigned_be, encode_value_at, find_mux_case_prefix, make_service_payload, + value_to_bytes, + }, +}; + +impl ServiceResolver { + /// Build UDS response bytes from SOVD JSON data using MDD response metadata. + /// + /// Queries the POS-RESPONSE parameter layout from the MDD to determine exact + /// byte positions and sizes for each parameter. Each parameter is encoded + /// at its MDD-defined position: + /// + /// - **CODED-CONST**: fixed value written directly (e.g. response SID). + /// - **`MatchingRequestParam`**: DID bytes from the original request. + /// - **VALUE**: SOVD data value encoded with the correct byte width; + /// defaults to 0 when the key is not present in the SOVD response. + /// + /// Falls back to naive encoding if response metadata is unavailable. + /// + /// # Errors + /// Returns an error if the response cannot be encoded. + /// + /// # TODO: + /// Once the SOVD server returns properly structured responses, the naive + /// encoding fallback and the MDD-based `encode_response_from_metadata` + /// path can be removed โ€” the proxy will forward pre-encoded UDS bytes. + pub async fn build_response( + &self, + service_name: &str, + sid: u8, + did: u16, + response_data: HashMap, + ) -> Result, DiagServiceError> { + tracing::debug!( + "[MDD] Building UDS response for '{}' SID 0x{:02X} DID 0x{:04X}", + service_name, + sid, + did, + ); + + let (response, effective_service) = if let Some((r, svc)) = self + .encode_response_from_metadata(service_name, sid, did, &response_data) + .await + { + (r, svc) + } else { + // Fallback: naive encoding โ€” used when no response metadata is available. + tracing::debug!( + "[MDD] No response metadata for '{}', using naive encoding", + service_name + ); + let response_sid = sid.wrapping_add(UDS_ID_RESPONSE_BITMASK); + #[allow(clippy::cast_possible_truncation)] + let mut response = vec![response_sid, (did >> 8) as u8, (did & 0xFF) as u8]; + + let entries: Vec<_> = response_data + .iter() + .filter(|(k, _)| !k.eq_ignore_ascii_case("sid")) + .collect(); + + for (key, value) in entries { + match value { + serde_json::Value::String(s) => { + response.extend_from_slice(s.as_bytes()); + } + serde_json::Value::Number(n) => { + if let Some(num) = n.as_u64() { + response.extend(encode_unsigned_be(num)); + } else if let Some(num) = n.as_i64() { + let unsigned = num.cast_unsigned(); + #[allow(clippy::cast_possible_truncation)] + if u8::try_from(unsigned).is_ok() { + response.push(unsigned as u8); + } else { + response.push((unsigned >> 8) as u8); + response.push((unsigned & 0xFF) as u8); + } + } + } + serde_json::Value::Array(arr) => { + for item in arr { + #[allow(clippy::cast_possible_truncation)] + if let Some(byte) = item.as_u64() { + response.push(byte as u8); + } + } + } + serde_json::Value::Bool(b) => { + response.push(u8::from(*b)); + } + _ => { + tracing::warn!( + "[MDD] Skipping unsupported value type for '{}': {:?}", + key, + value + ); + } + } + } + + tracing::debug!("[MDD] Built UDS response (naive): {:02X?}", response); + (response, service_name.to_string()) + }; + + // Debug-only round-trip validation: parse the built bytes back through + // the CDA to confirm the MDD layout produces a decodable + // response. Uses the effective service name (which may be an enriched + // MUX sibling) so the CDA parses against the same structure we + // encoded with. + if tracing::enabled!(tracing::Level::DEBUG) { + self.validate_response(&effective_service, sid, &response) + .await; + } + + Ok(response) + } + + /// Round-trip validate UDS response bytes by parsing them back through + /// the CDA. + /// + /// Called only when `tracing::Level::DEBUG` is enabled โ€” failures are logged + /// as warnings but never block the response (non-blocking). + async fn validate_response(&self, service_name: &str, request_sid: u8, uds_response: &[u8]) { + let diag_comm = self.make_diag_comm(service_name, request_sid); + let payload = make_service_payload(uds_response); + let manager = self.manager.read().await; + match manager.convert_from_uds(&diag_comm, &payload, true).await { + Ok(parsed) => match parsed.into_json() { + Ok(json) => tracing::trace!( + "[MDD] Round-trip validation OK for '{}': {:?}", + service_name, + json.data + ), + Err(e) => tracing::warn!( + "[MDD] Round-trip validation: JSON decode failed for '{}': {}", + service_name, + e + ), + }, + Err(e) => tracing::warn!( + "[MDD] Round-trip validation: parse failed for '{}': {}", + service_name, + e + ), + } + } + + /// Encode a UDS response using POS-RESPONSE parameter metadata from the MDD. + /// + /// For each parameter in the MDD response structure: + /// - CODED-CONST (e.g. response SID at byte 0): writes the const value. + /// - `MatchingRequestParam` (e.g. DID at bytes 1-2): writes the DID. + /// - VALUE: uses the SOVD response data keyed by the MDD parameter name; + /// falls back to `0` when the key is absent. + /// + /// Returns `None` when no response metadata is available for the service. + /// On success returns the encoded bytes and the effective service name + /// (which may differ from `service_name` when enriched MUX sibling metadata + /// is used). + async fn encode_response_from_metadata( + &self, + service_name: &str, + _sid: u8, + did: u16, + response_data: &HashMap, + ) -> Option<(Vec, String)> { + let (meta, effective_service) = self + .get_enriched_response_metadata_with_source(service_name, did) + .await + .ok()?; + if meta.is_empty() { + return None; + } + + // Find the MUX case matching this DID (if any) using floor-based matching. + let mux_case_prefix = find_mux_case_prefix(&meta, did); + + // Derive the matching marker name for total_size computation. + let mux_marker_name: Option = mux_case_prefix + .as_deref() + .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + // Filter: keep top-level params (no '/') + matching MUX case VALUE params + // + the matching case marker (for total_size). + let active_params: Vec<_> = meta + .iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = &mux_case_prefix { + p.name.starts_with(prefix.as_str()) + || mux_marker_name.as_deref() == Some(&p.name) + } else { + !p.name.starts_with("__mux_case__/") + } + }) + .collect(); + + // Resolve effective size for each active param. For VALUE params with + // `byte_size: None` (variable-length DOPs like EndOfPdu), the size is + // inferred from the actual response data. + let effective_sizes: Vec = active_params + .iter() + .map(|p| { + if let Some(s) = p.byte_size { + return s as usize; + } + // Variable-size VALUE param โ€” infer size from the data. + if !matches!( + &p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + ) { + return 0; + } + let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); + let value = response_data + .get(&p.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + value_to_bytes(value).len() + }) + .collect(); + + // Determine total response size from filtered params. + let total_size = active_params + .iter() + .zip(effective_sizes.iter()) + .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) + .max() + .unwrap_or(UDS_POSITIVE_RESPONSE_MIN_SIZE); + + let mut response = vec![0u8; total_size]; + + for (param, &eff_size) in active_params.iter().zip(effective_sizes.iter()) { + // Skip MUX case markers โ€” they're only used for total_size computation. + if param.name.starts_with("__mux_case__/") { + continue; + } + let pos = param.byte_position as usize; + + if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { + continue; + } + + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // The SID byte is stored as a decimal string (e.g. "98" for 0x62). + if let Ok(val) = coded_value.parse::() { + let bytes = encode_unsigned_be(val); + let copy_len = bytes.len().min(eff_size); + // Right-align in the field (big-endian convention). + let offset = eff_size.saturating_sub(copy_len); + let dst_start = pos.saturating_add(offset); + let dst_end = dst_start.saturating_add(copy_len); + let src_start = bytes.len().saturating_sub(copy_len); + if let (Some(dst), Some(src)) = + (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) + { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { + // DID bytes from the original request, big-endian. + let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; + let copy_len = did_bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + did_bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // For MUX case params, try the short name (after '/') as well. + let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); + let value = response_data + .get(¶m.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + + if param.byte_size.is_some() { + encode_value_at(&mut response, pos, eff_size, value); + } else { + // Variable-size param: write the raw byte representation. + let bytes = value_to_bytes(value); + let copy_len = bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} + } + } + + tracing::debug!( + "[MDD] Built UDS response via metadata for '{}'): {:02X?}", + service_name, + response + ); + Some((response, effective_service)) + } +} diff --git a/proxy-core/src/service_resolver/uds_helpers.rs b/proxy-core/src/service_resolver/uds_helpers.rs new file mode 100644 index 0000000..aabbb42 --- /dev/null +++ b/proxy-core/src/service_resolver/uds_helpers.rs @@ -0,0 +1,539 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! UDS helper functions for encoding, decoding, and service metadata queries. +//! +//! Pure functions used across the [`super::ServiceResolver`] implementation: +//! DID extraction, MUX-case matching, value encoding, and payload construction. + +use cda_interfaces::{ + CompuScaleInfo, DiagCommType, ResponseParameterInfo, ServiceParameterMetadata, ServicePayload, +}; + +/// Extract the 16-bit DID from UDS payload bytes at offset 1โ€“2. +/// +/// Returns `None` if the slice has fewer than 3 bytes. +pub(super) fn extract_did_from_uds(data: &[u8]) -> Option { + let b1 = *data.get(1)?; + let b2 = *data.get(2)?; + Some(u16::from_be_bytes([b1, b2])) +} + +/// Map a UDS service identifier to its [`DiagCommType`]. +/// +/// Falls back to [`DiagCommType::Data`] for unrecognised SIDs so that the +/// caller always receives a usable type rather than an error. +pub(super) fn diag_comm_type(service_id: u8) -> DiagCommType { + DiagCommType::try_from(service_id).unwrap_or(DiagCommType::Data) +} + +/// Create a `ServicePayload` from raw UDS bytes with default addresses. +pub(super) fn make_service_payload(data: &[u8]) -> ServicePayload { + ServicePayload { + data: data.to_vec(), + source_address: 0, + target_address: 0, + new_session: None, + new_security: None, + } +} + +/// Encode an unsigned integer as big-endian bytes using the minimum width needed. +/// +/// Always produces at least one byte; zero encodes as `[0x00]`. +pub(super) fn encode_unsigned_be(num: u64) -> Vec { + if num == 0 { + return vec![0x00]; + } + // Skip leading zero bytes; safe because num != 0 guarantees a non-empty result. + num.to_be_bytes() + .iter() + .copied() + .skip_while(|&b| b == 0) + .collect() +} + +/// Parse a MUX case `coded_value` string as a numeric DID value. +/// +/// MDD stores MUX case limits as strings that may be float-formatted +/// (e.g. `"61699.0"`) or integer-formatted (e.g. `"61699"`). +#[must_use] +pub fn parse_mux_coded_value(coded_value: &str) -> Option { + let trimmed = coded_value.trim(); + if let Ok(v) = trimmed.parse::() { + return Some(v); + } + #[allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss + )] + if let Ok(v) = trimmed.parse::() + && v >= 0.0 + && v <= u64::MAX as f64 + { + return Some(v as u64); + } + None +} + +/// Find the MUX case prefix that covers a given DID in response metadata. +/// +/// MDD `__mux_case__` entries store only the **`lower_limit`** of their range +/// (e.g. a case with `coded_value: "61697"` covering DIDs 0xF101 +/// through 0xF140). A DID like 0xF103 (61699) has no exact match +/// but falls in that range. +/// +/// This function uses **floor-based matching**: collect all `__mux_case__` +/// lower bounds, sort them, and find the case with the largest lower bound +/// that does not exceed the DID. This correctly handles both single-value +/// MUX cases (e.g. 0x7007) and range cases (e.g. 0xD100โ€“0xD150). +#[must_use] +pub fn find_mux_case_prefix(meta: &[ResponseParameterInfo], did: u16) -> Option { + let did_val = u64::from(did); + + // Collect (lower_bound, case_name) for all MUX case entries. + let mut mux_entries: Vec<(u64, &str)> = meta + .iter() + .filter_map(|p| { + let case_name = p.name.strip_prefix("__mux_case__/")?; + if let cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } = &p.param_type + { + let lower = parse_mux_coded_value(coded_value)?; + Some((lower, case_name)) + } else { + None + } + }) + .collect(); + + if mux_entries.is_empty() { + return None; + } + + // Sort by lower bound ascending. + mux_entries.sort_by_key(|&(lb, _)| lb); + + // Floor match: largest lower_bound โ‰ค DID. + let matched = mux_entries.iter().rev().find(|&&(lb, _)| lb <= did_val)?; + + Some(format!("{}/", matched.1)) +} + +/// Check if ANY MUX case in the response metadata **exactly** matches the DID. +/// +/// Uses exact (not floor) matching because this is for cross-service sibling +/// selection where different MUX DOPs can have overlapping ranges. +#[must_use] +pub fn has_mux_case_for_did_exact(meta: &[ResponseParameterInfo], did: u16) -> bool { + let did_val = u64::from(did); + meta.iter().any(|p| { + if let Some(_case_name) = p.name.strip_prefix("__mux_case__/") + && let cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } = &p.param_type + { + return parse_mux_coded_value(coded_value) == Some(did_val); + } + false + }) +} + +/// Parse numeric literals in decimal or hexadecimal form. +pub(super) fn parse_u64_literal(value: &str) -> Option { + let trimmed = value.trim(); + if let Some(hex) = trimmed + .strip_prefix("0x") + .or_else(|| trimmed.strip_prefix("0X")) + { + return u64::from_str_radix(hex, 16).ok(); + } + + trimmed + .parse::() + .ok() + .or_else(|| u64::from_str_radix(trimmed, 16).ok()) +} + +/// Find the DID-bearing parameter by position and type, not by name. +/// +/// In standard UDS requests parameters are stored in byte order: +/// - First `CodedConst` whose value matches the SID -> SID indicator (skip) +/// - Next `CodedConst` / `PhysConst` / `Value` -> DID parameter +/// +/// This avoids vendor-specific name or semantic string matching. +pub(super) fn find_did_param( + metadata: &[ServiceParameterMetadata], + sid: u8, +) -> Option<&ServiceParameterMetadata> { + let mut skipped_sid = false; + for p in metadata { + match &p.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + if !skipped_sid + && let Some(val) = parse_u64_literal(coded_value) + && val == u64::from(sid) + { + skipped_sid = true; + continue; + } + // Non-SID CodedConst -> DID param + return Some(p); + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } + | cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // PhysConst / Value -> DID param + return Some(p); + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} + } + } + None +} + +/// Check if a DID falls within any `CompuScale` range from the DOP metadata. +/// +/// For TEXTTABLE DOPs each scale defines a coded (internal) DID range. +/// Returns `true` if `did` falls in `[lower_limit, upper_limit]` of any scale. +pub(super) fn did_matches_compu_scales(scales: &[CompuScaleInfo], did: u16) -> bool { + let did_val = u64::from(did); + scales.iter().any(|s| match (s.lower_limit, s.upper_limit) { + (Some(lo), Some(hi)) => did_val >= lo && did_val <= hi, + (Some(lo), None) => did_val == lo, + _ => false, + }) +} + +/// Encode a JSON value into `buf[pos..pos+size]` using big-endian representation. +/// +/// Handles numbers, strings, byte arrays, and booleans. Fills the entire +/// `size` field, zero-padding on the left for numbers shorter than `size`. +pub(super) fn encode_value_at( + buf: &mut [u8], + pos: usize, + size: usize, + value: Option<&serde_json::Value>, +) { + if size == 0 { + return; + } + let Some(end) = pos.checked_add(size) else { + return; + }; + if end > buf.len() { + return; + } + let Some(value) = value else { + // No value provided โ€” leave as zero (already initialised). + return; + }; + match value { + serde_json::Value::Number(n) => { + let raw = n + .as_u64() + .unwrap_or_else(|| n.as_i64().unwrap_or(0).cast_unsigned()); + let be = raw.to_be_bytes(); + // Right-align in the field. + let u64_size = std::mem::size_of::(); + let start = u64_size.saturating_sub(size); + let copy = size.min(u64_size); + // end = pos + size; dst_start = end - copy = pos + (size - copy). + // copy <= size so no underflow. + let dst_start = end.saturating_sub(copy); + if let (Some(dst), Some(src)) = ( + buf.get_mut(dst_start..end), + be.get(start..start.saturating_add(copy)), + ) { + dst.copy_from_slice(src); + } + } + serde_json::Value::String(s) => { + let bytes = s.as_bytes(); + let copy = bytes.len().min(size); + if let (Some(dst), Some(src)) = ( + buf.get_mut(pos..pos.saturating_add(copy)), + bytes.get(..copy), + ) { + dst.copy_from_slice(src); + } + } + serde_json::Value::Array(arr) => { + for (i, item) in arr.iter().enumerate() { + if i >= size { + break; + } + if let Some(byte) = item.as_u64() + && let Some(slot) = buf.get_mut(pos.saturating_add(i)) + { + #[allow(clippy::cast_possible_truncation)] + { + *slot = byte as u8; + } + } + } + } + serde_json::Value::Bool(b) => { + if let Some(slot) = buf.get_mut(pos) { + *slot = u8::from(*b); + } + } + _ => {} + } +} + +/// Serialize a JSON value into raw bytes for UDS encoding. +/// +/// Returns an empty Vec when the value is None or cannot be serialized. +pub(super) fn value_to_bytes(value: Option<&serde_json::Value>) -> Vec { + let Some(value) = value else { + return Vec::new(); + }; + match value { + serde_json::Value::Number(n) => { + let raw = n + .as_u64() + .unwrap_or_else(|| n.as_i64().unwrap_or(0).cast_unsigned()); + encode_unsigned_be(raw) + } + serde_json::Value::String(s) => s.as_bytes().to_vec(), + serde_json::Value::Array(arr) => arr + .iter() + .filter_map(|item| { + #[allow(clippy::cast_possible_truncation)] + item.as_u64().map(|b| b as u8) + }) + .collect(), + serde_json::Value::Bool(b) => vec![u8::from(*b)], + _ => Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use cda_interfaces::ParameterTypeMetadata; + + use super::*; + + #[test] + fn test_encode_unsigned_be() { + assert_eq!(encode_unsigned_be(0), vec![0x00]); + assert_eq!(encode_unsigned_be(0xFF), vec![0xFF]); + assert_eq!(encode_unsigned_be(0x0100), vec![0x01, 0x00]); + assert_eq!(encode_unsigned_be(0xF190), vec![0xF1, 0x90]); + assert_eq!(encode_unsigned_be(0xFFFF), vec![0xFF, 0xFF]); + assert_eq!(encode_unsigned_be(0x01_0000), vec![0x01, 0x00, 0x00]); + assert_eq!(encode_unsigned_be(0xFF_FFFF), vec![0xFF, 0xFF, 0xFF]); + assert_eq!( + encode_unsigned_be(0x0100_0000), + vec![0x01, 0x00, 0x00, 0x00] + ); + assert_eq!( + encode_unsigned_be(0xDEAD_BEEF), + vec![0xDE, 0xAD, 0xBE, 0xEF] + ); + } + + #[test] + fn test_make_service_payload() { + let data = &[0x62, 0xF1, 0x90, 0x57]; + let payload = make_service_payload(data); + assert_eq!(payload.data, vec![0x62, 0xF1, 0x90, 0x57]); + assert_eq!(payload.source_address, 0); + assert_eq!(payload.target_address, 0); + assert!(payload.new_session.is_none()); + assert!(payload.new_security.is_none()); + } + + #[test] + fn test_diag_comm_type() { + use cda_interfaces::service_ids; + + assert!(matches!( + diag_comm_type(service_ids::WRITE_DATA_BY_IDENTIFIER), + DiagCommType::Configurations + )); + assert!(matches!( + diag_comm_type(service_ids::READ_DATA_BY_IDENTIFIER), + DiagCommType::Data + )); + assert!(matches!( + diag_comm_type(service_ids::SESSION_CONTROL), + DiagCommType::Modes + )); + assert!(matches!( + diag_comm_type(service_ids::TESTER_PRESENT), + DiagCommType::Data + )); + assert!(matches!( + diag_comm_type(service_ids::ROUTINE_CONTROL), + DiagCommType::Operations + )); + assert!(matches!( + diag_comm_type(service_ids::CLEAR_DIAGNOSTIC_INFORMATION), + DiagCommType::Faults + )); + } + + #[test] + fn test_parse_mux_coded_value() { + assert_eq!(parse_mux_coded_value("61699"), Some(61699)); + assert_eq!(parse_mux_coded_value("32776"), Some(32776)); + assert_eq!(parse_mux_coded_value("61699.0"), Some(61699)); + assert_eq!(parse_mux_coded_value(" 61699 "), Some(61699)); + assert_eq!(parse_mux_coded_value("non_numeric_text"), None); + assert_eq!(parse_mux_coded_value(""), None); + } + + #[test] + fn test_find_mux_case_prefix_floor_match() { + use cda_interfaces::ResponseParameterInfo; + + // Simulate real RDBI_RESP metadata with range-based and point MUX cases. + let meta = vec![ + // Point case: DID_POINT_8008 covers only DID 0x8008 (32776) + ResponseParameterInfo { + name: "__mux_case__/DID_POINT_8008".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "32776".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + // Range case: DID_RANGE_F101_F140 covers 0xF101 (61697) through 0xF140 (61760) + ResponseParameterInfo { + name: "__mux_case__/DID_RANGE_F101_F140".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61697".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + // Point case: DID_POINT_F141 covers only 0xF141 (61761) + ResponseParameterInfo { + name: "__mux_case__/DID_POINT_F141".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61761".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + ]; + + // Exact match + assert_eq!( + find_mux_case_prefix(&meta, 0x8008), + Some("DID_POINT_8008/".to_string()) + ); + assert_eq!( + find_mux_case_prefix(&meta, 0xF101), + Some("DID_RANGE_F101_F140/".to_string()) + ); + assert_eq!( + find_mux_case_prefix(&meta, 0xF141), + Some("DID_POINT_F141/".to_string()) + ); + + // Floor match within range + assert_eq!( + find_mux_case_prefix(&meta, 0xF103), // 61699 -> floor to 61697 + Some("DID_RANGE_F101_F140/".to_string()) + ); + assert_eq!( + find_mux_case_prefix(&meta, 0xF140), // 61760 -> floor to 61697 + Some("DID_RANGE_F101_F140/".to_string()) + ); + + // Float-formatted coded_value + let meta_float = vec![ResponseParameterInfo { + name: "__mux_case__/case_a".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61697.0".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }]; + assert_eq!( + find_mux_case_prefix(&meta_float, 0xF103), + Some("case_a/".to_string()) + ); + + // No MUX entries -> None + assert_eq!(find_mux_case_prefix(&[], 0xF103), None); + } + + #[test] + fn test_find_did_param() { + // Standard RDBI: CodedConst SID + PhysConst DID + let meta = vec![ + ServiceParameterMetadata { + name: "RDBI".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), // 0x22 + }, + }, + ServiceParameterMetadata { + name: "VIN".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::PhysConst { + phys_constant_value: "VIN".to_string(), + coded_value: Some(0xF190), + }, + }, + ]; + let did = find_did_param(&meta, 0x22); + assert!(did.is_some()); + assert_eq!(did.expect("DID param not found").name, "VIN"); + + // Value-type service: SID + Value DID + let meta2 = vec![ + ServiceParameterMetadata { + name: "SID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), + }, + }, + ServiceParameterMetadata { + name: "DynamicDID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + }, + ]; + let did = find_did_param(&meta2, 0x22); + assert!(did.is_some()); + assert!(matches!( + did.expect("DID param not found").param_type, + ParameterTypeMetadata::Value { .. } + )); + + // SID-only service: no DID param + let meta3 = vec![ServiceParameterMetadata { + name: "SID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), + }, + }]; + assert!(find_did_param(&meta3, 0x22).is_none()); + } +} diff --git a/testcontainer/mdd/FLXC1000.mdd.license b/testcontainer/mdd/FLXC1000.mdd.license new file mode 100644 index 0000000..7319749 --- /dev/null +++ b/testcontainer/mdd/FLXC1000.mdd.license @@ -0,0 +1,9 @@ +SPDX-License-Identifier: Apache-2.0 +SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + +See the NOTICE file(s) distributed with this work for additional +information regarding copyright ownership. + +This program and the accompanying materials are made available under the +terms of the Apache License Version 2.0 which is available at +https://www.apache.org/licenses/LICENSE-2.0 From b1ef0eb9ff962a1030cc3902b3ee230d4e7a2ab9 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Mon, 27 Apr 2026 11:14:42 +0200 Subject: [PATCH 06/33] refactor: remove DiagHandler trait from proxy-core Signed-off-by: Arvind Rathod --- Cargo.lock | 1 - docs/ServiceResolver_Sequence_Diagram.svg | 1 + docs/service_resolver_class.puml | 35 +- docs/service_resolver_class.svg | 1 + docs/service_resolver_sequence.puml | 158 +++++++++ proxy-core/Cargo.toml | 3 +- proxy-core/src/diag_handler.rs | 35 -- proxy-core/src/lib.rs | 4 +- proxy-core/src/service_resolver/metadata.rs | 284 +++++++++++++--- proxy-core/src/service_resolver/mod.rs | 59 ++-- proxy-core/src/service_resolver/resolve.rs | 302 +++++++++++------- proxy-core/src/service_resolver/response.rs | 261 ++++++++++++++- .../src/service_resolver/uds_helpers.rs | 61 +++- 13 files changed, 954 insertions(+), 251 deletions(-) create mode 100644 docs/ServiceResolver_Sequence_Diagram.svg create mode 100644 docs/service_resolver_class.svg create mode 100644 docs/service_resolver_sequence.puml delete mode 100644 proxy-core/src/diag_handler.rs diff --git a/Cargo.lock b/Cargo.lock index 42f3cf3..e273f79 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1316,7 +1316,6 @@ dependencies = [ name = "proxy-core" version = "0.1.0" dependencies = [ - "async-trait", "cda-core", "cda-database", "cda-interfaces", diff --git a/docs/ServiceResolver_Sequence_Diagram.svg b/docs/ServiceResolver_Sequence_Diagram.svg new file mode 100644 index 0000000..b767756 --- /dev/null +++ b/docs/ServiceResolver_Sequence_Diagram.svg @@ -0,0 +1 @@ +ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(resolve.rs)ServiceResolver(resolve.rs)ServiceResolver(metadata.rs)ServiceResolver(metadata.rs)ServiceResolver(response.rs)ServiceResolver(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve_read_service(did, uds_bytes)resolve_service(SID=0x22, did, uds_bytes)resolve_service_did()Step 1-2: Prefix lookup& candidate buildinglookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching servicesbuild_did_candidates()Fast path: single matchelse: enumerate SID-matchingservices via get_components_data_info()match_candidate_did()Step 3: Metadata matchingCodedConst / PhysConst / Value DIDsget_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)Exact match against DID[PhysConst DID]probe_service_did() (optional)Encode dummy request,extract DID from payloadcreate_uds_payload()encoded payloadextract_did_from_uds()[Value DID]did_matches_compu_scales()Range/list matching via MDD CompuScaleconvert_request_from_uds()parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesusing SID=0x2E andget_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)encode_response_from_metadata()get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutOpaque heuristic:Single VALUE with byte_size=Noneand no '/' in name?alt[opaque STRUCTURE detected]get_components_data_info()READ service componentshas_mux_case_for_did_exact(sibling_meta, did)Exact match — avoidscross-DOP false positives(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)mux_case_prefix = find_mux_case_prefix(meta, did)Floor-based matchingfor MUX case active paramsfilter active params by mux_case_prefixSelect top-level params +case-specific sub-paramsalt[metadata available]for each active param:encode_value_at(buf, pos, size, value)CodedConst -> fixed bytesMatchingRequestParam -> DID bytesValue -> encode_value_at()(encoded_bytes, effective_service)[no metadata (fallback)]naive encoding via value_to_bytes()Iterate response_dataString/Number/Array/Boolno MDD structurealt[DEBUG enabled]validate_response()convert_from_uds()JSONRound-trip validation:warn on mismatch, never blocksResult<Vec<u8>, DiagServiceError>  Module Layout (impl ServiceResolver): -resolve.rs: DID -> service resolution,candidate building, metadata matching-response.rs: UDS response encoding,round-trip validation (debug only)-metadata.rs: MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure utilities —encoding, decoding, MUX matching Resolution Algorithm (resolve.rs):1. Prefix lookup [SID, DID_HI, DID_LO]2. Fast path: single prefix match -> return3. Enumerate all SID-matching services4. Match via CodedConst / PhysConst / Value5. Parse request params inline via CDA \ No newline at end of file diff --git a/docs/service_resolver_class.puml b/docs/service_resolver_class.puml index 6d18faf..e53cd0f 100644 --- a/docs/service_resolver_class.puml +++ b/docs/service_resolver_class.puml @@ -33,10 +33,9 @@ package "proxy-core::service_resolver" { + ecu_name() : &str + {static} is_negative_response(uds) : bool + {static} get_nrc(uds) : Option - == resolve.rs โ€” DID โ†’ service name == - + <> resolve_read_service(did, uds) : Option<(String, Map)> - + <> resolve_write_service(did, uds) : Option<(String, Map)> - + <> parse_request(name, uds) : Result + == resolve.rs โ€” DID --> service name == + + <> resolve_read_service(did, uds) : Option + + <> resolve_write_service(did, uds) : Option == response.rs โ€” encode UDS response == + <> build_response(name, sid, did, data) : Result> == metadata.rs โ€” MDD parameter queries == @@ -51,18 +50,18 @@ package "proxy-core::service_resolver" { Service resolution algorithm (resolve.rs): 1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO]) - 2. Single match โ†’ service name found (fast path) - 3. Multiple candidates โ†’ inspect request parameter metadata: + 2. Single match --> service name found (fast path) + 3. Multiple candidates --> inspect request parameter metadata: โ€ข CodedConst โ€” exact DID value match โ€ข PhysConst โ€” coded_value or create_uds_payload probe โ€ข Value โ€” coded_default or CompuScale range match - 4. No match โ†’ log error, return None (no fallback) + 4. No match --> log error, return None (no fallback) Response encoding (response.rs): Walk MDD POS-RESPONSE parameters: - โ€ข CODED-CONST โ†’ fixed byte (e.g. response SID 0x62) - โ€ข MatchingRequestParam โ†’ echo DID bytes from request - โ€ข VALUE โ†’ SOVD JSON value at MDD-defined offset + โ€ข CODED-CONST --> fixed byte (e.g. response SID 0x62) + โ€ข MatchingRequestParam --> echo DID bytes from request + โ€ข VALUE --> SOVD JSON value at MDD-defined offset Opaque STRUCTURE types trigger MUX sibling lookup. end note @@ -113,7 +112,7 @@ package "cda-core (external path dep)" #LightGray { class "CdaEcuManager\n" as CdaEcuManager { ' Loads an MDD file (DiagnosticDatabase) and - ' implements EcuManagerTrait for UDS โ†” MDD ops. + ' implements EcuManagerTrait for UDS <-> MDD ops. } CdaEcuManager ..|> EcuManagerTrait @@ -121,17 +120,10 @@ package "cda-core (external path dep)" #LightGray { ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ' proxy-core public API consumed by proxy-sovd / proxy-doip +' DiagHandler trait removed โ€” no abstraction needed with one impl. ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ package "proxy-core (public API)" #LightYellow { - interface DiagHandler <> { - ' Implemented by SovdDiagHandler in proxy-sovd. - ' ServiceResolver is a field of SovdDiagHandler โ€” - ' not a DiagHandler implementor itself. - + <> handle_read_did(did, uds) : Result> - + <> handle_write_did(did, uds) : Result> - } - class Config { + server : ServerConfig + sovd : SovdConfig @@ -140,6 +132,11 @@ package "proxy-core (public API)" #LightYellow { -- + {static} from_file(path) : Result } + + class ResolvedService <> { + + name : String + + params : Map + } } ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ diff --git a/docs/service_resolver_class.svg b/docs/service_resolver_class.svg new file mode 100644 index 0000000..dbed3e5 --- /dev/null +++ b/docs/service_resolver_class.svg @@ -0,0 +1 @@ +Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)ServiceResolver-manager : Arc<RwLock<CdaEcuManager>>-ecu_name : String+new(ecu_name, db, logical, tester) : Result<Self>+ecu_name() : &str+is_negative_response(uds) : bool+get_nrc(uds) : Option<u8>mod.rs — construction & UDS helpers+«async» resolve_read_service(did, uds) : Option<ResolvedService>+«async» resolve_write_service(did, uds) : Option<ResolvedService>resolve.rs — DID --> service name+«async» build_response(name, sid, did, data) : Result<Vec<u8>>response.rs — encode UDS response+«async» get_service_parameter_metadata(name) : Result<Vec<Param>>+«async» get_response_parameter_metadata(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs — MDD parameter queries Service resolution algorithm (resolve.rs):1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:• CodedConst — exact DID value match• PhysConst — coded_value or create_uds_payload probe• Value — coded_default or CompuScale range match4. No match --> log error, return None (no fallback) Response encoding (response.rs):Walk MDD POS-RESPONSE parameters:• CODED-CONST --> fixed byte (e.g. response SID 0x62)• MatchingRequestParam --> echo DID bytes from request• VALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookup.«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rsand used by proxy-sovd for MUX matching.«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(service)+create_uds_payload(service, params)+convert_from_uds(service, bytes)+convert_request_from_uds(service, bytes)+detect_variant()CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>«struct»ResolvedService+name : String+params : Mapusesowns via Arc<RwLock>(shared with callers)Async RwLock allows concurrentread access across Tokio tasks. \ No newline at end of file diff --git a/docs/service_resolver_sequence.puml b/docs/service_resolver_sequence.puml new file mode 100644 index 0000000..df2a2c6 --- /dev/null +++ b/docs/service_resolver_sequence.puml @@ -0,0 +1,158 @@ +' SPDX-License-Identifier: Apache-2.0 +' SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +' +' See the NOTICE file(s) distributed with this work for additional +' information regarding copyright ownership. +' +' This program and the accompanying materials are made available under the +' terms of the Apache License Version 2.0 which is available at +' https://www.apache.org/licenses/LICENSE-2.0 + +@startuml ServiceResolver Sequence Diagram + +title ServiceResolver: DID Resolution & Response Building\nEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd) + +actor "SovdDiagHandler\n(proxy-sovd)" as Client +participant "ServiceResolver\n(resolve.rs)" as Resolver +participant "ServiceResolver\n(metadata.rs)" as Meta +participant "ServiceResolver\n(response.rs)" as Resp +participant "CDA EcuManager" as CDA + +== READ Service Resolution == + +Client -> Resolver: resolve_read_service(did, uds_bytes) +activate Resolver + +Resolver -> Resolver: resolve_service(SID=0x22, did, uds_bytes) + +Resolver -> Resolver: resolve_service_did() +note right: Step 1-2: Prefix lookup\n& candidate building + +Resolver -> CDA: lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO]) +activate CDA +CDA --> Resolver: matching services +deactivate CDA + +Resolver -> Resolver: build_did_candidates() +note right: Fast path: single match\nelse: enumerate SID-matching\nservices via get_components_data_info() + +Resolver -> Resolver: match_candidate_did() +note right: Step 3: Metadata matching\nCodedConst / PhysConst / Value DIDs + +Resolver -> CDA: get_request_parameter_metadata(candidate_name) +activate CDA +CDA --> Resolver: param metadata +deactivate CDA + +alt CodedConst DID + Resolver -> Resolver: parse_u64_literal(coded_value) + note right: Exact match against DID +else PhysConst DID + Resolver -> Resolver: probe_service_did() (optional) + note right: Encode dummy request,\nextract DID from payload + Resolver -> CDA: create_uds_payload() + activate CDA + CDA --> Resolver: encoded payload + deactivate CDA + Resolver -> Resolver: extract_did_from_uds() +else Value DID + Resolver -> Resolver: did_matches_compu_scales() + note right: Range/list matching via MDD CompuScale +end + +Resolver -> CDA: convert_request_from_uds() +activate CDA +CDA --> Resolver: parsed JSON params +deactivate CDA + +Resolver --> Client: Option +deactivate Resolver + +== WRITE Service Handling == + +note right of Client: Similar flow for WRITE services\nusing SID=0x2E and\nget_components_configurations_info() + +== Response Building == + +Client -> Resp: build_response(service_name, sid, did, response_data) +activate Resp + +Resp -> Resp: encode_response_from_metadata() + +Resp -> Meta: get_enriched_response_metadata_with_source(service_name, did) +activate Meta + +Meta -> CDA: get_response_parameter_metadata(service_name) +activate CDA +CDA --> Meta: response param layout +deactivate CDA + +note right of Meta: Opaque heuristic:\nSingle VALUE with byte_size=None\nand no '/' in name? + +alt opaque STRUCTURE detected + Meta -> CDA: get_components_data_info() + activate CDA + CDA --> Meta: READ service components + deactivate CDA + + Meta -> Meta: has_mux_case_for_did_exact(sibling_meta, did) + note right: Exact match โ€” avoids\ncross-DOP false positives + + Meta --> Resp: (enriched_meta, sibling_service_name) +else standard response + Meta --> Resp: (base_meta, service_name) +end + +deactivate Meta + +Resp -> Resp: mux_case_prefix = find_mux_case_prefix(meta, did) +note right: Floor-based matching\nfor MUX case active params + +Resp -> Resp: filter active params by mux_case_prefix +note right: Select top-level params +\ncase-specific sub-params + +alt metadata available + Resp -> Resp: for each active param: + Resp -> Resp: encode_value_at(buf, pos, size, value) + note right: CodedConst -> fixed bytes\nMatchingRequestParam -> DID bytes\nValue -> encode_value_at() + Resp --> Resp: (encoded_bytes, effective_service) +else no metadata (fallback) + Resp -> Resp: naive encoding via value_to_bytes() + note right: Iterate response_data\nString/Number/Array/Bool\nno MDD structure +end + +alt DEBUG enabled + Resp -> Resp: validate_response() + Resp -> CDA: convert_from_uds() + activate CDA + CDA --> Resp: JSON + deactivate CDA + note right: Round-trip validation:\nwarn on mismatch, never blocks +end + +Resp --> Client: Result, DiagServiceError> +deactivate Resp + +note right of Client + + + **Module Layout (impl ServiceResolver):** + + - **resolve.rs**: DID -> service resolution, + candidate building, metadata matching + - **response.rs**: UDS response encoding, + round-trip validation (debug only) + - **metadata.rs**: MDD metadata queries, + MUX sibling enrichment + - **uds_helpers.rs**: Pure utilities โ€” + encoding, decoding, MUX matching + + **Resolution Algorithm (resolve.rs):** + 1. Prefix lookup [SID, DID_HI, DID_LO] + 2. Fast path: single prefix match -> return + 3. Enumerate all SID-matching services + 4. Match via CodedConst / PhysConst / Value + 5. Parse request params inline via CDA +end note + +@enduml diff --git a/proxy-core/Cargo.toml b/proxy-core/Cargo.toml index 8933b87..e8f76e0 100644 --- a/proxy-core/Cargo.toml +++ b/proxy-core/Cargo.toml @@ -13,7 +13,7 @@ name = "proxy-core" version.workspace = true edition.workspace = true publish = false -description = "Shared types, errors, MDD engine, and DiagHandler trait for the UDS2SOVD proxy" +description = "Shared types, errors, and MDD engine for the UDS2SOVD proxy" homepage.workspace = true license.workspace = true @@ -22,7 +22,6 @@ cda-core = { workspace = true } cda-database = { workspace = true } cda-interfaces = { workspace = true } cda-plugin-security = { workspace = true } -async-trait = { workspace = true } thiserror = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/proxy-core/src/diag_handler.rs b/proxy-core/src/diag_handler.rs deleted file mode 100644 index adaace9..0000000 --- a/proxy-core/src/diag_handler.rs +++ /dev/null @@ -1,35 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License Version 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0 - */ - -use async_trait::async_trait; - -use crate::error::Result; - -/// Trait for processing UDS diagnostic requests through a backend. -#[async_trait] -pub trait DiagHandler { - /// Process a `ReadDataByIdentifier` (0x22) request. - /// - /// `did` is the extracted 16-bit Data Identifier. - /// `uds_request` is the full UDS request bytes including the SID byte. - /// - /// Returns the complete UDS response bytes (positive or negative). - async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result>; - - /// Process a `WriteDataByIdentifier` (0x2E) request. - /// - /// `did` is the extracted 16-bit Data Identifier. - /// `uds_request` is the full UDS request bytes including the SID byte. - /// - /// Returns the complete UDS response bytes (positive or negative). - async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result>; -} diff --git a/proxy-core/src/lib.rs b/proxy-core/src/lib.rs index c73cd7d..c489722 100644 --- a/proxy-core/src/lib.rs +++ b/proxy-core/src/lib.rs @@ -17,11 +17,9 @@ //! [`ServiceResolver`] for UDS request/response processing. pub mod config; -pub mod diag_handler; pub mod error; pub mod service_resolver; pub use config::Config; -pub use diag_handler::DiagHandler; pub use error::{ProxyError, Result}; -pub use service_resolver::ServiceResolver; +pub use service_resolver::{ResolvedService, ServiceResolver}; diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs index 5bf5d3f..dcbb9d8 100644 --- a/proxy-core/src/service_resolver/metadata.rs +++ b/proxy-core/src/service_resolver/metadata.rs @@ -71,12 +71,61 @@ impl ServiceResolver { .map(|(meta, _source)| meta) } - /// Same as [`get_enriched_response_metadata`] but also returns the name of - /// the service that actually provided the metadata. When the response is + /// Lookup all service names for a given UDS service ID (SID). + /// + /// Returns READ services for SID 0x22, WRITE services for SID 0x2E, + /// or an empty vector for unrecognized SIDs. + /// + /// # Errors + /// Does not currently return errors; always succeeds with a Vec. + pub async fn lookup_service_names_by_sid( + &self, + sid: u8, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + let security_plugin: DynamicPlugin = Box::new(()); + let names = if sid == service_ids::READ_DATA_BY_IDENTIFIER { + manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect() + } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { + manager + .get_components_configurations_info(&security_plugin) + .map(|v| v.into_iter().map(|c| c.id).collect()) + .unwrap_or_default() + } else { + Vec::new() + }; + Ok(names) + } + + /// Retrieve MUX case definitions for a given service. + /// + /// Queries the MDD for all MUX cases associated with the service, + /// used to determine which parameters are active for each MUX value. + /// + /// # Errors + /// Returns an error if the service is not found or MDD query fails. + pub async fn get_mux_cases_for_service( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_mux_cases_for_service(service_name) + } + + /// Retrieve enriched POS-RESPONSE metadata with source service name. + /// + /// Same as [`MetadataQuerying::get_enriched_response_metadata`] but also returns + /// the name of the service that actually provided the metadata. When the response is /// "opaque" (single STRUCTURE ref) and a MUX-based sibling is used, the /// returned name is the sibling โ€” callers that need to validate via /// `convert_from_uds` must use this name, not the original. /// + /// # Errors + /// Returns an error if the metadata is not available. pub(super) async fn get_enriched_response_metadata_with_source( &self, service_name: &str, @@ -119,17 +168,12 @@ impl ServiceResolver { let security_plugin: DynamicPlugin = Box::new(()); // Search READ services for a MUX-based sibling with a case for this DID. - let candidates: Vec = manager - .get_components_data_info(&security_plugin) - .into_iter() - .map(|c| c.id) - .collect(); - - for candidate in &candidates { + for component in manager.get_components_data_info(&security_plugin) { + let candidate = component.id; if candidate == service_name { continue; } - let sibling_meta = match manager.get_response_parameter_metadata(candidate) { + let sibling_meta = match manager.get_response_parameter_metadata(&candidate) { Ok(m) if m.len() > meta.len() => m, _ => continue, }; @@ -145,50 +189,200 @@ impl ServiceResolver { sibling_meta.len(), meta.len(), ); - return Ok((sibling_meta, candidate.clone())); + return Ok((sibling_meta, candidate)); } } // No MUX sibling found โ€” use original metadata. Ok((meta, service_name.to_string())) } +} - /// Look up service names by SID. - /// - /// # Errors - /// Returns an error if the lookup fails. - pub async fn lookup_service_names_by_sid( - &self, - sid: u8, - ) -> Result, DiagServiceError> { - let manager = self.manager.read().await; - let security_plugin: DynamicPlugin = Box::new(()); - let names = if sid == service_ids::READ_DATA_BY_IDENTIFIER { - manager - .get_components_data_info(&security_plugin) - .into_iter() - .map(|c| c.id) - .collect() - } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { - manager - .get_components_configurations_info(&security_plugin) - .map(|v| v.into_iter().map(|c| c.id).collect()) - .unwrap_or_default() - } else { - Vec::new() +#[cfg(test)] +mod tests { + use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; + + use super::super::uds_helpers::{find_mux_case_prefix, has_mux_case_for_did_exact}; + + /// Build a minimal `ResponseParameterInfo` MUX-case entry for test fixtures. + fn mux_case(name: &str, coded_lower: u64) -> ResponseParameterInfo { + ResponseParameterInfo { + name: format!("__mux_case__/{name}"), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: coded_lower.to_string(), + }, + byte_position: 0, + bit_position: 0, + byte_size: None, + } + } + + /// Build a plain VALUE parameter at a given byte position. + fn value_param(name: &str, pos: u32, size: u32) -> ResponseParameterInfo { + ResponseParameterInfo { + name: name.to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: pos, + bit_position: 0, + byte_size: Some(size), + } + } + + #[test] + fn test_has_mux_exact_match() { + let meta = vec![mux_case("VIN", 0xF190)]; + assert!(has_mux_case_for_did_exact(&meta, 0xF190)); + } + + #[test] + fn test_has_mux_exact_no_match() { + let meta = vec![mux_case("VIN", 0xF190)]; + // 0xF191 is one beyond the only entry โ€” no match. + assert!(!has_mux_case_for_did_exact(&meta, 0xF191)); + } + + #[test] + fn test_has_mux_exact_vs_floor_semantics() { + // Floor matching (find_mux_case_prefix) would return the 0xF100 case for + // 0xF103, but has_mux_case_for_did_exact must NOT. + let meta = vec![mux_case("RANGE", 0xF100)]; + assert!(!has_mux_case_for_did_exact(&meta, 0xF103)); + // Only the exact value matches. + assert!(has_mux_case_for_did_exact(&meta, 0xF100)); + } + + #[test] + fn test_has_mux_exact_empty_meta() { + assert!(!has_mux_case_for_did_exact(&[], 0xF190)); + } + + #[test] + fn test_has_mux_exact_non_mux_params_ignored() { + let meta = vec![value_param("DATA", 3, 17)]; + assert!(!has_mux_case_for_did_exact(&meta, 0x0000)); + } + + #[test] + fn test_floor_vs_exact_differ_for_range_case() { + let meta = vec![mux_case("RANGE", 0xF100), mux_case("OTHER", 0xF200)]; + // Floor: 0xF103 falls in the 0xF100 range โ†’ prefix returned. + assert_eq!( + find_mux_case_prefix(&meta, 0xF103), + Some("RANGE/".to_string()) + ); + // Exact: 0xF103 has no exact entry โ†’ false. + assert!(!has_mux_case_for_did_exact(&meta, 0xF103)); + // But 0xF100 itself is an exact hit. + assert!(has_mux_case_for_did_exact(&meta, 0xF100)); + } + + // The heuristic inside `get_enriched_response_metadata_with_source` checks: + // is_opaque = data_params.len() == 1 && first.byte_size.is_none() && + // !first.name.contains('/') + // We test the data-model conditions that drive it directly. + + #[test] + fn test_opaque_heuristic_single_none_size_param() { + // Only one VALUE param with byte_size = None and no '/' in name โ†’ opaque. + let param = ResponseParameterInfo { + name: "STRUCTURE_DATA".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: None, }; - Ok(names) + let data_params: Vec<_> = std::slice::from_ref(¶m) + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(is_opaque); } - /// Retrieve MUX case information for a service. - /// - /// # Errors - /// Returns an error if the metadata is not available. - pub async fn get_mux_cases_for_service( - &self, - service_name: &str, - ) -> Result, DiagServiceError> { - let manager = self.manager.read().await; - manager.get_mux_cases_for_service(service_name) + #[test] + fn test_opaque_heuristic_sized_param_not_opaque() { + // A VALUE param WITH a byte_size is NOT opaque (it has a known layout). + let param = value_param("DATA", 3, 17); + let data_params: Vec<_> = std::slice::from_ref(¶m) + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(!is_opaque); + } + + #[test] + fn test_opaque_heuristic_mux_subparam_not_opaque() { + // A MUX sub-param has '/' in its name โ†’ not opaque even if byte_size is None. + let param = ResponseParameterInfo { + name: "__mux_case__/VIN/DATA".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }; + let data_params: Vec<_> = std::slice::from_ref(¶m) + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(!is_opaque); + } + + #[test] + fn test_opaque_heuristic_multiple_params_not_opaque() { + // Multiple VALUE params โ†’ structured layout, NOT opaque. + let params = vec![value_param("FIELD_A", 3, 2), value_param("FIELD_B", 5, 1)]; + let data_params: Vec<_> = params + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(!is_opaque); } } diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs index 2afc900..301f9df 100644 --- a/proxy-core/src/service_resolver/mod.rs +++ b/proxy-core/src/service_resolver/mod.rs @@ -58,12 +58,12 @@ use cda_interfaces::{ FunctionalDescriptionConfig, HashMap, Protocol, datatypes::{ComParams, DatabaseNamingConvention, DiagnosticServiceAffixPosition}, diagservices::DiagServiceResponseType, - service_ids, }; use cda_plugin_security::DefaultSecurityPluginData; use tokio::sync::RwLock; -use uds_helpers::diag_comm_type; -pub use uds_helpers::{find_mux_case_prefix, has_mux_case_for_did_exact, parse_mux_coded_value}; +pub use uds_helpers::{ + UdsResponse, find_mux_case_prefix, has_mux_case_for_did_exact, parse_mux_coded_value, +}; /// Minimum UDS negative response length: 0x7F + SID + NRC. const UDS_NEGATIVE_RESPONSE_MIN_LEN: usize = 3; @@ -71,16 +71,29 @@ const UDS_NEGATIVE_RESPONSE_MIN_LEN: usize = 3; /// Minimum UDS positive response buffer size: response SID (1) + DID high (1) + DID low (1). const UDS_POSITIVE_RESPONSE_MIN_SIZE: usize = 3; +/// Result of a successful UDS DID-to-service resolution. +pub struct ResolvedService { + /// The matched MDD service name (e.g. `"RDBI_VIN"`). + pub name: String, + /// Decoded request parameters as a JSON map. + /// + /// Empty when the CDA request parser is unavailable for the matched service. + pub params: serde_json::Map, +} + /// Wraps the CDA's [`EcuManager`] with async locking /// to provide MDD-driven UDS encoding, decoding, and service resolution -/// for the proxy. +#[derive(Clone)] pub struct ServiceResolver { + /// All post-construction access uses `.read()` for concurrent reads. + /// The write lock is reserved for future runtime variant detection + /// (`detect_variant` requires `&mut CdaEcuManager`). manager: Arc>>, ecu_name: String, } impl ServiceResolver { - /// Create new ECU manager from MDD database. + /// Create new service resolver from ECU name and MDD database. /// /// # Arguments /// * `ecu_name` - Name of the ECU @@ -166,48 +179,32 @@ impl ServiceResolver { let mut responses: HashMap = HashMap::default(); responses.insert("__variant_init__".to_string(), dummy_response); - match manager.detect_variant(responses).await { - Ok(()) => Ok(()), - Err(e) => { - let variant = manager.variant(); - if variant.name.is_some() { + manager + .detect_variant(responses) + .await + .or_else(|e| match manager.variant().name { + Some(ref name) => { tracing::info!( "Base variant '{}' activated (state chart init skipped: {})", - variant.name.as_deref().unwrap_or("unknown"), + name, e ); Ok(()) - } else { - Err(e) } - } - } + None => Err(e), + }) } /// Check if a UDS response is negative (SID 0x7F). #[must_use] pub fn is_negative_response(uds_response: &[u8]) -> bool { - uds_response.len() >= UDS_NEGATIVE_RESPONSE_MIN_LEN - && uds_response.first().copied() == Some(service_ids::NEGATIVE_RESPONSE) + UdsResponse::new(uds_response).is_negative() } /// Extract NRC (Negative Response Code) from a negative response. #[must_use] pub fn get_nrc(uds_response: &[u8]) -> Option { - if Self::is_negative_response(uds_response) { - uds_response.get(2).copied() - } else { - None - } - } - - #[allow(clippy::unused_self)] - pub(super) fn make_diag_comm(&self, service_name: &str, service_id: u8) -> DiagComm { - DiagComm { - name: service_name.to_string(), - type_: diag_comm_type(service_id), - lookup_name: Some(service_name.to_string()), - } + UdsResponse::new(uds_response).nrc() } /// Get ECU name. diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs index 4c000c4..8512fba 100644 --- a/proxy-core/src/service_resolver/resolve.rs +++ b/proxy-core/src/service_resolver/resolve.rs @@ -10,24 +10,35 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! DID-to-service resolution. +//! DID-to-service resolution logic. //! -//! Resolves incoming UDS DID values to the correct MDD service name using -//! prefix lookup, request parameter metadata, and encoding probes. +//! Resolves incoming UDS DID values to the correct MDD service name +//! using prefix lookup, request parameter metadata, and encoding probes. +//! +//! # Exported Methods (via `ServiceResolver`) +//! - [`ServiceResolver::resolve_read_service`]: Resolve READ service for DID +//! - [`ServiceResolver::resolve_write_service`]: Resolve WRITE service for DID +//! +//! # Algorithm Overview +//! 1. `Prefix lookup` via `[SID, DID_HI, DID_LO]` against MDD coded-const services +//! 2. `Fast path`: Single prefix match -> return immediately +//! 3. `Candidate enumeration`: SID-matching services + component data/config +//! 4. `Metadata matching`: `CodedConst` (exact), `PhysConst` (`coded_value` or probe), +//! `Value` (range/list via `CompuScale`) +//! 5. `Parse validation`: Attempt CDA `convert_request_from_uds` to extract params use cda_core::EcuManager as CdaEcuManager; use cda_interfaces::{ - DiagComm, DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, HashMap, - ServiceParameterMetadata, + DynamicPlugin, EcuManager as EcuManagerTrait, HashMap, ServiceParameterMetadata, diagservices::{DiagServiceResponse, UdsPayloadData}, service_ids, }; use cda_plugin_security::DefaultSecurityPluginData; use super::{ - ServiceResolver, + ResolvedService, ServiceResolver, uds_helpers::{ - diag_comm_type, did_matches_compu_scales, extract_did_from_uds, find_did_param, + did_matches_compu_scales, extract_did_from_uds, find_did_param, make_diag_comm, make_service_payload, parse_u64_literal, }, }; @@ -38,7 +49,7 @@ impl ServiceResolver { &self, did: u16, uds_bytes: &[u8], - ) -> Option<(String, serde_json::Map)> { + ) -> Option { self.resolve_service(service_ids::READ_DATA_BY_IDENTIFIER, did, uds_bytes, "READ") .await } @@ -48,7 +59,7 @@ impl ServiceResolver { &self, did: u16, uds_bytes: &[u8], - ) -> Option<(String, serde_json::Map)> { + ) -> Option { self.resolve_service( service_ids::WRITE_DATA_BY_IDENTIFIER, did, @@ -89,11 +100,7 @@ impl ServiceResolver { } } - let diag_comm = DiagComm { - name: service_name.to_string(), - type_: diag_comm_type(sid), - lookup_name: Some(service_name.to_string()), - }; + let diag_comm = make_diag_comm(service_name, sid); let security_plugin: DynamicPlugin = Box::new(()); let payload = manager @@ -138,13 +145,45 @@ impl ServiceResolver { ) -> Option { let manager = self.manager.read().await; + // Step 1 + 2: prefix lookup and candidate list construction. + let did_prefix = [sid, (did >> 8) as u8, (did & 0xFF) as u8]; + let candidates = Self::build_did_candidates(&manager, did_prefix, sid, did, label)?; + + // Step 3: match DID against each candidate's request metadata. + for name in &candidates { + if self.match_candidate_did(&manager, name, sid, did).await { + tracing::info!("[resolve_did] {} DID 0x{:04X} -> '{}'", label, did, name); + return Some(name.clone()); + } + } + + tracing::error!( + "[resolve_did] {} no service found for DID 0x{:04X} (checked {} candidates)", + label, + did, + candidates.len() + ); + None + } + + /// Step 1 + 2: prefix lookup, fast-path, and candidate list. + /// + /// Returns `None` (after logging) when no candidates exist. + /// Returns `Some` with a single name already when the fast path fires + /// (only one prefix match โ€” skip Step 3 entirely). + fn build_did_candidates( + manager: &CdaEcuManager, + did_prefix: [u8; 3], + sid: u8, + did: u16, + label: &str, + ) -> Option> { // Step 1: Prefix lookup with [SID, DID_HI, DID_LO]. // // The CDA matches sequential coded-const parameters against the prefix: // - CODED-CONST DID services -> only exact DID matches pass. // - PhysConst / Value DID services -> only the SID byte is coded-const, // so all services with matching SID pass through. - let did_prefix = [sid, (did >> 8) as u8, (did & 0xFF) as u8]; let prefix_matches = manager .lookup_diagcomms_by_request_prefix(&did_prefix) .unwrap_or_default(); @@ -158,18 +197,17 @@ impl ServiceResolver { did, name ); - return Some(name.to_owned()); + return Some(vec![name.to_owned()]); } // Step 2: Build deduplicated candidate list from prefix matches + // supplementary sources (bypass NOT-INHERITED-DIAG-COMMS filter). - let mut seen = std::collections::HashSet::new(); let mut candidates: Vec = Vec::new(); for dc in &prefix_matches { - let name = dc.lookup_name.as_deref().unwrap_or(&dc.name); - if seen.insert(name.to_owned()) { - candidates.push(name.to_owned()); + let name = dc.lookup_name.as_deref().unwrap_or(&dc.name).to_owned(); + if !candidates.contains(&name) { + candidates.push(name); } } @@ -189,7 +227,7 @@ impl ServiceResolver { Vec::new() }; for name in extra_names { - if seen.insert(name.clone()) { + if !candidates.contains(&name) { candidates.push(name); } } @@ -205,65 +243,63 @@ impl ServiceResolver { } tracing::debug!( - "[resolve_did] {} SID 0x{:02X} DID 0x{:04X}", + "[resolve_did] {} SID 0x{:02X} DID 0x{:04X} ({} candidates)", label, sid, did, + candidates.len(), ); - // Step 3: Match DID against each candidate's request metadata. - for name in &candidates { - let Ok(meta) = manager.get_request_parameter_metadata(name) else { - continue; - }; + Some(candidates) + } - let did_param = find_did_param(&meta, sid); + /// Step 3: check if `candidate_name` matches `did` via request parameter metadata. + #[allow(clippy::cast_possible_truncation)] + async fn match_candidate_did( + &self, + manager: &CdaEcuManager, + candidate_name: &str, + sid: u8, + did: u16, + ) -> bool { + let Ok(meta) = manager.get_request_parameter_metadata(candidate_name) else { + return false; + }; - let matched = match did_param.map(|p| &p.param_type) { - Some(cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value }) => { - parse_u64_literal(coded_value) == Some(u64::from(did)) - } + let did_param = find_did_param(&meta, sid); - Some(cda_interfaces::ParameterTypeMetadata::PhysConst { coded_value, .. }) => { - let resolved = match coded_value { - Some(cv) => Some(*cv as u16), - None => Self::probe_service_did(&manager, name, sid, &meta).await, - }; - resolved == Some(did) - } + match did_param.map(|p| &p.param_type) { + Some(cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value }) => { + parse_u64_literal(coded_value) == Some(u64::from(did)) + } - Some(cda_interfaces::ParameterTypeMetadata::Value { - coded_default_value, - compu_scales, - .. - }) => { - let default_ok = coded_default_value - .map(|cd| cd as u16 == did) - .unwrap_or(false); - let scales_ok = - !compu_scales.is_empty() && did_matches_compu_scales(compu_scales, did); - - default_ok || scales_ok - } + Some(cda_interfaces::ParameterTypeMetadata::PhysConst { coded_value, .. }) => { + #[allow(clippy::cast_possible_truncation)] + let resolved = match coded_value { + Some(cv) => Some(*cv as u16), + None => Self::probe_service_did(manager, candidate_name, sid, &meta).await, + }; + resolved == Some(did) + } - None | Some(cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. }) => { - false - } - }; + Some(cda_interfaces::ParameterTypeMetadata::Value { + coded_default_value, + compu_scales, + .. + }) => { + #[allow(clippy::cast_possible_truncation)] + let default_ok = coded_default_value + .map(|cd| cd as u16 == did) + .unwrap_or(false); + let scales_ok = + !compu_scales.is_empty() && did_matches_compu_scales(compu_scales, did); + default_ok || scales_ok + } - if matched { - tracing::info!("[resolve_did] {} DID 0x{:04X} -> '{}'", label, did, name); - return Some(name.clone()); + None | Some(cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. }) => { + false } } - - tracing::error!( - "[resolve_did] {} no service found for DID 0x{:04X} (checked {} candidates)", - label, - did, - candidates.len() - ); - None } /// Find the correct service for a given SID + DID. @@ -277,7 +313,7 @@ impl ServiceResolver { did: u16, uds_bytes: &[u8], label: &str, - ) -> Option<(String, serde_json::Map)> { + ) -> Option { tracing::debug!("[MDD] {} DID 0x{:04X}", label, did); let service_name = self.resolve_service_did(sid, did, uds_bytes, label).await?; @@ -285,11 +321,7 @@ impl ServiceResolver { // Attempt parse-validation to extract structured parameter data. let manager = self.manager.read().await; let payload = make_service_payload(uds_bytes); - let diag_comm = DiagComm { - name: service_name.clone(), - type_: diag_comm_type(sid), - lookup_name: Some(service_name.clone()), - }; + let diag_comm = make_diag_comm(&service_name, sid); if let Ok(parsed) = manager .convert_request_from_uds(&diag_comm, &payload, true) @@ -303,7 +335,10 @@ impl ServiceResolver { did, service_name ); - return Some((service_name, map)); + return Some(ResolvedService { + name: service_name, + params: map, + }); } // Parse failed โ€” still return the metadata-resolved service with empty map. @@ -313,43 +348,94 @@ impl ServiceResolver { did, service_name ); - Some((service_name, serde_json::Map::new())) + Some(ResolvedService { + name: service_name, + params: serde_json::Map::new(), + }) } +} - /// Parse UDS request bytes using the MDD request structure. - /// - /// # Errors - /// Returns an error if the request cannot be parsed. - pub async fn parse_request( - &self, - service_name: &str, - uds_request: &[u8], - ) -> Result, DiagServiceError> { - let service_id = uds_request.first().copied().unwrap_or(0x00); - let diag_comm = self.make_diag_comm(service_name, service_id); - let payload = make_service_payload(uds_request); +#[cfg(test)] +mod tests { + use cda_interfaces::service_ids; - let manager = self.manager.read().await; - let response = manager - .convert_request_from_uds(&diag_comm, &payload, true) - .await?; - let json_response = response.into_json()?; + use super::super::uds_helpers::{did_matches_compu_scales, find_did_param, parse_u64_literal}; - if let serde_json::Value::Object(map) = json_response.data { - tracing::debug!( - "[MDD] Parsed request for '{}': {} fields", - service_name, - map.len() - ); - Ok(map) - } else { - tracing::error!( - "[MDD] Expected JSON object in request, got: {:?}", - json_response.data - ); - Err(DiagServiceError::InvalidRequest( - "Expected JSON object in request".to_string(), - )) - } + /// `parse_u64_literal` parses decimal and hexadecimal strings. + #[test] + fn test_parse_u64_literal_decimal() { + assert_eq!(parse_u64_literal("0"), Some(0)); + assert_eq!(parse_u64_literal("61699"), Some(61_699)); + } + + #[test] + fn test_parse_u64_literal_hex() { + assert_eq!(parse_u64_literal("0xF103"), Some(0xF103)); + assert_eq!(parse_u64_literal("0XFF"), Some(0xFF)); + // bare hex fallback (no prefix) + assert_eq!(parse_u64_literal("F103"), Some(0xF103)); + } + + #[test] + fn test_parse_u64_literal_invalid() { + assert_eq!(parse_u64_literal(""), None); + assert_eq!(parse_u64_literal("abc xyz"), None); + } + + /// `did_matches_compu_scales` returns true when DID falls in any range. + #[test] + fn test_did_matches_compu_scales_in_range() { + use cda_interfaces::CompuScaleInfo; + let scales = vec![CompuScaleInfo { + short_label: None, + lower_limit: Some(0xF100), + upper_limit: Some(0xF1FF), + compu_const_vt: None, + }]; + assert!(did_matches_compu_scales(&scales, 0xF190)); + assert!(did_matches_compu_scales(&scales, 0xF100)); + assert!(did_matches_compu_scales(&scales, 0xF1FF)); + assert!(!did_matches_compu_scales(&scales, 0xF200)); + } + + /// `find_did_param` skips the SID `CodedConst` and returns the next parameter. + #[test] + fn test_find_did_param_skips_sid() { + use cda_interfaces::{ParameterTypeMetadata, ServiceParameterMetadata}; + let sid = service_ids::READ_DATA_BY_IDENTIFIER; // 0x22 + let meta = vec![ + ServiceParameterMetadata { + name: "SID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), // 0x22 + }, + }, + ServiceParameterMetadata { + name: "DID".to_string(), + semantic: Some("DATA-IDENTIFIER".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61824".to_string(), // 0xF190 + }, + }, + ]; + let param = find_did_param(&meta, sid); + assert!(param.is_some()); + assert_eq!(param.unwrap().name, "DID"); + } + + /// `find_did_param` returns `None` when no DID parameter is present. + #[test] + fn test_find_did_param_none_when_only_sid() { + use cda_interfaces::{ParameterTypeMetadata, ServiceParameterMetadata}; + let sid = service_ids::READ_DATA_BY_IDENTIFIER; + let meta = vec![ServiceParameterMetadata { + name: "SID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), + }, + }]; + assert!(find_did_param(&meta, sid).is_none()); } } diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index 6bec4fa..430d009 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -23,8 +23,8 @@ use cda_interfaces::{ use super::{ ServiceResolver, UDS_POSITIVE_RESPONSE_MIN_SIZE, uds_helpers::{ - encode_unsigned_be, encode_value_at, find_mux_case_prefix, make_service_payload, - value_to_bytes, + encode_unsigned_be, encode_value_at, find_mux_case_prefix, make_diag_comm, + make_service_payload, value_to_bytes, }, }; @@ -146,7 +146,7 @@ impl ServiceResolver { /// Called only when `tracing::Level::DEBUG` is enabled โ€” failures are logged /// as warnings but never block the response (non-blocking). async fn validate_response(&self, service_name: &str, request_sid: u8, uds_response: &[u8]) { - let diag_comm = self.make_diag_comm(service_name, request_sid); + let diag_comm = make_diag_comm(service_name, request_sid); let payload = make_service_payload(uds_response); let manager = self.manager.read().await; match manager.convert_from_uds(&diag_comm, &payload, true).await { @@ -334,3 +334,258 @@ impl ServiceResolver { Some((response, effective_service)) } } + +#[cfg(test)] +mod tests { + use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; + + use super::super::uds_helpers::{ + encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, + }; + + /// Numbers are right-aligned (big-endian) in the target field. + #[test] + fn test_encode_value_at_number_right_aligned() { + let mut buf = [0u8; 5]; + encode_value_at(&mut buf, 1, 2, Some(&serde_json::json!(0xF1_90u64))); + assert_eq!(buf, [0x00, 0xF1, 0x90, 0x00, 0x00]); + } + + #[test] + fn test_encode_value_at_number_single_byte() { + let mut buf = [0u8; 3]; + encode_value_at(&mut buf, 0, 1, Some(&serde_json::json!(0x62u64))); + assert_eq!(buf, [0x62, 0x00, 0x00]); + } + + /// A string value is written left-aligned (byte-for-byte). + #[test] + fn test_encode_value_at_string() { + let mut buf = [0u8; 6]; + encode_value_at(&mut buf, 1, 4, Some(&serde_json::json!("VIN!"))); + assert_eq!(&buf[1..5], b"VIN!"); + assert_eq!(buf[0], 0x00); + assert_eq!(buf[5], 0x00); + } + + /// A string longer than `size` is truncated. + #[test] + fn test_encode_value_at_string_truncated() { + let mut buf = [0u8; 4]; + encode_value_at(&mut buf, 0, 2, Some(&serde_json::json!("ABCDE"))); + assert_eq!(&buf[..2], b"AB"); + assert_eq!(buf[2], 0x00); + } + + /// A JSON array encodes each element as one byte. + #[test] + fn test_encode_value_at_array() { + let mut buf = [0u8; 5]; + encode_value_at( + &mut buf, + 1, + 3, + Some(&serde_json::json!([0xDEu64, 0xADu64, 0xBEu64])), + ); + assert_eq!(&buf[1..4], [0xDE, 0xAD, 0xBE]); + } + + /// `true` encodes as 0x01, `false` as 0x00. + #[test] + fn test_encode_value_at_bool() { + let mut buf = [0u8; 2]; + encode_value_at(&mut buf, 0, 1, Some(&serde_json::json!(true))); + assert_eq!(buf[0], 0x01); + encode_value_at(&mut buf, 1, 1, Some(&serde_json::json!(false))); + assert_eq!(buf[1], 0x00); + } + + /// `None` leaves the buffer untouched. + #[test] + fn test_encode_value_at_none_noop() { + let mut buf = [0xFFu8; 4]; + encode_value_at(&mut buf, 0, 4, None); + assert_eq!(buf, [0xFF, 0xFF, 0xFF, 0xFF]); + } + + /// Out-of-bounds write is silently ignored. + #[test] + fn test_encode_value_at_out_of_bounds_noop() { + let mut buf = [0u8; 2]; + // pos=1, size=3 โ†’ end=4 > buf.len()=2 โ†’ noop + encode_value_at(&mut buf, 1, 3, Some(&serde_json::json!(0xFFu64))); + assert_eq!(buf, [0x00, 0x00]); + } + + #[test] + fn test_value_to_bytes_number() { + assert_eq!( + value_to_bytes(Some(&serde_json::json!(0xF190u64))), + vec![0xF1, 0x90] + ); + } + + #[test] + fn test_value_to_bytes_string() { + assert_eq!( + value_to_bytes(Some(&serde_json::json!("AB"))), + b"AB".to_vec() + ); + } + + #[test] + fn test_value_to_bytes_array() { + assert_eq!( + value_to_bytes(Some(&serde_json::json!([0x01u64, 0x02u64]))), + vec![0x01, 0x02] + ); + } + + #[test] + fn test_value_to_bytes_none() { + assert_eq!(value_to_bytes(None), Vec::::new()); + } + + #[test] + fn test_encode_unsigned_be_zero() { + assert_eq!(encode_unsigned_be(0), vec![0x00]); + } + + #[test] + fn test_encode_unsigned_be_two_bytes() { + assert_eq!(encode_unsigned_be(0xF190), vec![0xF1, 0x90]); + } + + /// Build a MUX-case marker `ResponseParameterInfo`. + fn mux_case_marker(name: &str, lower: u64) -> ResponseParameterInfo { + ResponseParameterInfo { + name: format!("__mux_case__/{name}"), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: lower.to_string(), + }, + byte_position: 0, + bit_position: 0, + byte_size: None, + } + } + + fn value_param(name: &str, pos: u32, size: u32) -> ResponseParameterInfo { + ResponseParameterInfo { + name: name.to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: pos, + bit_position: 0, + byte_size: Some(size), + } + } + + fn coded_const_param(name: &str, pos: u32, size: u32, val: &str) -> ResponseParameterInfo { + ResponseParameterInfo { + name: name.to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: val.to_string(), + }, + byte_position: pos, + bit_position: 0, + byte_size: Some(size), + } + } + + /// When a MUX case prefix matches the DID, only that case's sub-params + /// (and the top-level params without '/') are selected; the other case + /// sub-params are dropped. + #[test] + fn test_active_params_with_mux_case() { + let did: u16 = 0xF190; + // Sub-params use the case-name prefix (e.g. "VIN/"), NOT "__mux_case__/VIN/". + let meta = vec![ + coded_const_param("SID", 0, 1, "98"), // top-level, no '/' + value_param("DID", 1, 2), // top-level, no '/' + mux_case_marker("VIN", 0xF190), // case marker for 0xF190 + mux_case_marker("OTHER", 0xF100), // different case marker + value_param("VIN/DATA", 3, 17), // VIN sub-param + value_param("OTHER/DATA", 3, 4), // OTHER sub-param โ†’ excluded + ]; + + let mux_case_prefix = find_mux_case_prefix(&meta, did); + let mux_marker_name: Option = mux_case_prefix + .as_deref() + .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + let active: Vec<_> = meta + .iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = &mux_case_prefix { + p.name.starts_with(prefix.as_str()) + || mux_marker_name.as_deref() == Some(p.name.as_str()) + } else { + !p.name.starts_with("__mux_case__/") + } + }) + .map(|p| p.name.as_str()) + .collect(); + + assert!(active.contains(&"SID"), "top-level SID must be kept"); + assert!(active.contains(&"DID"), "top-level DID must be kept"); + assert!(active.contains(&"VIN/DATA"), "VIN sub-param must be kept"); + assert!( + !active.contains(&"OTHER/DATA"), + "OTHER sub-param must be excluded" + ); + } + + /// Without any MUX case (flat metadata), all params without '/' are kept + /// and any accidental `__mux_case__` entries are dropped. + #[test] + fn test_active_params_no_mux_case() { + let did: u16 = 0x1234; + let meta = vec![ + coded_const_param("SID", 0, 1, "98"), + value_param("DATA", 3, 4), + ]; + + let mux_case_prefix = find_mux_case_prefix(&meta, did); + assert!(mux_case_prefix.is_none()); + + let active: Vec<_> = meta + .iter() + .filter(|p| !p.name.contains('/') || p.name.starts_with("__mux_case__/")) + .map(|p| p.name.as_str()) + .collect(); + + assert_eq!(active, ["SID", "DATA"]); + } + + /// `total_size` is the maximum of (`byte_position` + `effective_size`) across params. + #[test] + fn test_total_size_from_params() { + let params = vec![ + coded_const_param("SID", 0, 1, "98"), + value_param("DID", 1, 2), + value_param("DATA", 3, 17), + ]; + let effective_sizes: Vec = params + .iter() + .map(|p| p.byte_size.map_or(0, |s| s as usize)) + .collect(); + + let total = params + .iter() + .zip(effective_sizes.iter()) + .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) + .max() + .unwrap_or(3); + + // SID: 0+1=1, DID: 1+2=3, DATA: 3+17=20 โ†’ max = 20 + assert_eq!(total, 20); + } +} diff --git a/proxy-core/src/service_resolver/uds_helpers.rs b/proxy-core/src/service_resolver/uds_helpers.rs index aabbb42..3730b2b 100644 --- a/proxy-core/src/service_resolver/uds_helpers.rs +++ b/proxy-core/src/service_resolver/uds_helpers.rs @@ -10,15 +10,54 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! UDS helper functions for encoding, decoding, and service metadata queries. +//! UDS helper functions, types for encoding, decoding, and service metadata queries. //! -//! Pure functions used across the [`super::ServiceResolver`] implementation: -//! DID extraction, MUX-case matching, value encoding, and payload construction. +//! Pure functions and types used across the [`super::ServiceResolver`] implementation: +//! DID extraction, MUX-case matching, value encoding, payload construction, and +//! structured access to UDS response bytes. use cda_interfaces::{ - CompuScaleInfo, DiagCommType, ResponseParameterInfo, ServiceParameterMetadata, ServicePayload, + CompuScaleInfo, DiagComm, DiagCommType, ResponseParameterInfo, ServiceParameterMetadata, + ServicePayload, service_ids, }; +use super::UDS_NEGATIVE_RESPONSE_MIN_LEN; + +/// Typed accessor for raw UDS response bytes. +/// +/// Wraps a byte slice and exposes structured accessors for UDS response fields, +/// hiding direct index arithmetic from callers. +pub struct UdsResponse<'a>(&'a [u8]); + +impl<'a> UdsResponse<'a> { + /// Wrap raw UDS response bytes. + #[must_use] + pub fn new(bytes: &'a [u8]) -> Self { + Self(bytes) + } + + /// Service Identifier byte of the response. + #[must_use] + pub fn sid(&self) -> Option { + self.0.first().copied() + } + + /// Returns `true` if this is a negative response (SID `0x7F`). + #[must_use] + pub fn is_negative(&self) -> bool { + self.0.len() >= UDS_NEGATIVE_RESPONSE_MIN_LEN + && self.sid() == Some(service_ids::NEGATIVE_RESPONSE) + } + + /// Extract the Negative Response Code from a negative response. + /// + /// Returns `None` if this is not a negative response or the byte is absent. + #[must_use] + pub fn nrc(&self) -> Option { + self.is_negative().then(|| self.0.get(2).copied()).flatten() + } +} + /// Extract the 16-bit DID from UDS payload bytes at offset 1โ€“2. /// /// Returns `None` if the slice has fewer than 3 bytes. @@ -315,6 +354,20 @@ pub(super) fn value_to_bytes(value: Option<&serde_json::Value>) -> Vec { } } +/// Create a [`DiagComm`] for the given service name and UDS service identifier. +/// +/// Centralises the repeated inline construction so that callers never have to +/// name [`DiagComm`] directly. Both `name` and `lookup_name` are set to the +/// same value, which is what the CDA requires for service dispatch. +pub(super) fn make_diag_comm(service_name: &str, service_id: u8) -> DiagComm { + let name = service_name.to_string(); + DiagComm { + lookup_name: Some(name.clone()), + name, + type_: diag_comm_type(service_id), + } +} + #[cfg(test)] mod tests { use cda_interfaces::ParameterTypeMetadata; From 06c5c41ecd4d78e87da02d3d42fab281347190a0 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 28 Apr 2026 06:40:51 +0200 Subject: [PATCH 07/33] Fix: Addresss review comments Signed-off-by: Arvind Rathod --- README.md | 2 +- docs/ServiceResolver_Sequence_Diagram.svg | 6 +- ...rviceResolver_Sequence_Diagram.svg.license | 9 ++ docs/service_resolver_class.svg | 6 +- docs/service_resolver_class.svg.license | 9 ++ proxy-core/src/config.rs | 85 +++++++++++-------- proxy-core/src/error.rs | 8 +- proxy-core/src/service_resolver/metadata.rs | 16 ++-- proxy-core/src/service_resolver/mod.rs | 2 +- proxy-core/src/service_resolver/resolve.rs | 23 +++-- proxy-core/src/service_resolver/response.rs | 7 +- .../src/service_resolver/uds_helpers.rs | 40 ++++----- 12 files changed, 129 insertions(+), 84 deletions(-) create mode 100644 docs/ServiceResolver_Sequence_Diagram.svg.license create mode 100644 docs/service_resolver_class.svg.license diff --git a/README.md b/README.md index 6454936..d0d7dd3 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ DoIP Client (port 13400) โ†“ UDS request (0x22 DID) Proxy (service resolution via MDD) โ†“ SOVD REST (GET /data/vindataidentifier_read) -Mock Gateway OR Real CDA +Mock Gateway OR Real SOVD Server โ†“ SOVD JSON response Proxy (MDD-based UDS encoding) โ†“ UDS response (0x62 DID data) diff --git a/docs/ServiceResolver_Sequence_Diagram.svg b/docs/ServiceResolver_Sequence_Diagram.svg index b767756..461ce4d 100644 --- a/docs/ServiceResolver_Sequence_Diagram.svg +++ b/docs/ServiceResolver_Sequence_Diagram.svg @@ -1 +1,5 @@ -ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(resolve.rs)ServiceResolver(resolve.rs)ServiceResolver(metadata.rs)ServiceResolver(metadata.rs)ServiceResolver(response.rs)ServiceResolver(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve_read_service(did, uds_bytes)resolve_service(SID=0x22, did, uds_bytes)resolve_service_did()Step 1-2: Prefix lookup& candidate buildinglookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching servicesbuild_did_candidates()Fast path: single matchelse: enumerate SID-matchingservices via get_components_data_info()match_candidate_did()Step 3: Metadata matchingCodedConst / PhysConst / Value DIDsget_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)Exact match against DID[PhysConst DID]probe_service_did() (optional)Encode dummy request,extract DID from payloadcreate_uds_payload()encoded payloadextract_did_from_uds()[Value DID]did_matches_compu_scales()Range/list matching via MDD CompuScaleconvert_request_from_uds()parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesusing SID=0x2E andget_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)encode_response_from_metadata()get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutOpaque heuristic:Single VALUE with byte_size=Noneand no '/' in name?alt[opaque STRUCTURE detected]get_components_data_info()READ service componentshas_mux_case_for_did_exact(sibling_meta, did)Exact match — avoidscross-DOP false positives(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)mux_case_prefix = find_mux_case_prefix(meta, did)Floor-based matchingfor MUX case active paramsfilter active params by mux_case_prefixSelect top-level params +case-specific sub-paramsalt[metadata available]for each active param:encode_value_at(buf, pos, size, value)CodedConst -> fixed bytesMatchingRequestParam -> DID bytesValue -> encode_value_at()(encoded_bytes, effective_service)[no metadata (fallback)]naive encoding via value_to_bytes()Iterate response_dataString/Number/Array/Boolno MDD structurealt[DEBUG enabled]validate_response()convert_from_uds()JSONRound-trip validation:warn on mismatch, never blocksResult<Vec<u8>, DiagServiceError>  Module Layout (impl ServiceResolver): -resolve.rs: DID -> service resolution,candidate building, metadata matching-response.rs: UDS response encoding,round-trip validation (debug only)-metadata.rs: MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure utilities —encoding, decoding, MUX matching Resolution Algorithm (resolve.rs):1. Prefix lookup [SID, DID_HI, DID_LO]2. Fast path: single prefix match -> return3. Enumerate all SID-matching services4. Match via CodedConst / PhysConst / Value5. Parse request params inline via CDA \ No newline at end of file + +ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(resolve.rs)ServiceResolver(resolve.rs)ServiceResolver(metadata.rs)ServiceResolver(metadata.rs)ServiceResolver(response.rs)ServiceResolver(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve_read_service(did, uds_bytes)resolve_service(SID=0x22, did, uds_bytes)resolve_service_did()Step 1-2: Prefix lookup& candidate buildinglookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching servicesbuild_did_candidates()Fast path: single matchelse: enumerate SID-matchingservices via get_components_data_info()match_candidate_did()Step 3: Metadata matchingCodedConst / PhysConst / Value DIDsget_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)Exact match against DID[PhysConst DID]probe_service_did() (optional)Encode dummy request,extract DID from payloadcreate_uds_payload()encoded payloadextract_did_from_uds()[Value DID]did_matches_compu_scales()Range/list matching via MDD CompuScaleconvert_request_from_uds()parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesusing SID=0x2E andget_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)encode_response_from_metadata()get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutOpaque heuristic:Single VALUE with byte_size=Noneand no '/' in name?alt[opaque STRUCTURE detected]get_components_data_info()READ service componentshas_mux_case_for_did_exact(sibling_meta, did)Exact match — avoidscross-DOP false positives(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)mux_case_prefix = find_mux_case_prefix(meta, did)Floor-based matchingfor MUX case active paramsfilter active params by mux_case_prefixSelect top-level params +case-specific sub-paramsalt[metadata available]for each active param:encode_value_at(buf, pos, size, value)CodedConst -> fixed bytesMatchingRequestParam -> DID bytesValue -> encode_value_at()(encoded_bytes, effective_service)[no metadata (fallback)]naive encoding via value_to_bytes()Iterate response_dataString/Number/Array/Boolno MDD structurealt[DEBUG enabled]validate_response()convert_from_uds()JSONRound-trip validation:warn on mismatch, never blocksResult<Vec<u8>, DiagServiceError>  Module Layout (impl ServiceResolver): -resolve.rs: DID -> service resolution,candidate building, metadata matching-response.rs: UDS response encoding,round-trip validation (debug only)-metadata.rs: MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure utilities —encoding, decoding, MUX matching Resolution Algorithm (resolve.rs):1. Prefix lookup [SID, DID_HI, DID_LO]2. Fast path: single prefix match -> return3. Enumerate all SID-matching services4. Match via CodedConst / PhysConst / Value5. Parse request params inline via CDA diff --git a/docs/ServiceResolver_Sequence_Diagram.svg.license b/docs/ServiceResolver_Sequence_Diagram.svg.license new file mode 100644 index 0000000..7319749 --- /dev/null +++ b/docs/ServiceResolver_Sequence_Diagram.svg.license @@ -0,0 +1,9 @@ +SPDX-License-Identifier: Apache-2.0 +SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + +See the NOTICE file(s) distributed with this work for additional +information regarding copyright ownership. + +This program and the accompanying materials are made available under the +terms of the Apache License Version 2.0 which is available at +https://www.apache.org/licenses/LICENSE-2.0 diff --git a/docs/service_resolver_class.svg b/docs/service_resolver_class.svg index dbed3e5..c920c08 100644 --- a/docs/service_resolver_class.svg +++ b/docs/service_resolver_class.svg @@ -1 +1,5 @@ -Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)ServiceResolver-manager : Arc<RwLock<CdaEcuManager>>-ecu_name : String+new(ecu_name, db, logical, tester) : Result<Self>+ecu_name() : &str+is_negative_response(uds) : bool+get_nrc(uds) : Option<u8>mod.rs — construction & UDS helpers+«async» resolve_read_service(did, uds) : Option<ResolvedService>+«async» resolve_write_service(did, uds) : Option<ResolvedService>resolve.rs — DID --> service name+«async» build_response(name, sid, did, data) : Result<Vec<u8>>response.rs — encode UDS response+«async» get_service_parameter_metadata(name) : Result<Vec<Param>>+«async» get_response_parameter_metadata(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs — MDD parameter queries Service resolution algorithm (resolve.rs):1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:• CodedConst — exact DID value match• PhysConst — coded_value or create_uds_payload probe• Value — coded_default or CompuScale range match4. No match --> log error, return None (no fallback) Response encoding (response.rs):Walk MDD POS-RESPONSE parameters:• CODED-CONST --> fixed byte (e.g. response SID 0x62)• MatchingRequestParam --> echo DID bytes from request• VALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookup.«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rsand used by proxy-sovd for MUX matching.«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(service)+create_uds_payload(service, params)+convert_from_uds(service, bytes)+convert_request_from_uds(service, bytes)+detect_variant()CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>«struct»ResolvedService+name : String+params : Mapusesowns via Arc<RwLock>(shared with callers)Async RwLock allows concurrentread access across Tokio tasks. \ No newline at end of file + +Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)ServiceResolver-manager : Arc<RwLock<CdaEcuManager>>-ecu_name : String+new(ecu_name, db, logical, tester) : Result<Self>+ecu_name() : &str+is_negative_response(uds) : bool+get_nrc(uds) : Option<u8>mod.rs — construction & UDS helpers+«async» resolve_read_service(did, uds) : Option<ResolvedService>+«async» resolve_write_service(did, uds) : Option<ResolvedService>resolve.rs — DID --> service name+«async» build_response(name, sid, did, data) : Result<Vec<u8>>response.rs — encode UDS response+«async» get_service_parameter_metadata(name) : Result<Vec<Param>>+«async» get_response_parameter_metadata(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs — MDD parameter queries Service resolution algorithm (resolve.rs):1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:• CodedConst — exact DID value match• PhysConst — coded_value or create_uds_payload probe• Value — coded_default or CompuScale range match4. No match --> log error, return None (no fallback) Response encoding (response.rs):Walk MDD POS-RESPONSE parameters:• CODED-CONST --> fixed byte (e.g. response SID 0x62)• MatchingRequestParam --> echo DID bytes from request• VALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookup.«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rsand used by proxy-sovd for MUX matching.«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(service)+create_uds_payload(service, params)+convert_from_uds(service, bytes)+convert_request_from_uds(service, bytes)+detect_variant()CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>«struct»ResolvedService+name : String+params : Mapusesowns via Arc<RwLock>(shared with callers)Async RwLock allows concurrentread access across Tokio tasks. diff --git a/docs/service_resolver_class.svg.license b/docs/service_resolver_class.svg.license new file mode 100644 index 0000000..7319749 --- /dev/null +++ b/docs/service_resolver_class.svg.license @@ -0,0 +1,9 @@ +SPDX-License-Identifier: Apache-2.0 +SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + +See the NOTICE file(s) distributed with this work for additional +information regarding copyright ownership. + +This program and the accompanying materials are made available under the +terms of the Apache License Version 2.0 which is available at +https://www.apache.org/licenses/LICENSE-2.0 diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index 8a9d699..e48a0aa 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -10,7 +10,10 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -use std::path::Path; +use std::{ + net::{IpAddr, Ipv4Addr}, + path::Path, +}; use serde::{Deserialize, Deserializer, de}; @@ -18,8 +21,36 @@ use crate::error::{ProxyError, Result}; /// Required byte length for EID and GID fields per ISO 13400-2. const EID_GID_BYTE_LENGTH: usize = 6; +/// Top-level proxy configuration loaded from a TOML file. +#[derive(Debug, Clone, Deserialize, Default)] +pub struct Config { + /// `DoIP` server settings (port, bind address, source address). + pub server: ServerConfig, + /// SOVD gateway connection settings. + pub sovd: SovdConfig, + /// ECU identity and addressing settings. + pub ecu: EcuConfig, + /// Logging configuration. + pub logging: LoggingConfig, +} + +/// `DoIP` server configuration. +#[derive(Debug, Clone, Deserialize)] +pub struct ServerConfig { + /// TCP port for the `DoIP` server (default: 13400). + #[serde(deserialize_with = "deserialize_nonzero_u16")] + pub doip_port: u16, + /// IP address to bind the server socket to. + #[serde(deserialize_with = "deserialize_ip_addr")] + pub bind_address: IpAddr, + /// Maximum number of concurrent connections. + #[serde(deserialize_with = "deserialize_max_connections")] + pub max_connections: usize, + /// `DoIP` source address used in response messages. + #[serde(deserialize_with = "deserialize_nonzero_u16")] + pub source_address: u16, +} -/// Reject zero during deserialization so invalid values never enter the config. fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -30,8 +61,17 @@ fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( Ok(v) } +/// Deserialize IP address string into `std::net::IpAddr`. +fn deserialize_ip_addr<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let s = String::deserialize(deserializer)?; + s.parse::() + .map_err(|_| de::Error::custom(format!("invalid IP address: {s}"))) +} + /// Reject zero during deserialization for `usize` fields. -fn deserialize_positive_usize<'de, D: Deserializer<'de>>( +fn deserialize_max_connections<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { let v = usize::deserialize(deserializer)?; @@ -41,50 +81,21 @@ fn deserialize_positive_usize<'de, D: Deserializer<'de>>( Ok(v) } -/// Reject empty strings during deserialization. -fn deserialize_nonempty_str<'de, D: Deserializer<'de>>( +/// Reject empty gateway URL strings during deserialization. +fn deserialize_nonempty_gateway_url<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { let s = String::deserialize(deserializer)?; if s.is_empty() { - return Err(de::Error::custom("value must not be empty")); + return Err(de::Error::custom("gateway_url must not be empty")); } Ok(s) } - -/// Top-level proxy configuration loaded from a TOML file. -#[derive(Debug, Clone, Deserialize, Default)] -pub struct Config { - /// `DoIP` server settings (port, bind address, source address). - pub server: ServerConfig, - /// SOVD gateway connection settings. - pub sovd: SovdConfig, - /// ECU identity and addressing settings. - pub ecu: EcuConfig, - /// Logging configuration. - pub logging: LoggingConfig, -} - -/// `DoIP` server configuration. -#[derive(Debug, Clone, Deserialize)] -pub struct ServerConfig { - /// TCP port for the `DoIP` server (default: 13400). - #[serde(deserialize_with = "deserialize_nonzero_u16")] - pub doip_port: u16, - /// IP address to bind the server socket to. - pub bind_address: String, - /// Maximum number of concurrent connections. - #[serde(deserialize_with = "deserialize_positive_usize")] - pub max_connections: usize, - /// `DoIP` source address used in response messages. - pub source_address: u16, -} - /// SOVD gateway connection configuration. #[derive(Debug, Clone, Deserialize)] pub struct SovdConfig { /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). - #[serde(deserialize_with = "deserialize_nonempty_str")] + #[serde(deserialize_with = "deserialize_nonempty_gateway_url")] pub gateway_url: String, /// `OAuth2` client ID for gateway authentication. pub client_id: String, @@ -149,7 +160,7 @@ impl Default for ServerConfig { fn default() -> Self { Self { doip_port: 13400, - bind_address: "0.0.0.0".to_string(), + bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), max_connections: 10, source_address: 0x0E80, } diff --git a/proxy-core/src/error.rs b/proxy-core/src/error.rs index 81b40d7..e1c5ae7 100644 --- a/proxy-core/src/error.rs +++ b/proxy-core/src/error.rs @@ -68,7 +68,7 @@ pub enum UdsError { /// SOVD gateway communication errors. #[derive(Error, Debug)] pub enum SovdError { - #[error("HTTP request failed: {0}")] + #[error("HTTP error: {0}")] Http(String), #[error("Authentication failed: {0}")] @@ -268,6 +268,12 @@ mod tests { }; assert!(err.to_string().contains('3')); assert!(err.to_string().contains('1')); + + let err = UdsError::NegativeResponse { + nrc: 0x31, + description: "Request out of range".into(), + }; + assert!(err.to_string().contains("0x31")); } #[test] diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs index dcbb9d8..7f6a977 100644 --- a/proxy-core/src/service_resolver/metadata.rs +++ b/proxy-core/src/service_resolver/metadata.rs @@ -84,19 +84,19 @@ impl ServiceResolver { ) -> Result, DiagServiceError> { let manager = self.manager.read().await; let security_plugin: DynamicPlugin = Box::new(()); - let names = if sid == service_ids::READ_DATA_BY_IDENTIFIER { - manager + let names = match sid { + service_ids::READ_DATA_BY_IDENTIFIER => manager .get_components_data_info(&security_plugin) .into_iter() .map(|c| c.id) - .collect() - } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { - manager + .collect(), + service_ids::WRITE_DATA_BY_IDENTIFIER => manager .get_components_configurations_info(&security_plugin) - .map(|v| v.into_iter().map(|c| c.id).collect()) .unwrap_or_default() - } else { - Vec::new() + .into_iter() + .map(|c| c.id) + .collect(), + _ => Vec::new(), }; Ok(names) } diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs index 301f9df..ab57a33 100644 --- a/proxy-core/src/service_resolver/mod.rs +++ b/proxy-core/src/service_resolver/mod.rs @@ -150,7 +150,7 @@ impl ServiceResolver { /// state-chart and pins the engine to a determinate base state. /// /// #`TODO:` real variant detection - /// + /// /// Replace the dummy response with actual variant-identification DID /// reads from a live ECU connection: /// 1. Read variant-identification DIDs from the ECU. diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs index 8512fba..21a0ac0 100644 --- a/proxy-core/src/service_resolver/resolve.rs +++ b/proxy-core/src/service_resolver/resolve.rs @@ -135,6 +135,8 @@ impl ServiceResolver { /// * `did` - 16-bit Data Identifier to resolve. /// * `uds_bytes` - Raw incoming UDS request bytes. /// * `label` - Log prefix string (e.g. `"READ"`, `"WRITE"`). + // `did` is `u16`; `did >> 8` is at most 0xFF and `did & 0xFF` is at most 0xFF, + // so both narrowing casts to `u8` are safe and can never truncate. #[allow(clippy::cast_possible_truncation)] async fn resolve_service_did( &self, @@ -212,19 +214,19 @@ impl ServiceResolver { } let security_plugin: DynamicPlugin = Box::new(()); - let extra_names: Vec = if sid == service_ids::READ_DATA_BY_IDENTIFIER { - manager + let extra_names: Vec = match sid { + service_ids::READ_DATA_BY_IDENTIFIER => manager .get_components_data_info(&security_plugin) .into_iter() .map(|c| c.id) - .collect() - } else if sid == service_ids::WRITE_DATA_BY_IDENTIFIER { - manager + .collect(), + service_ids::WRITE_DATA_BY_IDENTIFIER => manager .get_components_configurations_info(&security_plugin) - .map(|v| v.into_iter().map(|c| c.id).collect()) .unwrap_or_default() - } else { - Vec::new() + .into_iter() + .map(|c| c.id) + .collect(), + _ => Vec::new(), }; for name in extra_names { if !candidates.contains(&name) { @@ -254,7 +256,6 @@ impl ServiceResolver { } /// Step 3: check if `candidate_name` matches `did` via request parameter metadata. - #[allow(clippy::cast_possible_truncation)] async fn match_candidate_did( &self, manager: &CdaEcuManager, @@ -274,6 +275,8 @@ impl ServiceResolver { } Some(cda_interfaces::ParameterTypeMetadata::PhysConst { coded_value, .. }) => { + // `coded_value` is `f64` in the CDA schema; DIDs are bounded to + // u16 (0x0000โ€“0xFFFF per ISO 14229), so the narrowing cast is safe. #[allow(clippy::cast_possible_truncation)] let resolved = match coded_value { Some(cv) => Some(*cv as u16), @@ -287,6 +290,8 @@ impl ServiceResolver { compu_scales, .. }) => { + // `coded_default_value` is `f64` in the CDA schema; DIDs are bounded + // to u16 (0x0000โ€“0xFFFF per ISO 14229), so the narrowing cast is safe. #[allow(clippy::cast_possible_truncation)] let default_ok = coded_default_value .map(|cd| cd as u16 == did) diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index 430d009..5225a7e 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -45,7 +45,7 @@ impl ServiceResolver { /// # Errors /// Returns an error if the response cannot be encoded. /// - /// # TODO: + /// # TODO : /// Once the SOVD server returns properly structured responses, the naive /// encoding fallback and the MDD-based `encode_response_from_metadata` /// path can be removed โ€” the proxy will forward pre-encoded UDS bytes. @@ -75,6 +75,8 @@ impl ServiceResolver { service_name ); let response_sid = sid.wrapping_add(UDS_ID_RESPONSE_BITMASK); + // `did` is `u16`; `did >> 8` โ‰ค 0xFF and `did & 0xFF` โ‰ค 0xFF โ€” both + // narrowing casts to `u8` are always safe. #[allow(clippy::cast_possible_truncation)] let mut response = vec![response_sid, (did >> 8) as u8, (did & 0xFF) as u8]; @@ -93,6 +95,7 @@ impl ServiceResolver { response.extend(encode_unsigned_be(num)); } else if let Some(num) = n.as_i64() { let unsigned = num.cast_unsigned(); + // `try_from` check above proves `unsigned` fits in `u8`. #[allow(clippy::cast_possible_truncation)] if u8::try_from(unsigned).is_ok() { response.push(unsigned as u8); @@ -104,6 +107,8 @@ impl ServiceResolver { } serde_json::Value::Array(arr) => { for item in arr { + // Array elements in a JSON byte-array response are UDS byte + // values (0โ€“255). Truncation to `u8` is intentional. #[allow(clippy::cast_possible_truncation)] if let Some(byte) = item.as_u64() { response.push(byte as u8); diff --git a/proxy-core/src/service_resolver/uds_helpers.rs b/proxy-core/src/service_resolver/uds_helpers.rs index 3730b2b..bd222cc 100644 --- a/proxy-core/src/service_resolver/uds_helpers.rs +++ b/proxy-core/src/service_resolver/uds_helpers.rs @@ -108,21 +108,18 @@ pub(super) fn encode_unsigned_be(num: u64) -> Vec { #[must_use] pub fn parse_mux_coded_value(coded_value: &str) -> Option { let trimmed = coded_value.trim(); - if let Ok(v) = trimmed.parse::() { - return Some(v); - } + // Try integer parsing first; fall back to float (MDD may store values like "61699.0"). + // The bounds check (`>= 0.0` and `<= u64::MAX as f64`) ensures the value fits before + // the narrowing cast. DIDs are 16-bit so precision loss from f64 never occurs in practice. #[allow( - clippy::cast_precision_loss, - clippy::cast_possible_truncation, - clippy::cast_sign_loss + clippy::cast_precision_loss, // u64::MAX as f64 is safe for the upper-bound comparison + clippy::cast_possible_truncation, // guarded by the bounds check above + clippy::cast_sign_loss // guarded by the `>= 0.0` check above )] - if let Ok(v) = trimmed.parse::() - && v >= 0.0 - && v <= u64::MAX as f64 - { - return Some(v as u64); - } - None + trimmed.parse::().ok().or_else(|| { + let v = trimmed.parse::().ok()?; + (v >= 0.0 && v <= u64::MAX as f64).then_some(v as u64) + }) } /// Find the MUX case prefix that covers a given DID in response metadata. @@ -260,19 +257,14 @@ pub(super) fn encode_value_at( size: usize, value: Option<&serde_json::Value>, ) { - if size == 0 { - return; - } - let Some(end) = pos.checked_add(size) else { - return; - }; - if end > buf.len() { - return; - } - let Some(value) = value else { - // No value provided โ€” leave as zero (already initialised). + let (Some(value), Some(end)) = ( + value, + pos.checked_add(size) + .filter(|&e| size > 0 && e <= buf.len()), + ) else { return; }; + match value { serde_json::Value::Number(n) => { let raw = n From 7d6e2bf002d90df2ee46edb4502d94555ff7ba20 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 28 Apr 2026 10:46:06 +0200 Subject: [PATCH 08/33] Fix: svg images fixed Signed-off-by: Arvind Rathod --- docs/ServiceResolver_Sequence_Diagram.svg | 4 ---- docs/service_resolver_class.svg | 4 ---- 2 files changed, 8 deletions(-) diff --git a/docs/ServiceResolver_Sequence_Diagram.svg b/docs/ServiceResolver_Sequence_Diagram.svg index 461ce4d..18f8887 100644 --- a/docs/ServiceResolver_Sequence_Diagram.svg +++ b/docs/ServiceResolver_Sequence_Diagram.svg @@ -1,5 +1 @@ - ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(resolve.rs)ServiceResolver(resolve.rs)ServiceResolver(metadata.rs)ServiceResolver(metadata.rs)ServiceResolver(response.rs)ServiceResolver(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve_read_service(did, uds_bytes)resolve_service(SID=0x22, did, uds_bytes)resolve_service_did()Step 1-2: Prefix lookup& candidate buildinglookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching servicesbuild_did_candidates()Fast path: single matchelse: enumerate SID-matchingservices via get_components_data_info()match_candidate_did()Step 3: Metadata matchingCodedConst / PhysConst / Value DIDsget_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)Exact match against DID[PhysConst DID]probe_service_did() (optional)Encode dummy request,extract DID from payloadcreate_uds_payload()encoded payloadextract_did_from_uds()[Value DID]did_matches_compu_scales()Range/list matching via MDD CompuScaleconvert_request_from_uds()parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesusing SID=0x2E andget_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)encode_response_from_metadata()get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutOpaque heuristic:Single VALUE with byte_size=Noneand no '/' in name?alt[opaque STRUCTURE detected]get_components_data_info()READ service componentshas_mux_case_for_did_exact(sibling_meta, did)Exact match — avoidscross-DOP false positives(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)mux_case_prefix = find_mux_case_prefix(meta, did)Floor-based matchingfor MUX case active paramsfilter active params by mux_case_prefixSelect top-level params +case-specific sub-paramsalt[metadata available]for each active param:encode_value_at(buf, pos, size, value)CodedConst -> fixed bytesMatchingRequestParam -> DID bytesValue -> encode_value_at()(encoded_bytes, effective_service)[no metadata (fallback)]naive encoding via value_to_bytes()Iterate response_dataString/Number/Array/Boolno MDD structurealt[DEBUG enabled]validate_response()convert_from_uds()JSONRound-trip validation:warn on mismatch, never blocksResult<Vec<u8>, DiagServiceError>  Module Layout (impl ServiceResolver): -resolve.rs: DID -> service resolution,candidate building, metadata matching-response.rs: UDS response encoding,round-trip validation (debug only)-metadata.rs: MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure utilities —encoding, decoding, MUX matching Resolution Algorithm (resolve.rs):1. Prefix lookup [SID, DID_HI, DID_LO]2. Fast path: single prefix match -> return3. Enumerate all SID-matching services4. Match via CodedConst / PhysConst / Value5. Parse request params inline via CDA diff --git a/docs/service_resolver_class.svg b/docs/service_resolver_class.svg index c920c08..7f425b4 100644 --- a/docs/service_resolver_class.svg +++ b/docs/service_resolver_class.svg @@ -1,5 +1 @@ - Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)ServiceResolver-manager : Arc<RwLock<CdaEcuManager>>-ecu_name : String+new(ecu_name, db, logical, tester) : Result<Self>+ecu_name() : &str+is_negative_response(uds) : bool+get_nrc(uds) : Option<u8>mod.rs — construction & UDS helpers+«async» resolve_read_service(did, uds) : Option<ResolvedService>+«async» resolve_write_service(did, uds) : Option<ResolvedService>resolve.rs — DID --> service name+«async» build_response(name, sid, did, data) : Result<Vec<u8>>response.rs — encode UDS response+«async» get_service_parameter_metadata(name) : Result<Vec<Param>>+«async» get_response_parameter_metadata(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs — MDD parameter queries Service resolution algorithm (resolve.rs):1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:• CodedConst — exact DID value match• PhysConst — coded_value or create_uds_payload probe• Value — coded_default or CompuScale range match4. No match --> log error, return None (no fallback) Response encoding (response.rs):Walk MDD POS-RESPONSE parameters:• CODED-CONST --> fixed byte (e.g. response SID 0x62)• MatchingRequestParam --> echo DID bytes from request• VALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookup.«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rsand used by proxy-sovd for MUX matching.«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(service)+create_uds_payload(service, params)+convert_from_uds(service, bytes)+convert_request_from_uds(service, bytes)+detect_variant()CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>«struct»ResolvedService+name : String+params : Mapusesowns via Arc<RwLock>(shared with callers)Async RwLock allows concurrentread access across Tokio tasks. From edf6c998474d45ab1818c8c20a7049c917621fc8 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Wed, 29 Apr 2026 06:44:33 +0200 Subject: [PATCH 09/33] Refactoe: service_resolver mod into subcompoents Signed-off-by: Arvind Rathod --- Cargo.lock | 12 +- Cargo.toml | 8 +- docs/ServiceResolver_Sequence_Diagram.svg | 1 - docs/service_resolver_class.svg | 1 - ...ml => service_resolver_class_diagram.puml} | 140 ++++++--- docs/service_resolver_class_diagram.svg | 1 + ...ervice_resolver_class_diagram.svg.license} | 0 docs/service_resolver_sequence.puml | 158 ---------- docs/service_resolver_sequence_diagram.puml | 177 +++++++++++ docs/service_resolver_sequence_diagram.svg | 1 + ...ice_resolver_sequence_diagram.svg.license} | 0 proxy-core/src/error.rs | 8 + proxy-core/src/lib.rs | 4 +- proxy-core/src/service_resolver/metadata.rs | 82 +++--- proxy-core/src/service_resolver/mod.rs | 172 +++++------ proxy-core/src/service_resolver/resolve.rs | 276 +++++++++--------- proxy-core/src/service_resolver/response.rs | 161 +++++----- .../src/service_resolver/uds_helpers.rs | 20 +- 18 files changed, 632 insertions(+), 590 deletions(-) delete mode 100644 docs/ServiceResolver_Sequence_Diagram.svg delete mode 100644 docs/service_resolver_class.svg rename docs/{service_resolver_class.puml => service_resolver_class_diagram.puml} (51%) create mode 100644 docs/service_resolver_class_diagram.svg rename docs/{ServiceResolver_Sequence_Diagram.svg.license => service_resolver_class_diagram.svg.license} (100%) delete mode 100644 docs/service_resolver_sequence.puml create mode 100644 docs/service_resolver_sequence_diagram.puml create mode 100644 docs/service_resolver_sequence_diagram.svg rename docs/{service_resolver_class.svg.license => service_resolver_sequence_diagram.svg.license} (100%) diff --git a/Cargo.lock b/Cargo.lock index e273f79..322ab65 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -206,7 +206,7 @@ dependencies = [ [[package]] name = "cda-build" version = "0.1.0" -source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" dependencies = [ "rustversion", ] @@ -214,7 +214,7 @@ dependencies = [ [[package]] name = "cda-core" version = "0.1.0" -source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" dependencies = [ "cda-database", "cda-interfaces", @@ -231,7 +231,7 @@ dependencies = [ [[package]] name = "cda-database" version = "0.1.0" -source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" dependencies = [ "bytes", "cargo_toml", @@ -255,7 +255,7 @@ dependencies = [ [[package]] name = "cda-interfaces" version = "0.1.0" -source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" dependencies = [ "async-trait", "bytes", @@ -275,7 +275,7 @@ dependencies = [ [[package]] name = "cda-plugin-security" version = "0.1.0" -source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" dependencies = [ "aide", "async-trait", @@ -1721,7 +1721,7 @@ dependencies = [ [[package]] name = "sovd-interfaces" version = "0.1.0" -source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=ed58d5f9524f483c3f9409a1a79a12ab8261568c#ed58d5f9524f483c3f9409a1a79a12ab8261568c" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" dependencies = [ "cda-interfaces", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 4f247af..b74d56a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,10 +22,10 @@ members = ["proxy-core"] proxy-core = { path = "proxy-core" } proxy-doip = { path = "proxy-doip" } proxy-sovd = { path = "proxy-sovd" } -cda-core = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } -cda-database = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } -cda-interfaces = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } -cda-plugin-security = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "ed58d5f9524f483c3f9409a1a79a12ab8261568c" } +cda-core = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" } +cda-database = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" } +cda-interfaces = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" } +cda-plugin-security = { git = "https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git", rev = "cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" } # ---- common crates ---- async-trait = "0.1.89" diff --git a/docs/ServiceResolver_Sequence_Diagram.svg b/docs/ServiceResolver_Sequence_Diagram.svg deleted file mode 100644 index 18f8887..0000000 --- a/docs/ServiceResolver_Sequence_Diagram.svg +++ /dev/null @@ -1 +0,0 @@ -ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(resolve.rs)ServiceResolver(resolve.rs)ServiceResolver(metadata.rs)ServiceResolver(metadata.rs)ServiceResolver(response.rs)ServiceResolver(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve_read_service(did, uds_bytes)resolve_service(SID=0x22, did, uds_bytes)resolve_service_did()Step 1-2: Prefix lookup& candidate buildinglookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching servicesbuild_did_candidates()Fast path: single matchelse: enumerate SID-matchingservices via get_components_data_info()match_candidate_did()Step 3: Metadata matchingCodedConst / PhysConst / Value DIDsget_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)Exact match against DID[PhysConst DID]probe_service_did() (optional)Encode dummy request,extract DID from payloadcreate_uds_payload()encoded payloadextract_did_from_uds()[Value DID]did_matches_compu_scales()Range/list matching via MDD CompuScaleconvert_request_from_uds()parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesusing SID=0x2E andget_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)encode_response_from_metadata()get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutOpaque heuristic:Single VALUE with byte_size=Noneand no '/' in name?alt[opaque STRUCTURE detected]get_components_data_info()READ service componentshas_mux_case_for_did_exact(sibling_meta, did)Exact match — avoidscross-DOP false positives(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)mux_case_prefix = find_mux_case_prefix(meta, did)Floor-based matchingfor MUX case active paramsfilter active params by mux_case_prefixSelect top-level params +case-specific sub-paramsalt[metadata available]for each active param:encode_value_at(buf, pos, size, value)CodedConst -> fixed bytesMatchingRequestParam -> DID bytesValue -> encode_value_at()(encoded_bytes, effective_service)[no metadata (fallback)]naive encoding via value_to_bytes()Iterate response_dataString/Number/Array/Boolno MDD structurealt[DEBUG enabled]validate_response()convert_from_uds()JSONRound-trip validation:warn on mismatch, never blocksResult<Vec<u8>, DiagServiceError>  Module Layout (impl ServiceResolver): -resolve.rs: DID -> service resolution,candidate building, metadata matching-response.rs: UDS response encoding,round-trip validation (debug only)-metadata.rs: MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure utilities —encoding, decoding, MUX matching Resolution Algorithm (resolve.rs):1. Prefix lookup [SID, DID_HI, DID_LO]2. Fast path: single prefix match -> return3. Enumerate all SID-matching services4. Match via CodedConst / PhysConst / Value5. Parse request params inline via CDA diff --git a/docs/service_resolver_class.svg b/docs/service_resolver_class.svg deleted file mode 100644 index 7f425b4..0000000 --- a/docs/service_resolver_class.svg +++ /dev/null @@ -1 +0,0 @@ -Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)ServiceResolver-manager : Arc<RwLock<CdaEcuManager>>-ecu_name : String+new(ecu_name, db, logical, tester) : Result<Self>+ecu_name() : &str+is_negative_response(uds) : bool+get_nrc(uds) : Option<u8>mod.rs — construction & UDS helpers+«async» resolve_read_service(did, uds) : Option<ResolvedService>+«async» resolve_write_service(did, uds) : Option<ResolvedService>resolve.rs — DID --> service name+«async» build_response(name, sid, did, data) : Result<Vec<u8>>response.rs — encode UDS response+«async» get_service_parameter_metadata(name) : Result<Vec<Param>>+«async» get_response_parameter_metadata(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs — MDD parameter queries Service resolution algorithm (resolve.rs):1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:• CodedConst — exact DID value match• PhysConst — coded_value or create_uds_payload probe• Value — coded_default or CompuScale range match4. No match --> log error, return None (no fallback) Response encoding (response.rs):Walk MDD POS-RESPONSE parameters:• CODED-CONST --> fixed byte (e.g. response SID 0x62)• MatchingRequestParam --> echo DID bytes from request• VALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookup.«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rsand used by proxy-sovd for MUX matching.«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(service)+create_uds_payload(service, params)+convert_from_uds(service, bytes)+convert_request_from_uds(service, bytes)+detect_variant()CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>«struct»ResolvedService+name : String+params : Mapusesowns via Arc<RwLock>(shared with callers)Async RwLock allows concurrentread access across Tokio tasks. diff --git a/docs/service_resolver_class.puml b/docs/service_resolver_class_diagram.puml similarity index 51% rename from docs/service_resolver_class.puml rename to docs/service_resolver_class_diagram.puml index e53cd0f..df6f7fa 100644 --- a/docs/service_resolver_class.puml +++ b/docs/service_resolver_class_diagram.puml @@ -19,60 +19,98 @@ skinparam classFontSize 12 ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ' proxy-core::service_resolver -' One struct (ServiceResolver) whose impl blocks are split across -' four source files for readability. uds_helpers is a separate -' module of free (non-method) functions. +' Facade (ServiceResolver) owns CdaEcuManager and ecu_name, exposes +' sub-component accessors. Each sub-component is a focused struct: +' DidResolver (resolve.rs) -- DID-to-service resolution +' ResponseEncoder (response.rs) -- UDS response encoding +' MetadataProvider (metadata.rs) -- MDD parameter queries +' uds_helpers.rs holds free functions and the UdsResponse type. ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ package "proxy-core::service_resolver" { - class ServiceResolver { - - manager : Arc> + class ServiceResolver <> { + - manager : CdaEcuManager - ecu_name : String - == mod.rs โ€” construction & UDS helpers == - + {static} new(ecu_name, db, logical, tester) : Result + == mod.rs -- construction & accessors == + + {static} <> new(ecu_name, db, logical, tester) : Result + - {static} <> activate_base_variant(manager) : Result<()> + - {static} default_com_params(logical, tester: u16) : ComParams + ecu_name() : &str - + {static} is_negative_response(uds) : bool - + {static} get_nrc(uds) : Option - == resolve.rs โ€” DID --> service name == - + <> resolve_read_service(did, uds) : Option - + <> resolve_write_service(did, uds) : Option - == response.rs โ€” encode UDS response == - + <> build_response(name, sid, did, data) : Result> - == metadata.rs โ€” MDD parameter queries == - + <> get_service_parameter_metadata(name) : Result> - + <> get_response_parameter_metadata(name) : Result> - + <> get_enriched_response_metadata(name, did) : Result> - + <> lookup_service_names_by_sid(sid) : Result> - + <> get_mux_cases_for_service(name) : Result> + + did_resolver() : DidResolver + + response_encoder() : ResponseEncoder + + metadata() : MetadataProvider } - note right of ServiceResolver + together { + class DidResolver { + - manager : CdaEcuManager + == resolve.rs -- DID --> service name == + + <> resolve_read_service(did, uds) : Option + + <> resolve_write_service(did, uds) : Option + - <> resolve_service(sid, did, uds, label) : Option + - <> resolve_service_did(sid, did, ...) : Option + - {static} build_did_candidates(manager, prefix, sid, did) : Option> + - <> match_candidate_did(manager, name, sid, did) : bool + - {static} <> probe_service_did(manager, name, sid, meta) : Option + } + + class ResponseEncoder { + - manager : CdaEcuManager + - metadata : MetadataProvider + == response.rs -- encode UDS response == + + <> build_response(name, sid, did, data) : Result> + - <> encode_response_from_metadata(name, sid, did, data) : Option<(Vec, String)> + - <> validate_response(name, sid, bytes) : () + } + + class MetadataProvider { + - manager : CdaEcuManager + == metadata.rs -- MDD parameter queries == + + <> get_service_parameter_metadata(name) : Result> + + <> get_response_parameter_metadata(name) : Result> + + <> get_enriched_response_metadata(name, did) : Result> + + <> get_enriched_response_metadata_with_source(name, did) : Result<(Vec, String)> + + <> lookup_service_names_by_sid(sid) : Result> + + <> get_mux_cases_for_service(name) : Result> + } + } + + note right of DidResolver - Service resolution algorithm (resolve.rs): + Resolution algorithm: 1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO]) 2. Single match --> service name found (fast path) 3. Multiple candidates --> inspect request parameter metadata: - โ€ข CodedConst โ€” exact DID value match - โ€ข PhysConst โ€” coded_value or create_uds_payload probe - โ€ข Value โ€” coded_default or CompuScale range match + * CodedConst -- exact DID value match + * PhysConst -- coded_value or create_uds_payload probe + * Value -- coded_default or CompuScale range match 4. No match --> log error, return None (no fallback) + end note - Response encoding (response.rs): + note right of ResponseEncoder + Response encoding: Walk MDD POS-RESPONSE parameters: - โ€ข CODED-CONST --> fixed byte (e.g. response SID 0x62) - โ€ข MatchingRequestParam --> echo DID bytes from request - โ€ข VALUE --> SOVD JSON value at MDD-defined offset - Opaque STRUCTURE types trigger MUX sibling lookup. + * CODED-CONST --> fixed byte (e.g. response SID 0x62) + * MatchingRequestParam --> echo DID bytes from request + * VALUE --> SOVD JSON value at MDD-defined offset + Opaque STRUCTURE types trigger MUX sibling lookup + via MetadataProvider.get_enriched_response_metadata_with_source(). end note class uds_helpers <> { - ' โ”€โ”€ pub re-exports (used by proxy-sovd) โ”€โ”€ + ' -- pub re-exports (used by proxy-sovd) -- + parse_mux_coded_value(coded) : Option + find_mux_case_prefix(meta, did) : Option + has_mux_case_for_did_exact(meta, did) : bool + == UdsResponse == + + UdsResponse::new(bytes) : UdsResponse + + UdsResponse::sid() : Option + + UdsResponse::is_negative() : bool + + UdsResponse::nrc() : Option == internal helpers == ~ extract_did_from_uds(data) : Option ~ diag_comm_type(sid) : DiagCommType + ~ make_diag_comm(name, sid) : DiagComm ~ make_service_payload(data) : ServicePayload ~ encode_unsigned_be(num) : Vec ~ parse_u64_literal(value) : Option @@ -83,11 +121,22 @@ package "proxy-core::service_resolver" { } note bottom of uds_helpers - Top 3 are pub re-exported from mod.rs - and used by proxy-sovd for MUX matching. + Top 3 + UdsResponse are pub re-exported + from mod.rs and used by proxy-sovd. end note - ServiceResolver ..> uds_helpers : uses + class ResolvedService <> { + + name : String + + params : Map + } + + ServiceResolver --> DidResolver : did_resolver() + ServiceResolver --> ResponseEncoder : response_encoder() + ServiceResolver --> MetadataProvider : metadata() + ResponseEncoder o--> MetadataProvider : holds (explicit dependency) + DidResolver ..> uds_helpers : uses + ResponseEncoder ..> uds_helpers : uses + DidResolver ..> ResolvedService : returns } ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -101,13 +150,15 @@ package "cda-core (external path dep)" #LightGray { + get_request_parameter_metadata(service) ' โ€” response building โ€” + get_response_parameter_metadata(service) - + get_components_data_info(service) + + get_components_data_info(plugin) + + get_components_configurations_info(plugin) + + get_mux_cases_for_service(service) ' โ€” encoding / decoding โ€” - + create_uds_payload(service, params) - + convert_from_uds(service, bytes) - + convert_request_from_uds(service, bytes) + + create_uds_payload(service, plugin, params) + + convert_from_uds(service, payload, true) + + convert_request_from_uds(service, payload, true) ' โ€” variant selection โ€” - + detect_variant() + + detect_variant(responses) } class "CdaEcuManager\n" as CdaEcuManager { @@ -120,7 +171,6 @@ package "cda-core (external path dep)" #LightGray { ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ' proxy-core public API consumed by proxy-sovd / proxy-doip -' DiagHandler trait removed โ€” no abstraction needed with one impl. ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ package "proxy-core (public API)" #LightYellow { @@ -132,11 +182,6 @@ package "proxy-core (public API)" #LightYellow { -- + {static} from_file(path) : Result } - - class ResolvedService <> { - + name : String - + params : Map - } } ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -145,8 +190,9 @@ package "proxy-core (public API)" #LightYellow { ServiceResolver *--> CdaEcuManager : owns via Arc\n(shared with callers) note on link - Async RwLock allows concurrent - read access across Tokio tasks. + CdaEcuManager = Arc>>. + Each sub-component receives an Arc::clone + to allow concurrent async read access. end note @enduml diff --git a/docs/service_resolver_class_diagram.svg b/docs/service_resolver_class_diagram.svg new file mode 100644 index 0000000..1e71cba --- /dev/null +++ b/docs/service_resolver_class_diagram.svg @@ -0,0 +1 @@ +Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-ecu_name : String+«async» new(ecu_name, db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParams+ecu_name() : &str+did_resolver() : DidResolver+response_encoder() : ResponseEncoder+metadata() : MetadataProvidermod.rs -- construction & accessorsDidResolver-manager : CdaEcuManager+«async» resolve_read_service(did, uds) : Option<ResolvedService>+«async» resolve_write_service(did, uds) : Option<ResolvedService>-«async» resolve_service(sid, did, uds, label) : Option<ResolvedService>-«async» resolve_service_did(sid, did, ...) : Option<String>-build_did_candidates(manager, prefix, sid, did) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service nameResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider+«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS responseMetadataProvider-manager : CdaEcuManager+«async» get_service_parameter_metadata(name) : Result<Vec<Param>>+«async» get_response_parameter_metadata(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool+UdsResponse::new(bytes) : UdsResponse+UdsResponse::sid() : Option<u8>+UdsResponse::is_negative() : bool+UdsResponse::nrc() : Option<u8>UdsResponse~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 + UdsResponse are pub re-exportedfrom mod.rs and used by proxy-sovd.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>did_resolver()response_encoder()metadata()holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. diff --git a/docs/ServiceResolver_Sequence_Diagram.svg.license b/docs/service_resolver_class_diagram.svg.license similarity index 100% rename from docs/ServiceResolver_Sequence_Diagram.svg.license rename to docs/service_resolver_class_diagram.svg.license diff --git a/docs/service_resolver_sequence.puml b/docs/service_resolver_sequence.puml deleted file mode 100644 index df2a2c6..0000000 --- a/docs/service_resolver_sequence.puml +++ /dev/null @@ -1,158 +0,0 @@ -' SPDX-License-Identifier: Apache-2.0 -' SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) -' -' See the NOTICE file(s) distributed with this work for additional -' information regarding copyright ownership. -' -' This program and the accompanying materials are made available under the -' terms of the Apache License Version 2.0 which is available at -' https://www.apache.org/licenses/LICENSE-2.0 - -@startuml ServiceResolver Sequence Diagram - -title ServiceResolver: DID Resolution & Response Building\nEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd) - -actor "SovdDiagHandler\n(proxy-sovd)" as Client -participant "ServiceResolver\n(resolve.rs)" as Resolver -participant "ServiceResolver\n(metadata.rs)" as Meta -participant "ServiceResolver\n(response.rs)" as Resp -participant "CDA EcuManager" as CDA - -== READ Service Resolution == - -Client -> Resolver: resolve_read_service(did, uds_bytes) -activate Resolver - -Resolver -> Resolver: resolve_service(SID=0x22, did, uds_bytes) - -Resolver -> Resolver: resolve_service_did() -note right: Step 1-2: Prefix lookup\n& candidate building - -Resolver -> CDA: lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO]) -activate CDA -CDA --> Resolver: matching services -deactivate CDA - -Resolver -> Resolver: build_did_candidates() -note right: Fast path: single match\nelse: enumerate SID-matching\nservices via get_components_data_info() - -Resolver -> Resolver: match_candidate_did() -note right: Step 3: Metadata matching\nCodedConst / PhysConst / Value DIDs - -Resolver -> CDA: get_request_parameter_metadata(candidate_name) -activate CDA -CDA --> Resolver: param metadata -deactivate CDA - -alt CodedConst DID - Resolver -> Resolver: parse_u64_literal(coded_value) - note right: Exact match against DID -else PhysConst DID - Resolver -> Resolver: probe_service_did() (optional) - note right: Encode dummy request,\nextract DID from payload - Resolver -> CDA: create_uds_payload() - activate CDA - CDA --> Resolver: encoded payload - deactivate CDA - Resolver -> Resolver: extract_did_from_uds() -else Value DID - Resolver -> Resolver: did_matches_compu_scales() - note right: Range/list matching via MDD CompuScale -end - -Resolver -> CDA: convert_request_from_uds() -activate CDA -CDA --> Resolver: parsed JSON params -deactivate CDA - -Resolver --> Client: Option -deactivate Resolver - -== WRITE Service Handling == - -note right of Client: Similar flow for WRITE services\nusing SID=0x2E and\nget_components_configurations_info() - -== Response Building == - -Client -> Resp: build_response(service_name, sid, did, response_data) -activate Resp - -Resp -> Resp: encode_response_from_metadata() - -Resp -> Meta: get_enriched_response_metadata_with_source(service_name, did) -activate Meta - -Meta -> CDA: get_response_parameter_metadata(service_name) -activate CDA -CDA --> Meta: response param layout -deactivate CDA - -note right of Meta: Opaque heuristic:\nSingle VALUE with byte_size=None\nand no '/' in name? - -alt opaque STRUCTURE detected - Meta -> CDA: get_components_data_info() - activate CDA - CDA --> Meta: READ service components - deactivate CDA - - Meta -> Meta: has_mux_case_for_did_exact(sibling_meta, did) - note right: Exact match โ€” avoids\ncross-DOP false positives - - Meta --> Resp: (enriched_meta, sibling_service_name) -else standard response - Meta --> Resp: (base_meta, service_name) -end - -deactivate Meta - -Resp -> Resp: mux_case_prefix = find_mux_case_prefix(meta, did) -note right: Floor-based matching\nfor MUX case active params - -Resp -> Resp: filter active params by mux_case_prefix -note right: Select top-level params +\ncase-specific sub-params - -alt metadata available - Resp -> Resp: for each active param: - Resp -> Resp: encode_value_at(buf, pos, size, value) - note right: CodedConst -> fixed bytes\nMatchingRequestParam -> DID bytes\nValue -> encode_value_at() - Resp --> Resp: (encoded_bytes, effective_service) -else no metadata (fallback) - Resp -> Resp: naive encoding via value_to_bytes() - note right: Iterate response_data\nString/Number/Array/Bool\nno MDD structure -end - -alt DEBUG enabled - Resp -> Resp: validate_response() - Resp -> CDA: convert_from_uds() - activate CDA - CDA --> Resp: JSON - deactivate CDA - note right: Round-trip validation:\nwarn on mismatch, never blocks -end - -Resp --> Client: Result, DiagServiceError> -deactivate Resp - -note right of Client - - - **Module Layout (impl ServiceResolver):** - - - **resolve.rs**: DID -> service resolution, - candidate building, metadata matching - - **response.rs**: UDS response encoding, - round-trip validation (debug only) - - **metadata.rs**: MDD metadata queries, - MUX sibling enrichment - - **uds_helpers.rs**: Pure utilities โ€” - encoding, decoding, MUX matching - - **Resolution Algorithm (resolve.rs):** - 1. Prefix lookup [SID, DID_HI, DID_LO] - 2. Fast path: single prefix match -> return - 3. Enumerate all SID-matching services - 4. Match via CodedConst / PhysConst / Value - 5. Parse request params inline via CDA -end note - -@enduml diff --git a/docs/service_resolver_sequence_diagram.puml b/docs/service_resolver_sequence_diagram.puml new file mode 100644 index 0000000..0ffc744 --- /dev/null +++ b/docs/service_resolver_sequence_diagram.puml @@ -0,0 +1,177 @@ +' SPDX-License-Identifier: Apache-2.0 +' SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +' +' See the NOTICE file(s) distributed with this work for additional +' information regarding copyright ownership. +' +' This program and the accompanying materials are made available under the +' terms of the Apache License Version 2.0 which is available at +' https://www.apache.org/licenses/LICENSE-2.0 + +@startuml ServiceResolver Sequence Diagram + +title ServiceResolver: DID Resolution & Response Building\nEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd) + +actor "SovdDiagHandler\n(proxy-sovd)" as Client +participant "ServiceResolver\n(mod.rs facade)" as Facade +participant "DidResolver\n(resolve.rs)" as Resolver +participant "MetadataProvider\n(metadata.rs)" as Meta +participant "ResponseEncoder\n(response.rs)" as Resp +participant "CDA EcuManager" as CDA + +== READ Service Resolution == + +Client -> Facade: did_resolver() +Facade --> Client: DidResolver + +Client -> Resolver: resolve_read_service(did, uds_bytes) +activate Resolver + +Resolver -> Resolver: resolve_service(SID=0x22, did, uds_bytes, "READ") +activate Resolver + + Resolver -> Resolver: resolve_service_did(sid, did, uds_bytes, "READ") + activate Resolver + + Resolver -> CDA: lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO]) + activate CDA + CDA --> Resolver: matching_services + deactivate CDA + + Resolver -> Resolver: build_did_candidates(manager, prefix, sid, did) + activate Resolver + Resolver -> CDA: get_components_data_info() or\nget_components_configurations_info() + activate CDA + CDA --> Resolver: all SID-matching service names + deactivate CDA + deactivate Resolver + + loop for each candidate service name + Resolver -> Resolver: match_candidate_did(manager, name, sid, did) + activate Resolver + + Resolver -> CDA: get_request_parameter_metadata(candidate_name) + activate CDA + CDA --> Resolver: param metadata + deactivate CDA + + alt CodedConst DID + Resolver -> Resolver: parse_u64_literal(coded_value) + else PhysConst DID (coded_value absent) + Resolver -> Resolver: probe_service_did(manager, name, sid, meta) + activate Resolver + Resolver -> CDA: create_uds_payload(diag_comm, plugin, params) + activate CDA + CDA --> Resolver: encoded payload + deactivate CDA + Resolver -> Resolver: extract_did_from_uds(payload.data) + deactivate Resolver + else Value DID + Resolver -> Resolver: did_matches_compu_scales(scales, did) + end + + deactivate Resolver + end + + deactivate Resolver + + Resolver -> CDA: convert_request_from_uds(diag_comm, payload, strict=true) + activate CDA + CDA --> Resolver: parsed JSON params + deactivate CDA + +deactivate Resolver + +Resolver --> Client: Option +deactivate Resolver + +== WRITE Service Handling == + +note right of Client: Similar flow for WRITE services\nusing SID=0x2E and\nget_components_configurations_info()\nClient calls facade.did_resolver()\nthen resolver.resolve_write_service() + +== Response Building == + +Client -> Facade: response_encoder() +Facade --> Client: ResponseEncoder + +Client -> Resp: build_response(service_name, sid, did, response_data) +activate Resp + + Resp -> Resp: encode_response_from_metadata(service_name, sid, did, data) + activate Resp + + Resp -> Meta: get_enriched_response_metadata_with_source(service_name, did) + activate Meta + + Meta -> CDA: get_response_parameter_metadata(service_name) + activate CDA + CDA --> Meta: response param layout + deactivate CDA + + alt opaque STRUCTURE detected + Meta -> CDA: get_components_data_info() + activate CDA + CDA --> Meta: READ service components + deactivate CDA + + loop for each sibling candidate + Meta -> CDA: get_response_parameter_metadata(candidate) + activate CDA + CDA --> Meta: sibling response layout + deactivate CDA + Meta -> Meta: has_mux_case_for_did_exact(sibling_meta, did) + end + + Meta --> Resp: (enriched_meta, sibling_service_name) + else standard response + Meta --> Resp: (base_meta, service_name) + end + + deactivate Meta + + Resp -> Resp: find_mux_case_prefix(meta, did) + Resp -> Resp: filter active params by mux_case_prefix + Resp -> Resp: for each active param: encode at byte_position + + deactivate Resp + +alt encode_response_from_metadata returned Some +else no metadata available (fallback) + Resp -> Resp: naive encoding via value_to_bytes() +end + +alt DEBUG level enabled + Resp -> Resp: validate_response(effective_service, sid, bytes) + activate Resp + Resp -> CDA: convert_from_uds(diag_comm, payload, strict=true) + activate CDA + CDA --> Resp: JSON + deactivate CDA + note right: Round-trip validation + deactivate Resp +end + +Resp --> Client: Result, DiagServiceError> +deactivate Resp + +note right of Client + + - **ServiceResolver (mod.rs)**: Facade -- construction, + variant activation, sub-component accessors + - **DidResolver (resolve.rs)**: DID -> service resolution, + candidate building, metadata matching + - **ResponseEncoder (response.rs)**: UDS response encoding, + round-trip validation (debug only) + - **MetadataProvider (metadata.rs)**: MDD metadata queries, + MUX sibling enrichment + - **uds_helpers.rs**: Pure utilities + UdsResponse -- + encoding, decoding, MUX matching + + **Data flow:** + Caller gets sub-component via accessor, then calls + methods directly on that sub-component. + ResponseEncoder holds MetadataProvider internally + for the cross-module enrichment dependency. +end note + +@enduml diff --git a/docs/service_resolver_sequence_diagram.svg b/docs/service_resolver_sequence_diagram.svg new file mode 100644 index 0000000..0f80d69 --- /dev/null +++ b/docs/service_resolver_sequence_diagram.svg @@ -0,0 +1 @@ +ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs facade)ServiceResolver(mod.rs facade)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutiondid_resolver()DidResolverresolve_read_service(did, uds_bytes)resolve_service(SID=0x22, did, uds_bytes, "READ")resolve_service_did(sid, did, uds_bytes, "READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, prefix, sid, did)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesusing SID=0x2E andget_components_configurations_info()Client calls facade.did_resolver()then resolver.resolve_write_service()Response Buildingresponse_encoder()ResponseEncoderbuild_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): Facade -- construction,variant activation, sub-component accessors-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure utilities + UdsResponse --encoding, decoding, MUX matching Data flow:Caller gets sub-component via accessor, then callsmethods directly on that sub-component.ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. diff --git a/docs/service_resolver_class.svg.license b/docs/service_resolver_sequence_diagram.svg.license similarity index 100% rename from docs/service_resolver_class.svg.license rename to docs/service_resolver_sequence_diagram.svg.license diff --git a/proxy-core/src/error.rs b/proxy-core/src/error.rs index e1c5ae7..0bc5530 100644 --- a/proxy-core/src/error.rs +++ b/proxy-core/src/error.rs @@ -173,6 +173,14 @@ impl Nrc { } } +impl TryFrom for Nrc { + type Error = (); + + fn try_from(value: u8) -> std::result::Result { + Self::from_u8(value).ok_or(()) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/proxy-core/src/lib.rs b/proxy-core/src/lib.rs index c489722..b4d4408 100644 --- a/proxy-core/src/lib.rs +++ b/proxy-core/src/lib.rs @@ -22,4 +22,6 @@ pub mod service_resolver; pub use config::Config; pub use error::{ProxyError, Result}; -pub use service_resolver::{ResolvedService, ServiceResolver}; +pub use service_resolver::{ + DidResolver, MetadataProvider, ResolvedService, ResponseEncoder, ServiceResolver, +}; diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs index 7f6a977..778a377 100644 --- a/proxy-core/src/service_resolver/metadata.rs +++ b/proxy-core/src/service_resolver/metadata.rs @@ -10,23 +10,31 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! Service metadata queries and lookup. -//! -//! Methods for querying request/response parameter metadata from the MDD, -//! looking up services by SID, and retrieving MUX case information. +//! MDD metadata queries for service parameters, response layouts, and MUX cases. use cda_interfaces::{ DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, MuxCaseInfo, ServiceParameterMetadata, service_ids, }; -use super::{ServiceResolver, uds_helpers::has_mux_case_for_did_exact}; +use super::{CdaEcuManager, uds_helpers::has_mux_case_for_did_exact}; -impl ServiceResolver { - /// Retrieve request parameter metadata for a service. +#[derive(Clone)] +pub struct MetadataProvider { + manager: CdaEcuManager, +} + +impl MetadataProvider { + pub(super) fn new(manager: CdaEcuManager) -> Self { + Self { manager } + } + + /// Return the request parameter layout for `service_name`. /// /// # Errors - /// Returns an error if the metadata is not available. + /// + /// Returns `DiagServiceError` when the service is unknown or the MDD + /// does not contain request metadata. pub async fn get_service_parameter_metadata( &self, service_name: &str, @@ -35,10 +43,12 @@ impl ServiceResolver { manager.get_request_parameter_metadata(service_name) } - /// Retrieve POS-RESPONSE parameter metadata (byte positions, sizes, types). + /// Return the POS-RESPONSE parameter layout (byte positions, sizes, types). /// /// # Errors - /// Returns an error if the metadata is not available. + /// + /// Returns `DiagServiceError` when the service is unknown or no response + /// metadata exists. pub async fn get_response_parameter_metadata( &self, service_name: &str, @@ -60,7 +70,8 @@ impl ServiceResolver { /// MUX-based metadata instead, so callers get per-field byte positions. /// /// # Errors - /// Returns an error if the metadata is not available. + /// + /// Returns `DiagServiceError` when the base metadata lookup fails. pub async fn get_enriched_response_metadata( &self, service_name: &str, @@ -71,13 +82,14 @@ impl ServiceResolver { .map(|(meta, _source)| meta) } - /// Lookup all service names for a given UDS service ID (SID). + /// Return all service names registered under a given UDS SID. /// /// Returns READ services for SID 0x22, WRITE services for SID 0x2E, - /// or an empty vector for unrecognized SIDs. + /// or an empty vector for unrecognised SIDs. /// /// # Errors - /// Does not currently return errors; always succeeds with a Vec. + /// + /// Returns `DiagServiceError` when the service name lookup fails. pub async fn lookup_service_names_by_sid( &self, sid: u8, @@ -101,13 +113,15 @@ impl ServiceResolver { Ok(names) } - /// Retrieve MUX case definitions for a given service. + /// Return MUX case definitions for `service_name`. /// /// Queries the MDD for all MUX cases associated with the service, /// used to determine which parameters are active for each MUX value. /// /// # Errors - /// Returns an error if the service is not found or MDD query fails. + /// + /// Returns `DiagServiceError` when the service is unknown or the MDD + /// query fails. pub async fn get_mux_cases_for_service( &self, service_name: &str, @@ -116,17 +130,19 @@ impl ServiceResolver { manager.get_mux_cases_for_service(service_name) } - /// Retrieve enriched POS-RESPONSE metadata with source service name. + /// Retrieve enriched POS-RESPONSE metadata with the source service name. /// - /// Same as [`MetadataQuerying::get_enriched_response_metadata`] but also returns - /// the name of the service that actually provided the metadata. When the response is - /// "opaque" (single STRUCTURE ref) and a MUX-based sibling is used, the - /// returned name is the sibling โ€” callers that need to validate via - /// `convert_from_uds` must use this name, not the original. + /// Same as [`get_enriched_response_metadata`](Self::get_enriched_response_metadata) + /// but also returns the name of the service that actually provided the + /// metadata. When the response is "opaque" (single STRUCTURE ref) and a + /// MUX-based sibling is used, the returned name is the sibling -- callers + /// that need to validate via `convert_from_uds` must use this name, not + /// the original. /// /// # Errors - /// Returns an error if the metadata is not available. - pub(super) async fn get_enriched_response_metadata_with_source( + /// + /// Returns `DiagServiceError` when the base metadata lookup fails. + pub async fn get_enriched_response_metadata_with_source( &self, service_name: &str, did: u16, @@ -134,8 +150,8 @@ impl ServiceResolver { let manager = self.manager.read().await; let meta = manager.get_response_parameter_metadata(service_name)?; - // Heuristic: the response is "opaque" when the only data param - // (after SID + DID) is a single VALUE with byte_size = None. + // Heuristic: the response is "opaque" when the only data param (after + // SID + DID) is a single VALUE with byte_size = None. let data_params: Vec<_> = meta .iter() .filter(|p| { @@ -193,7 +209,7 @@ impl ServiceResolver { } } - // No MUX sibling found โ€” use original metadata. + // No MUX sibling found -- use original metadata. Ok((meta, service_name.to_string())) } } @@ -243,7 +259,7 @@ mod tests { #[test] fn test_has_mux_exact_no_match() { let meta = vec![mux_case("VIN", 0xF190)]; - // 0xF191 is one beyond the only entry โ€” no match. + // 0xF191 is one beyond the only entry -- no match. assert!(!has_mux_case_for_did_exact(&meta, 0xF191)); } @@ -271,12 +287,12 @@ mod tests { #[test] fn test_floor_vs_exact_differ_for_range_case() { let meta = vec![mux_case("RANGE", 0xF100), mux_case("OTHER", 0xF200)]; - // Floor: 0xF103 falls in the 0xF100 range โ†’ prefix returned. + // Floor: 0xF103 falls in the 0xF100 range -> prefix returned. assert_eq!( find_mux_case_prefix(&meta, 0xF103), Some("RANGE/".to_string()) ); - // Exact: 0xF103 has no exact entry โ†’ false. + // Exact: 0xF103 has no exact entry -> false. assert!(!has_mux_case_for_did_exact(&meta, 0xF103)); // But 0xF100 itself is an exact hit. assert!(has_mux_case_for_did_exact(&meta, 0xF100)); @@ -289,7 +305,7 @@ mod tests { #[test] fn test_opaque_heuristic_single_none_size_param() { - // Only one VALUE param with byte_size = None and no '/' in name โ†’ opaque. + // Only one VALUE param with byte_size = None and no '/' in name -> opaque. let param = ResponseParameterInfo { name: "STRUCTURE_DATA".to_string(), semantic: None, @@ -339,7 +355,7 @@ mod tests { #[test] fn test_opaque_heuristic_mux_subparam_not_opaque() { - // A MUX sub-param has '/' in its name โ†’ not opaque even if byte_size is None. + // A MUX sub-param has '/' in its name -> not opaque even if byte_size is None. let param = ResponseParameterInfo { name: "__mux_case__/VIN/DATA".to_string(), semantic: None, @@ -369,7 +385,7 @@ mod tests { #[test] fn test_opaque_heuristic_multiple_params_not_opaque() { - // Multiple VALUE params โ†’ structured layout, NOT opaque. + // Multiple VALUE params -> structured layout, NOT opaque. let params = vec![value_param("FIELD_A", 3, 2), value_param("FIELD_B", 5, 1)]; let data_params: Vec<_> = params .iter() diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs index ab57a33..68eacf5 100644 --- a/proxy-core/src/service_resolver/mod.rs +++ b/proxy-core/src/service_resolver/mod.rs @@ -10,39 +10,14 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! ECU Manager wrapper for MDD-driven UDS request/response processing. +//! MDD-driven UDS encoding, decoding, and service resolution. //! -//! Provides a simplified interface to the CDA's -//! `EcuManager` for encoding/decoding UDS messages using the loaded MDD -//! diagnostic database. +//! `ServiceResolver` is a thin facade that owns the CDA `EcuManager` and +//! exposes three focused sub-components via accessor methods: //! -//! ## Module layout -//! -//! - [`uds_helpers`]: Pure helper functions for UDS encoding, decoding, MUX -//! matching, and payload construction. -//! - [`response`]: UDS response building and round-trip validation. -//! - [`metadata`]: Service metadata queries and MUX-sibling enrichment. -//! - [`resolve`]: DID-to-service resolution, request parsing, and probing. -//! -//! ## Service resolution -//! -//! When a UDS request arrives the proxy must identify which diagnostic service -//! from the MDD it belongs to (e.g. `WDBI_VIN` vs `WDBI_PLAIN` for SID 0x2E). -//! -//! Resolution uses `lookup_diagcomms_by_request_prefix` with the full -//! `[SID, DID_HI, DID_LO]` prefix, which directly matches services whose -//! sequential coded-const parameters match the request bytes. This handles -//! CODED-CONST DID services in a single call. -//! -//! For services where the DID is not a coded constant (`PhysConst` / Value), -//! the prefix lookup returns all SID-matching services and the resolver -//! confirms the DID via request parameter metadata: -//! -//! - **`CodedConst`**: exact DID match. -//! - **`PhysConst`**: resolved `coded_value` or `create_uds_payload` probe. -//! - **Value**: `coded_default_value` or `CompuScale` range match. -//! -//! If no service matches, an error is logged โ€” no fallback. +//! - [`DidResolver`] -- DID-to-service resolution +//! - [`ResponseEncoder`] -- UDS response encoding +//! - [`MetadataProvider`] -- MDD parameter queries mod metadata; mod resolve; @@ -51,7 +26,7 @@ pub mod uds_helpers; use std::sync::Arc; -use cda_core::{DiagServiceResponseStruct, EcuManager as CdaEcuManager}; +use cda_core::{DiagServiceResponseStruct, EcuManager}; use cda_database::datatypes::DiagnosticDatabase; use cda_interfaces::{ DiagComm, DiagCommType, DiagServiceError, EcuManager as EcuManagerTrait, EcuManagerType, @@ -60,49 +35,35 @@ use cda_interfaces::{ diagservices::DiagServiceResponseType, }; use cda_plugin_security::DefaultSecurityPluginData; +pub use metadata::MetadataProvider; +pub use resolve::{DidResolver, ResolvedService}; +pub use response::ResponseEncoder; use tokio::sync::RwLock; pub use uds_helpers::{ UdsResponse, find_mux_case_prefix, has_mux_case_for_did_exact, parse_mux_coded_value, }; +pub(crate) type CdaEcuManager = Arc>>; + /// Minimum UDS negative response length: 0x7F + SID + NRC. const UDS_NEGATIVE_RESPONSE_MIN_LEN: usize = 3; /// Minimum UDS positive response buffer size: response SID (1) + DID high (1) + DID low (1). const UDS_POSITIVE_RESPONSE_MIN_SIZE: usize = 3; -/// Result of a successful UDS DID-to-service resolution. -pub struct ResolvedService { - /// The matched MDD service name (e.g. `"RDBI_VIN"`). - pub name: String, - /// Decoded request parameters as a JSON map. - /// - /// Empty when the CDA request parser is unavailable for the matched service. - pub params: serde_json::Map, -} - -/// Wraps the CDA's [`EcuManager`] with async locking -/// to provide MDD-driven UDS encoding, decoding, and service resolution #[derive(Clone)] pub struct ServiceResolver { - /// All post-construction access uses `.read()` for concurrent reads. - /// The write lock is reserved for future runtime variant detection - /// (`detect_variant` requires `&mut CdaEcuManager`). - manager: Arc>>, + manager: CdaEcuManager, ecu_name: String, } impl ServiceResolver { - /// Create new service resolver from ECU name and MDD database. - /// - /// # Arguments - /// * `ecu_name` - Name of the ECU - /// * `db` - Loaded `DiagnosticDatabase` from MDD file - /// * `logical_address` - ECU logical address (e.g. 0x1000) - /// * `tester_address` - Tester logical address (e.g. 0x0E80) + /// Initialise from an ECU name and a loaded MDD database. /// /// # Errors - /// Returns an error if the ECU manager cannot be initialized from the database. + /// + /// Returns `DiagServiceError` when the CDA `EcuManager` cannot be created + /// or the base variant fails to activate. pub async fn new( ecu_name: String, db: DiagnosticDatabase, @@ -118,7 +79,7 @@ impl ServiceResolver { protocol_case_sensitive: false, }; - let mut manager = CdaEcuManager::new( + let mut manager = EcuManager::new( db, Protocol::DoIp, &com_params, @@ -140,6 +101,30 @@ impl ServiceResolver { }) } + /// Return a [`DidResolver`] for DID-to-service resolution. + #[must_use] + pub fn did_resolver(&self) -> DidResolver { + DidResolver::new(Arc::clone(&self.manager)) + } + + /// Return a [`ResponseEncoder`] for building UDS response bytes. + #[must_use] + pub fn response_encoder(&self) -> ResponseEncoder { + ResponseEncoder::new(Arc::clone(&self.manager)) + } + + /// Return a [`MetadataProvider`] for MDD parameter queries. + #[must_use] + pub fn metadata(&self) -> MetadataProvider { + MetadataProvider::new(Arc::clone(&self.manager)) + } + + /// ECU name as configured at construction time. + #[must_use] + pub fn ecu_name(&self) -> &str { + &self.ecu_name + } + /// Activate the base (fallback) ECU variant. /// /// The CDA's diagnostic engine requires a variant to be selected before @@ -158,13 +143,13 @@ impl ServiceResolver { /// 3. The engine narrows the active variant and limits visible services. /// /// # Errors - /// Returns an error only when `detect_variant` fails **and** no variant - /// name was set (i.e. the engine did not activate at all). + /// + /// Returns `DiagServiceError` when `detect_variant` fails and no + /// variant name was set. async fn activate_base_variant( - manager: &mut CdaEcuManager, + manager: &mut EcuManager, ) -> Result<(), DiagServiceError> { - // `TODO:` replace this dummy response with real variant-identification - // DID reads from the ECU (see doc comment above). + // TODO(#16): replace with real variant-identification DID reads. let dummy_response = DiagServiceResponseStruct { service: DiagComm { name: String::new(), @@ -195,24 +180,7 @@ impl ServiceResolver { }) } - /// Check if a UDS response is negative (SID 0x7F). - #[must_use] - pub fn is_negative_response(uds_response: &[u8]) -> bool { - UdsResponse::new(uds_response).is_negative() - } - - /// Extract NRC (Negative Response Code) from a negative response. - #[must_use] - pub fn get_nrc(uds_response: &[u8]) -> Option { - UdsResponse::new(uds_response).nrc() - } - - /// Get ECU name. - #[must_use] - pub fn ecu_name(&self) -> &str { - &self.ecu_name - } - + /// Build default `DoIP` communication parameters for the given addresses. fn default_com_params(logical_address: u16, tester_address: u16) -> ComParams { let mut com_params = ComParams::default(); com_params.doip.logical_gateway_address.default = logical_address; @@ -228,21 +196,21 @@ mod tests { #[test] fn test_is_negative_response() { - assert!(!ServiceResolver::is_negative_response(&[0x62, 0xF1, 0x90])); - assert!(!ServiceResolver::is_negative_response(&[0x50, 0x01])); - assert!(ServiceResolver::is_negative_response(&[0x7F, 0x22, 0x31])); - assert!(!ServiceResolver::is_negative_response(&[0x7F])); - assert!(!ServiceResolver::is_negative_response(&[0x7F, 0x22])); + assert!(!UdsResponse::new(&[0x62, 0xF1, 0x90]).is_negative()); + assert!(!UdsResponse::new(&[0x50, 0x01]).is_negative()); + assert!(UdsResponse::new(&[0x7F, 0x22, 0x31]).is_negative()); + assert!(!UdsResponse::new(&[0x7F]).is_negative()); + assert!(!UdsResponse::new(&[0x7F, 0x22]).is_negative()); } #[test] fn test_get_nrc() { - assert_eq!(ServiceResolver::get_nrc(&[0x62, 0xF1, 0x90]), None); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x31]), Some(0x31)); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x10, 0x11]), Some(0x11)); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22, 0x22]), Some(0x22)); - assert_eq!(ServiceResolver::get_nrc(&[0x7F]), None); - assert_eq!(ServiceResolver::get_nrc(&[0x7F, 0x22]), None); + assert_eq!(UdsResponse::new(&[0x62, 0xF1, 0x90]).nrc(), None); + assert_eq!(UdsResponse::new(&[0x7F, 0x22, 0x31]).nrc(), Some(0x31)); + assert_eq!(UdsResponse::new(&[0x7F, 0x10, 0x11]).nrc(), Some(0x11)); + assert_eq!(UdsResponse::new(&[0x7F, 0x22, 0x22]).nrc(), Some(0x22)); + assert_eq!(UdsResponse::new(&[0x7F]).nrc(), None); + assert_eq!(UdsResponse::new(&[0x7F, 0x22]).nrc(), None); } #[test] @@ -258,23 +226,17 @@ mod tests { (0x22, 0x78, 0x78), ]; for &(sid, nrc, expected) in cases { - assert_eq!(ServiceResolver::get_nrc(&[0x7F, sid, nrc]), Some(expected)); + assert_eq!(UdsResponse::new(&[0x7F, sid, nrc]).nrc(), Some(expected)); } } #[test] fn test_positive_response_sids() { - assert!(!ServiceResolver::is_negative_response(&[ - 0x50, 0x01, 0x00, 0x32 - ])); - assert!(!ServiceResolver::is_negative_response(&[ - 0x62, 0xF1, 0x90, 0x57 - ])); - assert!(!ServiceResolver::is_negative_response(&[ - 0x67, 0x01, 0x12, 0x34 - ])); - assert!(!ServiceResolver::is_negative_response(&[0x6E, 0xF1, 0x90])); - assert!(!ServiceResolver::is_negative_response(&[0x7E, 0x00])); + assert!(!UdsResponse::new(&[0x50, 0x01, 0x00, 0x32]).is_negative()); + assert!(!UdsResponse::new(&[0x62, 0xF1, 0x90, 0x57]).is_negative()); + assert!(!UdsResponse::new(&[0x67, 0x01, 0x12, 0x34]).is_negative()); + assert!(!UdsResponse::new(&[0x6E, 0xF1, 0x90]).is_negative()); + assert!(!UdsResponse::new(&[0x7E, 0x00]).is_negative()); } #[test] @@ -299,7 +261,7 @@ mod tests { #[test] fn test_empty_response() { - assert!(!ServiceResolver::is_negative_response(&[])); - assert_eq!(ServiceResolver::get_nrc(&[]), None); + assert!(!UdsResponse::new(&[]).is_negative()); + assert_eq!(UdsResponse::new(&[]).nrc(), None); } } diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs index 21a0ac0..c5f24f3 100644 --- a/proxy-core/src/service_resolver/resolve.rs +++ b/proxy-core/src/service_resolver/resolve.rs @@ -10,24 +10,12 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! DID-to-service resolution logic. +//! DID-to-service resolution. //! //! Resolves incoming UDS DID values to the correct MDD service name //! using prefix lookup, request parameter metadata, and encoding probes. -//! -//! # Exported Methods (via `ServiceResolver`) -//! - [`ServiceResolver::resolve_read_service`]: Resolve READ service for DID -//! - [`ServiceResolver::resolve_write_service`]: Resolve WRITE service for DID -//! -//! # Algorithm Overview -//! 1. `Prefix lookup` via `[SID, DID_HI, DID_LO]` against MDD coded-const services -//! 2. `Fast path`: Single prefix match -> return immediately -//! 3. `Candidate enumeration`: SID-matching services + component data/config -//! 4. `Metadata matching`: `CodedConst` (exact), `PhysConst` (`coded_value` or probe), -//! `Value` (range/list via `CompuScale`) -//! 5. `Parse validation`: Attempt CDA `convert_request_from_uds` to extract params - -use cda_core::EcuManager as CdaEcuManager; + +use cda_core::EcuManager as InnerManager; use cda_interfaces::{ DynamicPlugin, EcuManager as EcuManagerTrait, HashMap, ServiceParameterMetadata, diagservices::{DiagServiceResponse, UdsPayloadData}, @@ -36,15 +24,37 @@ use cda_interfaces::{ use cda_plugin_security::DefaultSecurityPluginData; use super::{ - ResolvedService, ServiceResolver, + CdaEcuManager, uds_helpers::{ did_matches_compu_scales, extract_did_from_uds, find_did_param, make_diag_comm, make_service_payload, parse_u64_literal, }, }; -impl ServiceResolver { - /// Resolve the best-matching READ service for UDS request bytes. +/// Successful result of DID-to-service resolution. +pub struct ResolvedService { + /// Matched MDD service name (e.g. `"RDBI_VIN"`). + pub name: String, + /// Decoded request parameters, or an empty map when the CDA parser + /// is unavailable for the matched service. + pub params: serde_json::Map, +} + +/// Resolves UDS DID values to MDD service names. +/// +/// Obtain an instance via +/// [`ServiceResolver::did_resolver()`](super::ServiceResolver::did_resolver). +#[derive(Clone)] +pub struct DidResolver { + manager: CdaEcuManager, +} + +impl DidResolver { + pub(super) fn new(manager: CdaEcuManager) -> Self { + Self { manager } + } + + /// Resolve the best-matching READ service for the given DID and raw UDS bytes. pub async fn resolve_read_service( &self, did: u16, @@ -54,7 +64,7 @@ impl ServiceResolver { .await } - /// Resolve the best-matching WRITE service for UDS request bytes. + /// Resolve the best-matching WRITE service for the given DID and raw UDS bytes. pub async fn resolve_write_service( &self, did: u16, @@ -69,72 +79,62 @@ impl ServiceResolver { .await } - /// Probe a service DID via request encoding for symbolic PHYS-CONST cases. - async fn probe_service_did( - manager: &CdaEcuManager, - service_name: &str, + /// Find the correct service for a given SID + DID. + /// + /// Delegates DID matching to `resolve_service_did`, then attempts + /// parse-validation via `convert_request_from_uds`. + async fn resolve_service( + &self, sid: u8, - params: &[ServiceParameterMetadata], - ) -> Option { - let mut param_map: HashMap = HashMap::default(); - for param in params { - match ¶m.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - // `?` is intentional: if any CodedConst can't be parsed we cannot - // build a valid probe request, so abort the entire probe. - let parsed = parse_u64_literal(coded_value)?; - param_map.insert(param.name.clone(), serde_json::json!(parsed)); - } - cda_interfaces::ParameterTypeMetadata::PhysConst { - phys_constant_value, - .. - } => { - param_map.insert(param.name.clone(), serde_json::json!(phys_constant_value)); - } - cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // Use string probe value for VALUE params to satisfy DOPs that - // parse textual values (TEXTTABLE / string-typed fields). - param_map.insert(param.name.clone(), serde_json::json!("0")); - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} - } - } + did: u16, + uds_bytes: &[u8], + label: &str, + ) -> Option { + tracing::debug!("[MDD] {} DID 0x{:04X}", label, did); - let diag_comm = make_diag_comm(service_name, sid); - let security_plugin: DynamicPlugin = Box::new(()); + let service_name = self.resolve_service_did(sid, did, uds_bytes, label).await?; - let payload = manager - .create_uds_payload( - &diag_comm, - &security_plugin, - Some(UdsPayloadData::ParameterMap(param_map)), - ) - .await - .ok()?; + // Attempt parse-validation to extract structured parameter data. + let manager = self.manager.read().await; + let payload = make_service_payload(uds_bytes); + let diag_comm = make_diag_comm(&service_name, sid); - let probed_did = extract_did_from_uds(&payload.data)?; - // ISO 14229-1 ยง7.3.2: DID 0x0000 is reserved. A zero result means the - // Payload encoding produced a degenerate output (e.g. a TEXTTABLE - // lookup silently failed), so treat it as unresolvable rather than a match. - if probed_did == 0 { - None - } else { - Some(probed_did) + if let Ok(parsed) = manager + .convert_request_from_uds(&diag_comm, &payload, true) + .await + && let Ok(json_resp) = parsed.into_json() + && let serde_json::Value::Object(map) = json_resp.data + { + tracing::debug!( + "[MDD] {} DID 0x{:04X} -> '{}' (parse verified)", + label, + did, + service_name + ); + return Some(ResolvedService { + name: service_name, + params: map, + }); } + + // Parse failed -- still return the metadata-resolved service with empty map. + tracing::debug!( + "[MDD] {} DID 0x{:04X} -> '{}' (metadata match, parse unavailable)", + label, + did, + service_name + ); + Some(ResolvedService { + name: service_name, + params: serde_json::Map::new(), + }) } /// Resolve a DID to a service name using prefix lookup and metadata. /// - /// Uses `lookup_diagcomms_by_request_prefix` with the full `[SID, DID_HI, - /// DID_LO]` prefix for direct matching of CODED-CONST DID services. For - /// `PhysConst` / Value DID services (where only the SID is a coded constant), - /// confirms the match via request parameter metadata. - /// - /// # Parameters - /// * `sid` - UDS service identifier (e.g. 0x22 for RDBI, 0x2E for WDBI). - /// * `did` - 16-bit Data Identifier to resolve. - /// * `uds_bytes` - Raw incoming UDS request bytes. - /// * `label` - Log prefix string (e.g. `"READ"`, `"WRITE"`). + /// Step 1: prefix lookup with `[SID, DID_HI, DID_LO]`. + /// Step 2: build candidate list. + /// Step 3: match each candidate via request parameter metadata. // `did` is `u16`; `did >> 8` is at most 0xFF and `did & 0xFF` is at most 0xFF, // so both narrowing casts to `u8` are safe and can never truncate. #[allow(clippy::cast_possible_truncation)] @@ -168,29 +168,25 @@ impl ServiceResolver { None } - /// Step 1 + 2: prefix lookup, fast-path, and candidate list. + /// Build the candidate list from prefix lookup and supplementary sources. /// - /// Returns `None` (after logging) when no candidates exist. - /// Returns `Some` with a single name already when the fast path fires - /// (only one prefix match โ€” skip Step 3 entirely). + /// Returns `Some` with a single-element vec on a unique prefix match + /// (fast path). Returns `None` when no candidates exist. fn build_did_candidates( - manager: &CdaEcuManager, + manager: &InnerManager, did_prefix: [u8; 3], sid: u8, did: u16, label: &str, ) -> Option> { - // Step 1: Prefix lookup with [SID, DID_HI, DID_LO]. - // - // The CDA matches sequential coded-const parameters against the prefix: - // - CODED-CONST DID services -> only exact DID matches pass. - // - PhysConst / Value DID services -> only the SID byte is coded-const, - // so all services with matching SID pass through. + // Prefix lookup with [SID, DID_HI, DID_LO]. + // CODED-CONST DID services only pass on exact DID match; + // PhysConst/Value services pass when the SID byte matches. let prefix_matches = manager .lookup_diagcomms_by_request_prefix(&did_prefix) .unwrap_or_default(); - // Fast path: single match from prefix lookup (common case: unique DID). + // Single prefix match (common case: unique DID) -- skip metadata check. if let [only] = prefix_matches.as_slice() { let name = only.lookup_name.as_deref().unwrap_or(&only.name); tracing::info!( @@ -202,8 +198,8 @@ impl ServiceResolver { return Some(vec![name.to_owned()]); } - // Step 2: Build deduplicated candidate list from prefix matches + - // supplementary sources (bypass NOT-INHERITED-DIAG-COMMS filter). + // Build deduplicated candidate list from prefix matches and + // supplementary sources (bypasses NOT-INHERITED-DIAG-COMMS filter). let mut candidates: Vec = Vec::new(); for dc in &prefix_matches { @@ -255,10 +251,10 @@ impl ServiceResolver { Some(candidates) } - /// Step 3: check if `candidate_name` matches `did` via request parameter metadata. + /// Check whether `candidate_name` matches `did` via request parameter metadata. async fn match_candidate_did( &self, - manager: &CdaEcuManager, + manager: &InnerManager, candidate_name: &str, sid: u8, did: u16, @@ -275,8 +271,7 @@ impl ServiceResolver { } Some(cda_interfaces::ParameterTypeMetadata::PhysConst { coded_value, .. }) => { - // `coded_value` is `f64` in the CDA schema; DIDs are bounded to - // u16 (0x0000โ€“0xFFFF per ISO 14229), so the narrowing cast is safe. + // f64 -> u16 narrowing is safe for DID range (0x0000-0xFFFF). #[allow(clippy::cast_possible_truncation)] let resolved = match coded_value { Some(cv) => Some(*cv as u16), @@ -290,8 +285,7 @@ impl ServiceResolver { compu_scales, .. }) => { - // `coded_default_value` is `f64` in the CDA schema; DIDs are bounded - // to u16 (0x0000โ€“0xFFFF per ISO 14229), so the narrowing cast is safe. + // f64 -> u16 narrowing is safe for DID range. #[allow(clippy::cast_possible_truncation)] let default_ok = coded_default_value .map(|cd| cd as u16 == did) @@ -307,56 +301,56 @@ impl ServiceResolver { } } - /// Find the correct service for a given SID + DID. - /// - /// Delegates DID -> service resolution to [`resolve_service_did`] which uses - /// MDD metadata and probing (`CodedConst`, `PhysConst`, Value+MUX). Then attempts - /// parse-validation via `convert_request_from_uds` for the matched service. - async fn resolve_service( - &self, + /// Probe a service DID via request encoding for symbolic PHYS-CONST cases. + async fn probe_service_did( + manager: &InnerManager, + service_name: &str, sid: u8, - did: u16, - uds_bytes: &[u8], - label: &str, - ) -> Option { - tracing::debug!("[MDD] {} DID 0x{:04X}", label, did); - - let service_name = self.resolve_service_did(sid, did, uds_bytes, label).await?; + params: &[ServiceParameterMetadata], + ) -> Option { + let mut param_map: HashMap = HashMap::default(); + for param in params { + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // `?` is intentional: if any CodedConst can't be parsed we cannot + // build a valid probe request, so abort the entire probe. + let parsed = parse_u64_literal(coded_value)?; + param_map.insert(param.name.clone(), serde_json::json!(parsed)); + } + cda_interfaces::ParameterTypeMetadata::PhysConst { + phys_constant_value, + .. + } => { + param_map.insert(param.name.clone(), serde_json::json!(phys_constant_value)); + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // Use string probe value for VALUE params to satisfy DOPs that + // parse textual values (TEXTTABLE / string-typed fields). + param_map.insert(param.name.clone(), serde_json::json!("0")); + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => {} + } + } - // Attempt parse-validation to extract structured parameter data. - let manager = self.manager.read().await; - let payload = make_service_payload(uds_bytes); - let diag_comm = make_diag_comm(&service_name, sid); + let diag_comm = make_diag_comm(service_name, sid); + let security_plugin: DynamicPlugin = Box::new(()); - if let Ok(parsed) = manager - .convert_request_from_uds(&diag_comm, &payload, true) + let payload = manager + .create_uds_payload( + &diag_comm, + &security_plugin, + Some(UdsPayloadData::ParameterMap(param_map)), + ) .await - && let Ok(json_resp) = parsed.into_json() - && let serde_json::Value::Object(map) = json_resp.data - { - tracing::debug!( - "[MDD] {} DID 0x{:04X} -> '{}' (parse verified)", - label, - did, - service_name - ); - return Some(ResolvedService { - name: service_name, - params: map, - }); - } + .ok()?; - // Parse failed โ€” still return the metadata-resolved service with empty map. - tracing::debug!( - "[MDD] {} DID 0x{:04X} -> '{}' (metadata match, parse unavailable)", - label, - did, - service_name - ); - Some(ResolvedService { - name: service_name, - params: serde_json::Map::new(), - }) + let probed_did = extract_did_from_uds(&payload.data)?; + // ISO 14229-1: DID 0x0000 is reserved; treat zero as unresolvable. + if probed_did == 0 { + None + } else { + Some(probed_did) + } } } diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index 5225a7e..284b6be 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -12,8 +12,11 @@ //! UDS response building and validation. //! -//! Implements [`ServiceResolver::build_response`] which encodes SOVD JSON -//! data into UDS response bytes using MDD parameter metadata. +//! [`ResponseEncoder`] encodes SOVD JSON data into UDS response bytes using +//! MDD parameter metadata. It depends on [`MetadataProvider`] for enriched +//! response metadata queries. + +use std::sync::Arc; use cda_interfaces::{ DiagServiceError, EcuManager as EcuManagerTrait, HashMap, UDS_ID_RESPONSE_BITMASK, @@ -21,34 +24,46 @@ use cda_interfaces::{ }; use super::{ - ServiceResolver, UDS_POSITIVE_RESPONSE_MIN_SIZE, + CdaEcuManager, MetadataProvider, UDS_POSITIVE_RESPONSE_MIN_SIZE, uds_helpers::{ encode_unsigned_be, encode_value_at, find_mux_case_prefix, make_diag_comm, make_service_payload, value_to_bytes, }, }; -impl ServiceResolver { - /// Build UDS response bytes from SOVD JSON data using MDD response metadata. +/// Encodes SOVD JSON data into UDS response bytes using MDD metadata. +#[derive(Clone)] +pub struct ResponseEncoder { + manager: CdaEcuManager, + metadata: MetadataProvider, +} + +impl ResponseEncoder { + pub(super) fn new(manager: CdaEcuManager) -> Self { + let metadata = MetadataProvider::new(Arc::clone(&manager)); + Self { manager, metadata } + } + + /// Build UDS response bytes from SOVD JSON data. /// - /// Queries the POS-RESPONSE parameter layout from the MDD to determine exact - /// byte positions and sizes for each parameter. Each parameter is encoded - /// at its MDD-defined position: + /// Queries the MDD POS-RESPONSE layout and encodes each parameter at its + /// defined byte position: /// - /// - **CODED-CONST**: fixed value written directly (e.g. response SID). - /// - **`MatchingRequestParam`**: DID bytes from the original request. - /// - **VALUE**: SOVD data value encoded with the correct byte width; - /// defaults to 0 when the key is not present in the SOVD response. + /// - `CODED-CONST` -- fixed value (e.g. response SID). + /// - `MatchingRequestParam` -- DID bytes echoed from the request. + /// - `VALUE` -- SOVD data at the MDD offset; defaults to 0 when absent. /// - /// Falls back to naive encoding if response metadata is unavailable. + /// Falls back to naive encoding when no response metadata is available. /// /// # Errors - /// Returns an error if the response cannot be encoded. /// - /// # TODO : - /// Once the SOVD server returns properly structured responses, the naive - /// encoding fallback and the MDD-based `encode_response_from_metadata` - /// path can be removed โ€” the proxy will forward pre-encoded UDS bytes. + /// Returns `DiagServiceError` when the response cannot be encoded. + /// + /// # TODO + /// + /// -- + /// once the SOVD server returns pre-encoded UDS bytes, both encoding + /// paths can be removed. pub async fn build_response( &self, service_name: &str, @@ -69,14 +84,13 @@ impl ServiceResolver { { (r, svc) } else { - // Fallback: naive encoding โ€” used when no response metadata is available. + // Fallback: naive encoding when no response metadata is available. tracing::debug!( "[MDD] No response metadata for '{}', using naive encoding", service_name ); let response_sid = sid.wrapping_add(UDS_ID_RESPONSE_BITMASK); - // `did` is `u16`; `did >> 8` โ‰ค 0xFF and `did & 0xFF` โ‰ค 0xFF โ€” both - // narrowing casts to `u8` are always safe. + // u16 -> u8 narrowing is safe (each half fits in a byte). #[allow(clippy::cast_possible_truncation)] let mut response = vec![response_sid, (did >> 8) as u8, (did & 0xFF) as u8]; @@ -95,7 +109,6 @@ impl ServiceResolver { response.extend(encode_unsigned_be(num)); } else if let Some(num) = n.as_i64() { let unsigned = num.cast_unsigned(); - // `try_from` check above proves `unsigned` fits in `u8`. #[allow(clippy::cast_possible_truncation)] if u8::try_from(unsigned).is_ok() { response.push(unsigned as u8); @@ -107,8 +120,6 @@ impl ServiceResolver { } serde_json::Value::Array(arr) => { for item in arr { - // Array elements in a JSON byte-array response are UDS byte - // values (0โ€“255). Truncation to `u8` is intentional. #[allow(clippy::cast_possible_truncation)] if let Some(byte) = item.as_u64() { response.push(byte as u8); @@ -132,11 +143,8 @@ impl ServiceResolver { (response, service_name.to_string()) }; - // Debug-only round-trip validation: parse the built bytes back through - // the CDA to confirm the MDD layout produces a decodable - // response. Uses the effective service name (which may be an enriched - // MUX sibling) so the CDA parses against the same structure we - // encoded with. + // Debug-only round-trip: parse the built bytes back through the CDA + // to confirm the MDD layout produces a decodable response. if tracing::enabled!(tracing::Level::DEBUG) { self.validate_response(&effective_service, sid, &response) .await; @@ -145,48 +153,11 @@ impl ServiceResolver { Ok(response) } - /// Round-trip validate UDS response bytes by parsing them back through - /// the CDA. + /// Encode a UDS response using POS-RESPONSE parameter metadata. /// - /// Called only when `tracing::Level::DEBUG` is enabled โ€” failures are logged - /// as warnings but never block the response (non-blocking). - async fn validate_response(&self, service_name: &str, request_sid: u8, uds_response: &[u8]) { - let diag_comm = make_diag_comm(service_name, request_sid); - let payload = make_service_payload(uds_response); - let manager = self.manager.read().await; - match manager.convert_from_uds(&diag_comm, &payload, true).await { - Ok(parsed) => match parsed.into_json() { - Ok(json) => tracing::trace!( - "[MDD] Round-trip validation OK for '{}': {:?}", - service_name, - json.data - ), - Err(e) => tracing::warn!( - "[MDD] Round-trip validation: JSON decode failed for '{}': {}", - service_name, - e - ), - }, - Err(e) => tracing::warn!( - "[MDD] Round-trip validation: parse failed for '{}': {}", - service_name, - e - ), - } - } - - /// Encode a UDS response using POS-RESPONSE parameter metadata from the MDD. - /// - /// For each parameter in the MDD response structure: - /// - CODED-CONST (e.g. response SID at byte 0): writes the const value. - /// - `MatchingRequestParam` (e.g. DID at bytes 1-2): writes the DID. - /// - VALUE: uses the SOVD response data keyed by the MDD parameter name; - /// falls back to `0` when the key is absent. - /// - /// Returns `None` when no response metadata is available for the service. - /// On success returns the encoded bytes and the effective service name - /// (which may differ from `service_name` when enriched MUX sibling metadata - /// is used). + /// Returns `None` when no metadata is available. On success returns the + /// encoded bytes and the effective service name (which may differ when + /// enriched MUX sibling metadata is used). async fn encode_response_from_metadata( &self, service_name: &str, @@ -194,7 +165,9 @@ impl ServiceResolver { did: u16, response_data: &HashMap, ) -> Option<(Vec, String)> { + // Cross-component call: ResponseEncoder -> MetadataProvider. let (meta, effective_service) = self + .metadata .get_enriched_response_metadata_with_source(service_name, did) .await .ok()?; @@ -202,16 +175,15 @@ impl ServiceResolver { return None; } - // Find the MUX case matching this DID (if any) using floor-based matching. + // Find the MUX case matching this DID (floor-based). let mux_case_prefix = find_mux_case_prefix(&meta, did); - // Derive the matching marker name for total_size computation. + // Derive the case marker name for total_size computation. let mux_marker_name: Option = mux_case_prefix .as_deref() .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - // Filter: keep top-level params (no '/') + matching MUX case VALUE params - // + the matching case marker (for total_size). + // Keep top-level params (no '/') plus matching MUX case sub-params. let active_params: Vec<_> = meta .iter() .filter(|p| { @@ -226,16 +198,15 @@ impl ServiceResolver { }) .collect(); - // Resolve effective size for each active param. For VALUE params with - // `byte_size: None` (variable-length DOPs like EndOfPdu), the size is - // inferred from the actual response data. + // Resolve effective size: for VALUE params with `byte_size: None` + // (variable-length DOPs), infer the size from actual response data. let effective_sizes: Vec = active_params .iter() .map(|p| { if let Some(s) = p.byte_size { return s as usize; } - // Variable-size VALUE param โ€” infer size from the data. + // Variable-size VALUE param -- infer size from the data. if !matches!( &p.param_type, cda_interfaces::ParameterTypeMetadata::Value { .. } @@ -338,6 +309,34 @@ impl ServiceResolver { ); Some((response, effective_service)) } + + /// Round-trip validate UDS response bytes by parsing them back through + /// the CDA. Only called at DEBUG level; failures are logged but never + /// block the response. + async fn validate_response(&self, service_name: &str, request_sid: u8, uds_response: &[u8]) { + let diag_comm = make_diag_comm(service_name, request_sid); + let payload = make_service_payload(uds_response); + let manager = self.manager.read().await; + match manager.convert_from_uds(&diag_comm, &payload, true).await { + Ok(parsed) => match parsed.into_json() { + Ok(json) => tracing::trace!( + "[MDD] Round-trip validation OK for '{}': {:?}", + service_name, + json.data + ), + Err(e) => tracing::warn!( + "[MDD] Round-trip validation: JSON decode failed for '{}': {}", + service_name, + e + ), + }, + Err(e) => tracing::warn!( + "[MDD] Round-trip validation: parse failed for '{}': {}", + service_name, + e + ), + } + } } #[cfg(test)] @@ -417,7 +416,7 @@ mod tests { #[test] fn test_encode_value_at_out_of_bounds_noop() { let mut buf = [0u8; 2]; - // pos=1, size=3 โ†’ end=4 > buf.len()=2 โ†’ noop + // pos=1, size=3 -> end=4 > buf.len()=2 -> noop encode_value_at(&mut buf, 1, 3, Some(&serde_json::json!(0xFFu64))); assert_eq!(buf, [0x00, 0x00]); } @@ -516,7 +515,7 @@ mod tests { mux_case_marker("VIN", 0xF190), // case marker for 0xF190 mux_case_marker("OTHER", 0xF100), // different case marker value_param("VIN/DATA", 3, 17), // VIN sub-param - value_param("OTHER/DATA", 3, 4), // OTHER sub-param โ†’ excluded + value_param("OTHER/DATA", 3, 4), // OTHER sub-param -> excluded ]; let mux_case_prefix = find_mux_case_prefix(&meta, did); @@ -590,7 +589,7 @@ mod tests { .max() .unwrap_or(3); - // SID: 0+1=1, DID: 1+2=3, DATA: 3+17=20 โ†’ max = 20 + // SID: 0+1=1, DID: 1+2=3, DATA: 3+17=20 -> max = 20 assert_eq!(total, 20); } } diff --git a/proxy-core/src/service_resolver/uds_helpers.rs b/proxy-core/src/service_resolver/uds_helpers.rs index bd222cc..d47b1da 100644 --- a/proxy-core/src/service_resolver/uds_helpers.rs +++ b/proxy-core/src/service_resolver/uds_helpers.rs @@ -10,11 +10,11 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! UDS helper functions, types for encoding, decoding, and service metadata queries. +//! UDS helper functions and types. //! -//! Pure functions and types used across the [`super::ServiceResolver`] implementation: -//! DID extraction, MUX-case matching, value encoding, payload construction, and -//! structured access to UDS response bytes. +//! Pure functions used across the `service_resolver` module: DID extraction, +//! MUX-case matching, value encoding, payload construction, and +//! [`UdsResponse`] for structured access to UDS response bytes. use cda_interfaces::{ CompuScaleInfo, DiagComm, DiagCommType, ResponseParameterInfo, ServiceParameterMetadata, @@ -24,9 +24,6 @@ use cda_interfaces::{ use super::UDS_NEGATIVE_RESPONSE_MIN_LEN; /// Typed accessor for raw UDS response bytes. -/// -/// Wraps a byte slice and exposes structured accessors for UDS response fields, -/// hiding direct index arithmetic from callers. pub struct UdsResponse<'a>(&'a [u8]); impl<'a> UdsResponse<'a> { @@ -42,7 +39,7 @@ impl<'a> UdsResponse<'a> { self.0.first().copied() } - /// Returns `true` if this is a negative response (SID `0x7F`). + /// Returns `true` if this is a negative response (`0x7F` + SID + NRC). #[must_use] pub fn is_negative(&self) -> bool { self.0.len() >= UDS_NEGATIVE_RESPONSE_MIN_LEN @@ -67,7 +64,7 @@ pub(super) fn extract_did_from_uds(data: &[u8]) -> Option { Some(u16::from_be_bytes([b1, b2])) } -/// Map a UDS service identifier to its [`DiagCommType`]. +/// Map a UDS SID to its [`DiagCommType`]. /// /// Falls back to [`DiagCommType::Data`] for unrecognised SIDs so that the /// caller always receives a usable type rather than an error. @@ -86,14 +83,13 @@ pub(super) fn make_service_payload(data: &[u8]) -> ServicePayload { } } -/// Encode an unsigned integer as big-endian bytes using the minimum width needed. +/// Encode an unsigned integer as big-endian bytes (minimum width). /// -/// Always produces at least one byte; zero encodes as `[0x00]`. +/// Zero encodes as `[0x00]`. pub(super) fn encode_unsigned_be(num: u64) -> Vec { if num == 0 { return vec![0x00]; } - // Skip leading zero bytes; safe because num != 0 guarantees a non-empty result. num.to_be_bytes() .iter() .copied() From a3b2e13900e0b3e5ca09e0af0926f903d65a2a30 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 30 Apr 2026 14:23:17 +0200 Subject: [PATCH 10/33] Fix: address review comments Signed-off-by: Arvind Rathod --- .../service_resolver_class_diagram.puml | 50 ++--- .../service_resolver_class_diagram.svg | 1 + ...service_resolver_class_diagram.svg.license | 0 .../service_resolver_sequence_diagram.puml | 33 ++- .../service_resolver_sequence_diagram.svg | 1 + ...vice_resolver_sequence_diagram.svg.license | 0 docs/service_resolver_class_diagram.svg | 1 - docs/service_resolver_sequence_diagram.svg | 1 - proxy-core/src/config.rs | 34 ++- proxy-core/src/lib.rs | 11 +- proxy-core/src/service_resolver/metadata.rs | 23 +- proxy-core/src/service_resolver/mod.rs | 165 ++++++-------- proxy-core/src/service_resolver/resolve.rs | 202 ++++++++++-------- proxy-core/src/service_resolver/response.rs | 16 +- .../src/service_resolver/uds_helpers.rs | 73 +------ 15 files changed, 278 insertions(+), 333 deletions(-) rename docs/{ => service_resolver}/service_resolver_class_diagram.puml (81%) create mode 100644 docs/service_resolver/service_resolver_class_diagram.svg rename docs/{ => service_resolver}/service_resolver_class_diagram.svg.license (100%) rename docs/{ => service_resolver}/service_resolver_sequence_diagram.puml (84%) create mode 100644 docs/service_resolver/service_resolver_sequence_diagram.svg rename docs/{ => service_resolver}/service_resolver_sequence_diagram.svg.license (100%) delete mode 100644 docs/service_resolver_class_diagram.svg delete mode 100644 docs/service_resolver_sequence_diagram.svg diff --git a/docs/service_resolver_class_diagram.puml b/docs/service_resolver/service_resolver_class_diagram.puml similarity index 81% rename from docs/service_resolver_class_diagram.puml rename to docs/service_resolver/service_resolver_class_diagram.puml index df6f7fa..ee38b4b 100644 --- a/docs/service_resolver_class_diagram.puml +++ b/docs/service_resolver/service_resolver_class_diagram.puml @@ -19,38 +19,36 @@ skinparam classFontSize 12 ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ' proxy-core::service_resolver -' Facade (ServiceResolver) owns CdaEcuManager and ecu_name, exposes -' sub-component accessors. Each sub-component is a focused struct: -' DidResolver (resolve.rs) -- DID-to-service resolution -' ResponseEncoder (response.rs) -- UDS response encoding -' MetadataProvider (metadata.rs) -- MDD parameter queries -' uds_helpers.rs holds free functions and the UdsResponse type. +' Facade (ServiceResolver) owns CdaEcuManager and ecu_name. +' Sub-components are public fields (not accessors): +' resolver : DidResolver (resolve.rs) -- DID-to-service resolution +' encoder : ResponseEncoder (response.rs) -- UDS response encoding +' metadata : MetadataProvider (metadata.rs) -- MDD parameter queries +' uds_helpers.rs holds pure free functions only. ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ package "proxy-core::service_resolver" { class ServiceResolver <> { - manager : CdaEcuManager - ecu_name : String - == mod.rs -- construction & accessors == + + resolver : DidResolver + + encoder : ResponseEncoder + + metadata : MetadataProvider + == mod.rs -- construction == + {static} <> new(ecu_name, db, logical, tester) : Result - {static} <> activate_base_variant(manager) : Result<()> - {static} default_com_params(logical, tester: u16) : ComParams + ecu_name() : &str - + did_resolver() : DidResolver - + response_encoder() : ResponseEncoder - + metadata() : MetadataProvider } together { class DidResolver { - manager : CdaEcuManager == resolve.rs -- DID --> service name == - + <> resolve_read_service(did, uds) : Option - + <> resolve_write_service(did, uds) : Option - - <> resolve_service(sid, did, uds, label) : Option - - <> resolve_service_did(sid, did, ...) : Option - - {static} build_did_candidates(manager, prefix, sid, did) : Option> - - <> match_candidate_did(manager, name, sid, did) : bool + + <> resolve(service_type, did, uds) : Option + - <> resolve_service_did(sid, did, label) : Option + - {static} build_did_candidates(manager, did_prefix, sid, did, label) : Option> + - {static} <> match_candidate_did(manager, name, sid, did) : bool - {static} <> probe_service_did(manager, name, sid, meta) : Option } @@ -66,8 +64,8 @@ package "proxy-core::service_resolver" { class MetadataProvider { - manager : CdaEcuManager == metadata.rs -- MDD parameter queries == - + <> get_service_parameter_metadata(name) : Result> - + <> get_response_parameter_metadata(name) : Result> + + <> get_request_params(name) : Result> + + <> get_response_params(name) : Result> + <> get_enriched_response_metadata(name, did) : Result> + <> get_enriched_response_metadata_with_source(name, did) : Result<(Vec, String)> + <> lookup_service_names_by_sid(sid) : Result> @@ -98,15 +96,10 @@ package "proxy-core::service_resolver" { end note class uds_helpers <> { - ' -- pub re-exports (used by proxy-sovd) -- + ' -- pub re-exports -- + parse_mux_coded_value(coded) : Option + find_mux_case_prefix(meta, did) : Option + has_mux_case_for_did_exact(meta, did) : bool - == UdsResponse == - + UdsResponse::new(bytes) : UdsResponse - + UdsResponse::sid() : Option - + UdsResponse::is_negative() : bool - + UdsResponse::nrc() : Option == internal helpers == ~ extract_did_from_uds(data) : Option ~ diag_comm_type(sid) : DiagCommType @@ -121,8 +114,7 @@ package "proxy-core::service_resolver" { } note bottom of uds_helpers - Top 3 + UdsResponse are pub re-exported - from mod.rs and used by proxy-sovd. + Top 3 are pub re-exported from mod.rs. end note class ResolvedService <> { @@ -130,9 +122,9 @@ package "proxy-core::service_resolver" { + params : Map } - ServiceResolver --> DidResolver : did_resolver() - ServiceResolver --> ResponseEncoder : response_encoder() - ServiceResolver --> MetadataProvider : metadata() + ServiceResolver *--> DidResolver : resolver (pub field) + ServiceResolver *--> ResponseEncoder : encoder (pub field) + ServiceResolver *--> MetadataProvider : metadata (pub field) ResponseEncoder o--> MetadataProvider : holds (explicit dependency) DidResolver ..> uds_helpers : uses ResponseEncoder ..> uds_helpers : uses diff --git a/docs/service_resolver/service_resolver_class_diagram.svg b/docs/service_resolver/service_resolver_class_diagram.svg new file mode 100644 index 0000000..83190e5 --- /dev/null +++ b/docs/service_resolver/service_resolver_class_diagram.svg @@ -0,0 +1 @@ +Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-ecu_name : String+resolver : DidResolver+encoder : ResponseEncoder+metadata : MetadataProvider+«async» new(ecu_name, db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParams+ecu_name() : &strmod.rs -- constructionDidResolver-manager : CdaEcuManager+«async» resolve(service_type, did, uds) : Option<ResolvedService>-«async» resolve_service_did(sid, did, label) : Option<String>-build_did_candidates(manager, did_prefix, sid, did, label) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service nameResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider+«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS responseMetadataProvider-manager : CdaEcuManager+«async» get_request_params(name) : Result<Vec<Param>>+«async» get_response_params(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rs.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>resolver (pub field)encoder (pub field)metadata (pub field)holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. diff --git a/docs/service_resolver_class_diagram.svg.license b/docs/service_resolver/service_resolver_class_diagram.svg.license similarity index 100% rename from docs/service_resolver_class_diagram.svg.license rename to docs/service_resolver/service_resolver_class_diagram.svg.license diff --git a/docs/service_resolver_sequence_diagram.puml b/docs/service_resolver/service_resolver_sequence_diagram.puml similarity index 84% rename from docs/service_resolver_sequence_diagram.puml rename to docs/service_resolver/service_resolver_sequence_diagram.puml index 0ffc744..8c234fb 100644 --- a/docs/service_resolver_sequence_diagram.puml +++ b/docs/service_resolver/service_resolver_sequence_diagram.puml @@ -21,16 +21,10 @@ participant "CDA EcuManager" as CDA == READ Service Resolution == -Client -> Facade: did_resolver() -Facade --> Client: DidResolver - -Client -> Resolver: resolve_read_service(did, uds_bytes) -activate Resolver - -Resolver -> Resolver: resolve_service(SID=0x22, did, uds_bytes, "READ") +Client -> Resolver: resolve(ServiceType::Read, did, uds_bytes) activate Resolver - Resolver -> Resolver: resolve_service_did(sid, did, uds_bytes, "READ") + Resolver -> Resolver: resolve_service_did(sid=0x22, did, label="READ") activate Resolver Resolver -> CDA: lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO]) @@ -38,7 +32,7 @@ activate Resolver CDA --> Resolver: matching_services deactivate CDA - Resolver -> Resolver: build_did_candidates(manager, prefix, sid, did) + Resolver -> Resolver: build_did_candidates(manager, did_prefix, sid, did, label) activate Resolver Resolver -> CDA: get_components_data_info() or\nget_components_configurations_info() activate CDA @@ -87,13 +81,14 @@ deactivate Resolver == WRITE Service Handling == -note right of Client: Similar flow for WRITE services\nusing SID=0x2E and\nget_components_configurations_info()\nClient calls facade.did_resolver()\nthen resolver.resolve_write_service() +note right of Client + Similar flow for WRITE services + client calls resolver.resolve(ServiceType::Write, did, uds_bytes) + which uses sid=0x2E and get_components_configurations_info() +end note == Response Building == -Client -> Facade: response_encoder() -Facade --> Client: ResponseEncoder - Client -> Resp: build_response(service_name, sid, did, response_data) activate Resp @@ -156,20 +151,22 @@ deactivate Resp note right of Client - - **ServiceResolver (mod.rs)**: Facade -- construction, - variant activation, sub-component accessors + - **ServiceResolver (mod.rs)**: construction, + variant activation. Sub-components: + resolver, encoder, metadata - **DidResolver (resolve.rs)**: DID -> service resolution, candidate building, metadata matching - **ResponseEncoder (response.rs)**: UDS response encoding, round-trip validation (debug only) - **MetadataProvider (metadata.rs)**: MDD metadata queries, MUX sibling enrichment - - **uds_helpers.rs**: Pure utilities + UdsResponse -- + - **uds_helpers.rs**: Pure free functions -- encoding, decoding, MUX matching **Data flow:** - Caller gets sub-component via accessor, then calls - methods directly on that sub-component. + Caller accesses resolver, encoder, metadata as + direct pub fields on ServiceResolver, then calls methods + on those sub-components directly. ResponseEncoder holds MetadataProvider internally for the cross-module enrichment dependency. end note diff --git a/docs/service_resolver/service_resolver_sequence_diagram.svg b/docs/service_resolver/service_resolver_sequence_diagram.svg new file mode 100644 index 0000000..e61421a --- /dev/null +++ b/docs/service_resolver/service_resolver_sequence_diagram.svg @@ -0,0 +1 @@ +ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs facade)ServiceResolver(mod.rs facade)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve(ServiceType::Read, did, uds_bytes)resolve_service_did(sid=0x22, did, label="READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, did_prefix, sid, did, label)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesclient calls resolver.resolve(ServiceType::Write, did, uds_bytes)which uses sid=0x2E and get_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): construction,variant activation. Sub-components:resolver, encoder, metadata-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure free functions --encoding, decoding, MUX matching Data flow:Caller accesses resolver, encoder, metadata asdirect pub fields on ServiceResolver, then calls methodson those sub-components directly.ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. diff --git a/docs/service_resolver_sequence_diagram.svg.license b/docs/service_resolver/service_resolver_sequence_diagram.svg.license similarity index 100% rename from docs/service_resolver_sequence_diagram.svg.license rename to docs/service_resolver/service_resolver_sequence_diagram.svg.license diff --git a/docs/service_resolver_class_diagram.svg b/docs/service_resolver_class_diagram.svg deleted file mode 100644 index 1e71cba..0000000 --- a/docs/service_resolver_class_diagram.svg +++ /dev/null @@ -1 +0,0 @@ -Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-ecu_name : String+«async» new(ecu_name, db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParams+ecu_name() : &str+did_resolver() : DidResolver+response_encoder() : ResponseEncoder+metadata() : MetadataProvidermod.rs -- construction & accessorsDidResolver-manager : CdaEcuManager+«async» resolve_read_service(did, uds) : Option<ResolvedService>+«async» resolve_write_service(did, uds) : Option<ResolvedService>-«async» resolve_service(sid, did, uds, label) : Option<ResolvedService>-«async» resolve_service_did(sid, did, ...) : Option<String>-build_did_candidates(manager, prefix, sid, did) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service nameResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider+«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS responseMetadataProvider-manager : CdaEcuManager+«async» get_service_parameter_metadata(name) : Result<Vec<Param>>+«async» get_response_parameter_metadata(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool+UdsResponse::new(bytes) : UdsResponse+UdsResponse::sid() : Option<u8>+UdsResponse::is_negative() : bool+UdsResponse::nrc() : Option<u8>UdsResponse~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 + UdsResponse are pub re-exportedfrom mod.rs and used by proxy-sovd.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>did_resolver()response_encoder()metadata()holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. diff --git a/docs/service_resolver_sequence_diagram.svg b/docs/service_resolver_sequence_diagram.svg deleted file mode 100644 index 0f80d69..0000000 --- a/docs/service_resolver_sequence_diagram.svg +++ /dev/null @@ -1 +0,0 @@ -ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs facade)ServiceResolver(mod.rs facade)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutiondid_resolver()DidResolverresolve_read_service(did, uds_bytes)resolve_service(SID=0x22, did, uds_bytes, "READ")resolve_service_did(sid, did, uds_bytes, "READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, prefix, sid, did)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesusing SID=0x2E andget_components_configurations_info()Client calls facade.did_resolver()then resolver.resolve_write_service()Response Buildingresponse_encoder()ResponseEncoderbuild_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): Facade -- construction,variant activation, sub-component accessors-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure utilities + UdsResponse --encoding, decoding, MUX matching Data flow:Caller gets sub-component via accessor, then callsmethods directly on that sub-component.ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index e48a0aa..91ad685 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -21,6 +21,22 @@ use crate::error::{ProxyError, Result}; /// Required byte length for EID and GID fields per ISO 13400-2. const EID_GID_BYTE_LENGTH: usize = 6; + +// Default values for ServerConfig. +const DEFAULT_DOIP_PORT: u16 = 13400; +const DEFAULT_MAX_CONNECTIONS: usize = 10; +/// `DoIP` source address (tester logical address used in response messages). +const DEFAULT_SOURCE_ADDRESS: u16 = 0x0E80; + +// Default values for SovdConfig. +const DEFAULT_GATEWAY_URL: &str = "http://localhost:20002"; +const DEFAULT_CLIENT_ID: &str = "uds2sovd_proxy"; +const DEFAULT_CLIENT_SECRET: &str = "test_secret"; +const DEFAULT_TIMEOUT_MS: u64 = 5000; +const DEFAULT_API_VERSION: &str = "v15"; + +// Default values for EcuConfig. +const DEFAULT_ECU_NAME: &str = "ECU"; /// Top-level proxy configuration loaded from a TOML file. #[derive(Debug, Clone, Deserialize, Default)] pub struct Config { @@ -159,10 +175,10 @@ impl Config { impl Default for ServerConfig { fn default() -> Self { Self { - doip_port: 13400, + doip_port: DEFAULT_DOIP_PORT, bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), - max_connections: 10, - source_address: 0x0E80, + max_connections: DEFAULT_MAX_CONNECTIONS, + source_address: DEFAULT_SOURCE_ADDRESS, } } } @@ -170,11 +186,11 @@ impl Default for ServerConfig { impl Default for SovdConfig { fn default() -> Self { Self { - gateway_url: "http://localhost:20002".to_string(), - client_id: "uds2sovd_proxy".to_string(), - client_secret: "test_secret".to_string(), - timeout_ms: 5000, - api_version: "v15".to_string(), + gateway_url: DEFAULT_GATEWAY_URL.to_string(), + client_id: DEFAULT_CLIENT_ID.to_string(), + client_secret: DEFAULT_CLIENT_SECRET.to_string(), + timeout_ms: DEFAULT_TIMEOUT_MS, + api_version: DEFAULT_API_VERSION.to_string(), include_schema: true, mock_gateway: false, } @@ -184,7 +200,7 @@ impl Default for SovdConfig { impl Default for EcuConfig { fn default() -> Self { Self { - default_name: "ECU".to_string(), + default_name: DEFAULT_ECU_NAME.to_string(), logical_address: 0x0001, eid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], gid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], diff --git a/proxy-core/src/lib.rs b/proxy-core/src/lib.rs index b4d4408..84d5ad6 100644 --- a/proxy-core/src/lib.rs +++ b/proxy-core/src/lib.rs @@ -12,9 +12,12 @@ //! Core types and traits shared across all proxy crates. //! -//! Defines configuration, error types, the [`DiagHandler`] trait for -//! pluggable backend implementations, and the MDD-driven -//! [`ServiceResolver`] for UDS request/response processing. +//! Defines configuration, error types, and the MDD-driven [`ServiceResolver`] facade +//! with three composable sub-components: +//! +//! - [`DidResolver`] โ€” DID-to-service resolution +//! - [`ResponseEncoder`] โ€” UDS response encoding +//! - [`MetadataProvider`] โ€” MDD parameter metadata queries pub mod config; pub mod error; @@ -23,5 +26,5 @@ pub mod service_resolver; pub use config::Config; pub use error::{ProxyError, Result}; pub use service_resolver::{ - DidResolver, MetadataProvider, ResolvedService, ResponseEncoder, ServiceResolver, + DidResolver, MetadataProvider, ResolvedService, ResponseEncoder, ServiceResolver, ServiceType, }; diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs index 778a377..7065d98 100644 --- a/proxy-core/src/service_resolver/metadata.rs +++ b/proxy-core/src/service_resolver/metadata.rs @@ -10,22 +10,25 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! MDD metadata queries for service parameters, response layouts, and MUX cases. +//! Service metadata queries and lookup. +//! +//! [`MetadataProvider`] queries request/response parameter metadata from the +//! MDD, looks up services by SID, and retrieves MUX case information. use cda_interfaces::{ DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, MuxCaseInfo, - ServiceParameterMetadata, service_ids, + ServiceParameterMetadata, }; -use super::{CdaEcuManager, uds_helpers::has_mux_case_for_did_exact}; +use super::{ManagerHandle, uds_helpers::has_mux_case_for_did_exact, uds_service_ids}; #[derive(Clone)] pub struct MetadataProvider { - manager: CdaEcuManager, + manager: ManagerHandle, } impl MetadataProvider { - pub(super) fn new(manager: CdaEcuManager) -> Self { + pub fn new(manager: ManagerHandle) -> Self { Self { manager } } @@ -35,7 +38,7 @@ impl MetadataProvider { /// /// Returns `DiagServiceError` when the service is unknown or the MDD /// does not contain request metadata. - pub async fn get_service_parameter_metadata( + pub async fn get_request_params( &self, service_name: &str, ) -> Result, DiagServiceError> { @@ -49,7 +52,7 @@ impl MetadataProvider { /// /// Returns `DiagServiceError` when the service is unknown or no response /// metadata exists. - pub async fn get_response_parameter_metadata( + pub async fn get_response_params( &self, service_name: &str, ) -> Result, DiagServiceError> { @@ -97,12 +100,12 @@ impl MetadataProvider { let manager = self.manager.read().await; let security_plugin: DynamicPlugin = Box::new(()); let names = match sid { - service_ids::READ_DATA_BY_IDENTIFIER => manager + uds_service_ids::READ_DATA_BY_IDENTIFIER => manager .get_components_data_info(&security_plugin) .into_iter() .map(|c| c.id) .collect(), - service_ids::WRITE_DATA_BY_IDENTIFIER => manager + uds_service_ids::WRITE_DATA_BY_IDENTIFIER => manager .get_components_configurations_info(&security_plugin) .unwrap_or_default() .into_iter() @@ -132,7 +135,7 @@ impl MetadataProvider { /// Retrieve enriched POS-RESPONSE metadata with the source service name. /// - /// Same as [`get_enriched_response_metadata`](Self::get_enriched_response_metadata) + /// Same as [`MetadataProvider::get_enriched_response_metadata`] /// but also returns the name of the service that actually provided the /// metadata. When the response is "opaque" (single STRUCTURE ref) and a /// MUX-based sibling is used, the returned name is the sibling -- callers diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs index 68eacf5..1bf1fb8 100644 --- a/proxy-core/src/service_resolver/mod.rs +++ b/proxy-core/src/service_resolver/mod.rs @@ -15,18 +15,15 @@ //! `ServiceResolver` is a thin facade that owns the CDA `EcuManager` and //! exposes three focused sub-components via accessor methods: //! -//! - [`DidResolver`] -- DID-to-service resolution -//! - [`ResponseEncoder`] -- UDS response encoding -//! - [`MetadataProvider`] -- MDD parameter queries -mod metadata; -mod resolve; -mod response; +pub(crate) mod metadata; +pub(crate) mod resolve; +pub(crate) mod response; pub mod uds_helpers; use std::sync::Arc; -use cda_core::{DiagServiceResponseStruct, EcuManager}; +use cda_core::{DiagServiceResponseStruct, EcuManager as CdaEcuManager}; use cda_database::datatypes::DiagnosticDatabase; use cda_interfaces::{ DiagComm, DiagCommType, DiagServiceError, EcuManager as EcuManagerTrait, EcuManagerType, @@ -36,24 +33,63 @@ use cda_interfaces::{ }; use cda_plugin_security::DefaultSecurityPluginData; pub use metadata::MetadataProvider; -pub use resolve::{DidResolver, ResolvedService}; +pub use resolve::{DidResolver, ResolvedService, ServiceType}; pub use response::ResponseEncoder; use tokio::sync::RwLock; -pub use uds_helpers::{ - UdsResponse, find_mux_case_prefix, has_mux_case_for_did_exact, parse_mux_coded_value, -}; - -pub(crate) type CdaEcuManager = Arc>>; +pub use uds_helpers::find_mux_case_prefix; -/// Minimum UDS negative response length: 0x7F + SID + NRC. -const UDS_NEGATIVE_RESPONSE_MIN_LEN: usize = 3; +pub(crate) type ManagerHandle = Arc>>; /// Minimum UDS positive response buffer size: response SID (1) + DID high (1) + DID low (1). -const UDS_POSITIVE_RESPONSE_MIN_SIZE: usize = 3; +pub(crate) const UDS_POSITIVE_RESPONSE_MIN_SIZE: usize = 3; + +/// UDS Service Identifiers (SIDs) for diagnostic services. +/// +/// Proxy-level definitions independent of CDA library. +pub mod uds_service_ids { + /// Session Control + pub const SESSION_CONTROL: u8 = 0x10; + /// ECU Reset + pub const ECU_RESET: u8 = 0x11; + /// Clear Diagnostic Information + pub const CLEAR_DIAGNOSTIC_INFORMATION: u8 = 0x14; + /// Read DTC Information + pub const READ_DTC_INFORMATION: u8 = 0x19; + /// Read Data By Identifier + pub const READ_DATA_BY_IDENTIFIER: u8 = 0x22; + /// Security Access + pub const SECURITY_ACCESS: u8 = 0x27; + /// Communication Control + pub const COMMUNICATION_CONTROL: u8 = 0x28; + /// Authentication + pub const AUTHENTICATION: u8 = 0x29; + /// Write Data By Identifier + pub const WRITE_DATA_BY_IDENTIFIER: u8 = 0x2E; + /// Input/Output Control By Identifier + pub const INPUT_OUTPUT_CONTROL_BY_IDENTIFIER: u8 = 0x2F; + /// Routine Control + pub const ROUTINE_CONTROL: u8 = 0x31; + /// Request Download + pub const REQUEST_DOWNLOAD: u8 = 0x34; + /// Transfer Data + pub const TRANSFER_DATA: u8 = 0x36; + /// Request Transfer Exit + pub const REQUEST_TRANSFER_EXIT: u8 = 0x37; + /// Tester Present + pub const TESTER_PRESENT: u8 = 0x3E; + /// Control DTC Setting + pub const CONTROL_DTC_SETTING: u8 = 0x85; + /// Negative Response + pub const NEGATIVE_RESPONSE: u8 = 0x7F; +} -#[derive(Clone)] pub struct ServiceResolver { - manager: CdaEcuManager, + /// DID-to-service resolution. + pub resolver: DidResolver, + /// UDS response encoding from SOVD JSON data. + pub encoder: ResponseEncoder, + /// MDD metadata queries (request/response parameter info, MUX cases). + pub metadata: MetadataProvider, ecu_name: String, } @@ -79,7 +115,7 @@ impl ServiceResolver { protocol_case_sensitive: false, }; - let mut manager = EcuManager::new( + let mut manager = CdaEcuManager::new( db, Protocol::DoIp, &com_params, @@ -95,36 +131,17 @@ impl ServiceResolver { Self::activate_base_variant(&mut manager).await?; + let handle: ManagerHandle = Arc::new(RwLock::new(manager)); + + let metadata = MetadataProvider::new(Arc::clone(&handle)); Ok(Self { - manager: Arc::new(RwLock::new(manager)), + resolver: DidResolver::new(Arc::clone(&handle)), + encoder: ResponseEncoder::new(Arc::clone(&handle), metadata.clone()), + metadata, ecu_name, }) } - /// Return a [`DidResolver`] for DID-to-service resolution. - #[must_use] - pub fn did_resolver(&self) -> DidResolver { - DidResolver::new(Arc::clone(&self.manager)) - } - - /// Return a [`ResponseEncoder`] for building UDS response bytes. - #[must_use] - pub fn response_encoder(&self) -> ResponseEncoder { - ResponseEncoder::new(Arc::clone(&self.manager)) - } - - /// Return a [`MetadataProvider`] for MDD parameter queries. - #[must_use] - pub fn metadata(&self) -> MetadataProvider { - MetadataProvider::new(Arc::clone(&self.manager)) - } - - /// ECU name as configured at construction time. - #[must_use] - pub fn ecu_name(&self) -> &str { - &self.ecu_name - } - /// Activate the base (fallback) ECU variant. /// /// The CDA's diagnostic engine requires a variant to be selected before @@ -147,7 +164,7 @@ impl ServiceResolver { /// Returns `DiagServiceError` when `detect_variant` fails and no /// variant name was set. async fn activate_base_variant( - manager: &mut EcuManager, + manager: &mut CdaEcuManager, ) -> Result<(), DiagServiceError> { // TODO(#16): replace with real variant-identification DID reads. let dummy_response = DiagServiceResponseStruct { @@ -180,7 +197,12 @@ impl ServiceResolver { }) } - /// Build default `DoIP` communication parameters for the given addresses. + /// Get ECU name. + #[must_use] + pub fn ecu_name(&self) -> &str { + &self.ecu_name + } + fn default_com_params(logical_address: u16, tester_address: u16) -> ComParams { let mut com_params = ComParams::default(); com_params.doip.logical_gateway_address.default = logical_address; @@ -194,51 +216,6 @@ impl ServiceResolver { mod tests { use super::*; - #[test] - fn test_is_negative_response() { - assert!(!UdsResponse::new(&[0x62, 0xF1, 0x90]).is_negative()); - assert!(!UdsResponse::new(&[0x50, 0x01]).is_negative()); - assert!(UdsResponse::new(&[0x7F, 0x22, 0x31]).is_negative()); - assert!(!UdsResponse::new(&[0x7F]).is_negative()); - assert!(!UdsResponse::new(&[0x7F, 0x22]).is_negative()); - } - - #[test] - fn test_get_nrc() { - assert_eq!(UdsResponse::new(&[0x62, 0xF1, 0x90]).nrc(), None); - assert_eq!(UdsResponse::new(&[0x7F, 0x22, 0x31]).nrc(), Some(0x31)); - assert_eq!(UdsResponse::new(&[0x7F, 0x10, 0x11]).nrc(), Some(0x11)); - assert_eq!(UdsResponse::new(&[0x7F, 0x22, 0x22]).nrc(), Some(0x22)); - assert_eq!(UdsResponse::new(&[0x7F]).nrc(), None); - assert_eq!(UdsResponse::new(&[0x7F, 0x22]).nrc(), None); - } - - #[test] - fn test_nrc_codes() { - let cases: &[(u8, u8, u8)] = &[ - (0x22, 0x11, 0x11), - (0x22, 0x12, 0x12), - (0x22, 0x13, 0x13), - (0x22, 0x22, 0x22), - (0x22, 0x31, 0x31), - (0x27, 0x33, 0x33), - (0x27, 0x35, 0x35), - (0x22, 0x78, 0x78), - ]; - for &(sid, nrc, expected) in cases { - assert_eq!(UdsResponse::new(&[0x7F, sid, nrc]).nrc(), Some(expected)); - } - } - - #[test] - fn test_positive_response_sids() { - assert!(!UdsResponse::new(&[0x50, 0x01, 0x00, 0x32]).is_negative()); - assert!(!UdsResponse::new(&[0x62, 0xF1, 0x90, 0x57]).is_negative()); - assert!(!UdsResponse::new(&[0x67, 0x01, 0x12, 0x34]).is_negative()); - assert!(!UdsResponse::new(&[0x6E, 0xF1, 0x90]).is_negative()); - assert!(!UdsResponse::new(&[0x7E, 0x00]).is_negative()); - } - #[test] fn test_default_com_params() { let com_params = ServiceResolver::default_com_params(0x1000, 0x0E80); @@ -258,10 +235,4 @@ mod tests { "CP_UniqueRespIdTable" ); } - - #[test] - fn test_empty_response() { - assert!(!UdsResponse::new(&[]).is_negative()); - assert_eq!(UdsResponse::new(&[]).nrc(), None); - } } diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs index c5f24f3..2877edb 100644 --- a/proxy-core/src/service_resolver/resolve.rs +++ b/proxy-core/src/service_resolver/resolve.rs @@ -15,22 +15,50 @@ //! Resolves incoming UDS DID values to the correct MDD service name //! using prefix lookup, request parameter metadata, and encoding probes. -use cda_core::EcuManager as InnerManager; +use cda_core::EcuManager as CdaEcuManager; use cda_interfaces::{ DynamicPlugin, EcuManager as EcuManagerTrait, HashMap, ServiceParameterMetadata, diagservices::{DiagServiceResponse, UdsPayloadData}, - service_ids, }; use cda_plugin_security::DefaultSecurityPluginData; use super::{ - CdaEcuManager, + ManagerHandle, uds_helpers::{ did_matches_compu_scales, extract_did_from_uds, find_did_param, make_diag_comm, make_service_payload, parse_u64_literal, }, + uds_service_ids, }; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServiceType { + /// `ReadDataByIdentifier` (SID 0x22). + Read, + /// `WriteDataByIdentifier` (SID 0x2E). + Write, +} + +impl ServiceType { + /// UDS service identifier byte. + #[must_use] + pub fn sid(self) -> u8 { + match self { + Self::Read => uds_service_ids::READ_DATA_BY_IDENTIFIER, + Self::Write => uds_service_ids::WRITE_DATA_BY_IDENTIFIER, + } + } + + /// Human-readable label for log messages. + #[must_use] + pub fn label(self) -> &'static str { + match self { + Self::Read => "READ", + Self::Write => "WRITE", + } + } +} + /// Successful result of DID-to-service resolution. pub struct ResolvedService { /// Matched MDD service name (e.g. `"RDBI_VIN"`). @@ -41,62 +69,32 @@ pub struct ResolvedService { } /// Resolves UDS DID values to MDD service names. -/// -/// Obtain an instance via -/// [`ServiceResolver::did_resolver()`](super::ServiceResolver::did_resolver). -#[derive(Clone)] pub struct DidResolver { - manager: CdaEcuManager, + manager: ManagerHandle, } impl DidResolver { - pub(super) fn new(manager: CdaEcuManager) -> Self { + /// Create a new resolver backed by the given manager handle. + pub fn new(manager: ManagerHandle) -> Self { Self { manager } } - /// Resolve the best-matching READ service for the given DID and raw UDS bytes. - pub async fn resolve_read_service( - &self, - did: u16, - uds_bytes: &[u8], - ) -> Option { - self.resolve_service(service_ids::READ_DATA_BY_IDENTIFIER, did, uds_bytes, "READ") - .await - } - - /// Resolve the best-matching WRITE service for the given DID and raw UDS bytes. - pub async fn resolve_write_service( + /// Resolve the best-matching service for a UDS DID request. + pub async fn resolve( &self, + service_type: ServiceType, did: u16, uds_bytes: &[u8], ) -> Option { - self.resolve_service( - service_ids::WRITE_DATA_BY_IDENTIFIER, - did, - uds_bytes, - "WRITE", - ) - .await - } - - /// Find the correct service for a given SID + DID. - /// - /// Delegates DID matching to `resolve_service_did`, then attempts - /// parse-validation via `convert_request_from_uds`. - async fn resolve_service( - &self, - sid: u8, - did: u16, - uds_bytes: &[u8], - label: &str, - ) -> Option { + let sid = service_type.sid(); + let label = service_type.label(); tracing::debug!("[MDD] {} DID 0x{:04X}", label, did); - let service_name = self.resolve_service_did(sid, did, uds_bytes, label).await?; + let service_name = self.resolve_service_did(sid, did, label).await?; // Attempt parse-validation to extract structured parameter data. let manager = self.manager.read().await; - let payload = make_service_payload(uds_bytes); + let payload: cda_interfaces::ServicePayload = make_service_payload(uds_bytes); let diag_comm = make_diag_comm(&service_name, sid); if let Ok(parsed) = manager @@ -138,13 +136,7 @@ impl DidResolver { // `did` is `u16`; `did >> 8` is at most 0xFF and `did & 0xFF` is at most 0xFF, // so both narrowing casts to `u8` are safe and can never truncate. #[allow(clippy::cast_possible_truncation)] - async fn resolve_service_did( - &self, - sid: u8, - did: u16, - _uds_bytes: &[u8], - label: &str, - ) -> Option { + async fn resolve_service_did(&self, sid: u8, did: u16, label: &str) -> Option { let manager = self.manager.read().await; // Step 1 + 2: prefix lookup and candidate list construction. @@ -153,7 +145,7 @@ impl DidResolver { // Step 3: match DID against each candidate's request metadata. for name in &candidates { - if self.match_candidate_did(&manager, name, sid, did).await { + if Self::match_candidate_did(&manager, name, sid, did).await { tracing::info!("[resolve_did] {} DID 0x{:04X} -> '{}'", label, did, name); return Some(name.clone()); } @@ -173,7 +165,7 @@ impl DidResolver { /// Returns `Some` with a single-element vec on a unique prefix match /// (fast path). Returns `None` when no candidates exist. fn build_did_candidates( - manager: &InnerManager, + manager: &CdaEcuManager, did_prefix: [u8; 3], sid: u8, did: u16, @@ -210,19 +202,19 @@ impl DidResolver { } let security_plugin: DynamicPlugin = Box::new(()); - let extra_names: Vec = match sid { - service_ids::READ_DATA_BY_IDENTIFIER => manager + let extra_names: Vec = if sid == uds_service_ids::READ_DATA_BY_IDENTIFIER { + manager .get_components_data_info(&security_plugin) .into_iter() .map(|c| c.id) - .collect(), - service_ids::WRITE_DATA_BY_IDENTIFIER => manager + .collect() + } else if sid == uds_service_ids::WRITE_DATA_BY_IDENTIFIER { + manager .get_components_configurations_info(&security_plugin) + .map(|v| v.into_iter().map(|c| c.id).collect()) .unwrap_or_default() - .into_iter() - .map(|c| c.id) - .collect(), - _ => Vec::new(), + } else { + Vec::new() }; for name in extra_names { if !candidates.contains(&name) { @@ -251,10 +243,9 @@ impl DidResolver { Some(candidates) } - /// Check whether `candidate_name` matches `did` via request parameter metadata. + /// Check if `candidate_name` matches `did` via request parameter metadata. async fn match_candidate_did( - &self, - manager: &InnerManager, + manager: &CdaEcuManager, candidate_name: &str, sid: u8, did: u16, @@ -303,7 +294,7 @@ impl DidResolver { /// Probe a service DID via request encoding for symbolic PHYS-CONST cases. async fn probe_service_did( - manager: &InnerManager, + manager: &CdaEcuManager, service_name: &str, sid: u8, params: &[ServiceParameterMetadata], @@ -356,11 +347,10 @@ impl DidResolver { #[cfg(test)] mod tests { - use cda_interfaces::service_ids; - - use super::super::uds_helpers::{did_matches_compu_scales, find_did_param, parse_u64_literal}; - - /// `parse_u64_literal` parses decimal and hexadecimal strings. + use super::super::{ + uds_helpers::{did_matches_compu_scales, find_did_param, parse_u64_literal}, + uds_service_ids, + }; #[test] fn test_parse_u64_literal_decimal() { assert_eq!(parse_u64_literal("0"), Some(0)); @@ -371,7 +361,6 @@ mod tests { fn test_parse_u64_literal_hex() { assert_eq!(parse_u64_literal("0xF103"), Some(0xF103)); assert_eq!(parse_u64_literal("0XFF"), Some(0xFF)); - // bare hex fallback (no prefix) assert_eq!(parse_u64_literal("F103"), Some(0xF103)); } @@ -381,7 +370,6 @@ mod tests { assert_eq!(parse_u64_literal("abc xyz"), None); } - /// `did_matches_compu_scales` returns true when DID falls in any range. #[test] fn test_did_matches_compu_scales_in_range() { use cda_interfaces::CompuScaleInfo; @@ -397,44 +385,88 @@ mod tests { assert!(!did_matches_compu_scales(&scales, 0xF200)); } - /// `find_did_param` skips the SID `CodedConst` and returns the next parameter. #[test] fn test_find_did_param_skips_sid() { use cda_interfaces::{ParameterTypeMetadata, ServiceParameterMetadata}; - let sid = service_ids::READ_DATA_BY_IDENTIFIER; // 0x22 + let sid = uds_service_ids::READ_DATA_BY_IDENTIFIER; let meta = vec![ ServiceParameterMetadata { name: "SID".to_string(), semantic: None, param_type: ParameterTypeMetadata::CodedConst { - coded_value: "34".to_string(), // 0x22 + coded_value: "34".to_string(), }, }, ServiceParameterMetadata { name: "DID".to_string(), semantic: Some("DATA-IDENTIFIER".to_string()), param_type: ParameterTypeMetadata::CodedConst { - coded_value: "61824".to_string(), // 0xF190 + coded_value: "61824".to_string(), + }, + }, + ]; + let did_param = find_did_param(&meta, sid); + assert!(did_param.is_some()); + assert_eq!(did_param.unwrap().name, "DID"); + } + + #[test] + fn test_service_type_sid() { + assert_eq!(super::ServiceType::Read.sid(), 0x22); + assert_eq!(super::ServiceType::Write.sid(), 0x2E); + } + + #[test] + fn test_service_type_label() { + assert_eq!(super::ServiceType::Read.label(), "READ"); + assert_eq!(super::ServiceType::Write.label(), "WRITE"); + } + + #[test] + fn test_find_did_param_phys_const() { + use cda_interfaces::{ParameterTypeMetadata, ServiceParameterMetadata}; + let sid = uds_service_ids::READ_DATA_BY_IDENTIFIER; + let meta = vec![ + ServiceParameterMetadata { + name: "SID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "34".to_string(), + }, + }, + ServiceParameterMetadata { + name: "DID".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::PhysConst { + phys_constant_value: "VIN".to_string(), + coded_value: Some(0xF190), }, }, ]; - let param = find_did_param(&meta, sid); - assert!(param.is_some()); - assert_eq!(param.unwrap().name, "DID"); + let did_param = find_did_param(&meta, sid); + assert!(did_param.is_some()); + assert_eq!(did_param.unwrap().name, "DID"); } - /// `find_did_param` returns `None` when no DID parameter is present. #[test] - fn test_find_did_param_none_when_only_sid() { + fn test_find_did_param_no_sid_match() { use cda_interfaces::{ParameterTypeMetadata, ServiceParameterMetadata}; - let sid = service_ids::READ_DATA_BY_IDENTIFIER; let meta = vec![ServiceParameterMetadata { - name: "SID".to_string(), + name: "ONLY_PARAM".to_string(), semantic: None, - param_type: ParameterTypeMetadata::CodedConst { - coded_value: "34".to_string(), + param_type: ParameterTypeMetadata::PhysConst { + phys_constant_value: "VALUE".to_string(), + coded_value: None, }, }]; - assert!(find_did_param(&meta, sid).is_none()); + let did_param = find_did_param(&meta, 0x22); + assert!(did_param.is_some()); + assert_eq!(did_param.unwrap().name, "ONLY_PARAM"); + } + + #[test] + fn test_find_did_param_empty_metadata() { + let meta: Vec = vec![]; + assert!(find_did_param(&meta, 0x22).is_none()); } } diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index 284b6be..efe52a8 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -12,11 +12,8 @@ //! UDS response building and validation. //! -//! [`ResponseEncoder`] encodes SOVD JSON data into UDS response bytes using -//! MDD parameter metadata. It depends on [`MetadataProvider`] for enriched -//! response metadata queries. - -use std::sync::Arc; +//! [`ResponseEncoder`] encodes SOVD JSON data into UDS response bytes +//! using MDD parameter metadata. use cda_interfaces::{ DiagServiceError, EcuManager as EcuManagerTrait, HashMap, UDS_ID_RESPONSE_BITMASK, @@ -24,7 +21,7 @@ use cda_interfaces::{ }; use super::{ - CdaEcuManager, MetadataProvider, UDS_POSITIVE_RESPONSE_MIN_SIZE, + ManagerHandle, MetadataProvider, UDS_POSITIVE_RESPONSE_MIN_SIZE, uds_helpers::{ encode_unsigned_be, encode_value_at, find_mux_case_prefix, make_diag_comm, make_service_payload, value_to_bytes, @@ -32,15 +29,14 @@ use super::{ }; /// Encodes SOVD JSON data into UDS response bytes using MDD metadata. -#[derive(Clone)] pub struct ResponseEncoder { - manager: CdaEcuManager, + manager: ManagerHandle, metadata: MetadataProvider, } impl ResponseEncoder { - pub(super) fn new(manager: CdaEcuManager) -> Self { - let metadata = MetadataProvider::new(Arc::clone(&manager)); + /// Create a new response encoder. + pub fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { Self { manager, metadata } } diff --git a/proxy-core/src/service_resolver/uds_helpers.rs b/proxy-core/src/service_resolver/uds_helpers.rs index d47b1da..40bd778 100644 --- a/proxy-core/src/service_resolver/uds_helpers.rs +++ b/proxy-core/src/service_resolver/uds_helpers.rs @@ -13,48 +13,13 @@ //! UDS helper functions and types. //! //! Pure functions used across the `service_resolver` module: DID extraction, -//! MUX-case matching, value encoding, payload construction, and -//! [`UdsResponse`] for structured access to UDS response bytes. +//! MUX-case matching, value encoding, and payload construction. use cda_interfaces::{ CompuScaleInfo, DiagComm, DiagCommType, ResponseParameterInfo, ServiceParameterMetadata, - ServicePayload, service_ids, + ServicePayload, }; -use super::UDS_NEGATIVE_RESPONSE_MIN_LEN; - -/// Typed accessor for raw UDS response bytes. -pub struct UdsResponse<'a>(&'a [u8]); - -impl<'a> UdsResponse<'a> { - /// Wrap raw UDS response bytes. - #[must_use] - pub fn new(bytes: &'a [u8]) -> Self { - Self(bytes) - } - - /// Service Identifier byte of the response. - #[must_use] - pub fn sid(&self) -> Option { - self.0.first().copied() - } - - /// Returns `true` if this is a negative response (`0x7F` + SID + NRC). - #[must_use] - pub fn is_negative(&self) -> bool { - self.0.len() >= UDS_NEGATIVE_RESPONSE_MIN_LEN - && self.sid() == Some(service_ids::NEGATIVE_RESPONSE) - } - - /// Extract the Negative Response Code from a negative response. - /// - /// Returns `None` if this is not a negative response or the byte is absent. - #[must_use] - pub fn nrc(&self) -> Option { - self.is_negative().then(|| self.0.get(2).copied()).flatten() - } -} - /// Extract the 16-bit DID from UDS payload bytes at offset 1โ€“2. /// /// Returns `None` if the slice has fewer than 3 bytes. @@ -102,7 +67,7 @@ pub(super) fn encode_unsigned_be(num: u64) -> Vec { /// MDD stores MUX case limits as strings that may be float-formatted /// (e.g. `"61699.0"`) or integer-formatted (e.g. `"61699"`). #[must_use] -pub fn parse_mux_coded_value(coded_value: &str) -> Option { +pub(super) fn parse_mux_coded_value(coded_value: &str) -> Option { let trimmed = coded_value.trim(); // Try integer parsing first; fall back to float (MDD may store values like "61699.0"). // The bounds check (`>= 0.0` and `<= u64::MAX as f64`) ensures the value fits before @@ -166,7 +131,7 @@ pub fn find_mux_case_prefix(meta: &[ResponseParameterInfo], did: u16) -> Option< /// Uses exact (not floor) matching because this is for cross-service sibling /// selection where different MUX DOPs can have overlapping ranges. #[must_use] -pub fn has_mux_case_for_did_exact(meta: &[ResponseParameterInfo], did: u16) -> bool { +pub(super) fn has_mux_case_for_did_exact(meta: &[ResponseParameterInfo], did: u16) -> bool { let did_val = u64::from(did); meta.iter().any(|p| { if let Some(_case_name) = p.name.strip_prefix("__mux_case__/") @@ -392,36 +357,6 @@ mod tests { assert!(payload.new_security.is_none()); } - #[test] - fn test_diag_comm_type() { - use cda_interfaces::service_ids; - - assert!(matches!( - diag_comm_type(service_ids::WRITE_DATA_BY_IDENTIFIER), - DiagCommType::Configurations - )); - assert!(matches!( - diag_comm_type(service_ids::READ_DATA_BY_IDENTIFIER), - DiagCommType::Data - )); - assert!(matches!( - diag_comm_type(service_ids::SESSION_CONTROL), - DiagCommType::Modes - )); - assert!(matches!( - diag_comm_type(service_ids::TESTER_PRESENT), - DiagCommType::Data - )); - assert!(matches!( - diag_comm_type(service_ids::ROUTINE_CONTROL), - DiagCommType::Operations - )); - assert!(matches!( - diag_comm_type(service_ids::CLEAR_DIAGNOSTIC_INFORMATION), - DiagCommType::Faults - )); - } - #[test] fn test_parse_mux_coded_value() { assert_eq!(parse_mux_coded_value("61699"), Some(61699)); From 1bcaf23afcda805702d59d2fa700e4b02bfddd82 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 12 May 2026 14:24:04 +0200 Subject: [PATCH 11/33] refactor: encapsulate ServiceResolver internals behind facade methods Signed-off-by: Arvind Rathod --- Cargo.lock | 389 +++++++++ Cargo.toml | 1 + .../service_resolver_class_diagram.puml | 46 +- .../service_resolver_class_diagram.svg | 2 +- .../service_resolver_sequence_diagram.puml | 111 +-- .../service_resolver_sequence_diagram.svg | 2 +- proxy-core/Cargo.toml | 2 + proxy-core/src/config.rs | 757 ++++++++++++------ proxy-core/src/lib.rs | 15 +- proxy-core/src/service_resolver/metadata.rs | 57 +- proxy-core/src/service_resolver/mod.rs | 77 +- proxy-core/src/service_resolver/resolve.rs | 8 +- proxy-core/src/service_resolver/response.rs | 323 ++++---- 13 files changed, 1251 insertions(+), 539 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 322ab65..3c84452 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,6 +46,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + [[package]] name = "anyhow" version = "1.0.102" @@ -312,6 +362,52 @@ dependencies = [ "windows-link", ] +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "const-oid" version = "0.9.6" @@ -414,6 +510,17 @@ dependencies = [ "subtle", ] +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "dyn-clone" version = "1.0.20" @@ -556,6 +663,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures" version = "0.3.32" @@ -828,12 +944,115 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + [[package]] name = "id-arena" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indexmap" version = "2.14.0" @@ -846,6 +1065,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.14.0" @@ -927,6 +1152,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + [[package]] name = "lock_api" version = "0.4.14" @@ -1065,6 +1296,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "ouroboros" version = "0.18.5" @@ -1205,6 +1442,15 @@ version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -1320,12 +1566,14 @@ dependencies = [ "cda-database", "cda-interfaces", "cda-plugin-security", + "clap", "serde", "serde_json", "thiserror", "tokio", "toml", "tracing", + "url", ] [[package]] @@ -1747,12 +1995,24 @@ dependencies = [ "der", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.27.2" @@ -1797,6 +2057,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -1861,6 +2132,16 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tokio" version = "1.52.1" @@ -2003,6 +2284,31 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.23.1" @@ -2297,6 +2603,12 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + [[package]] name = "xz2" version = "0.1.7" @@ -2312,6 +2624,29 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.48" @@ -2332,12 +2667,66 @@ dependencies = [ "syn", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + [[package]] name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index b74d56a..3f3c127 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ toml = "0.9.8" # ---- networking crates ---- reqwest = { version = "0.12.24", default-features = false } +url = { version = "2", features = ["serde"] } # ---- tracing & logging crates ---- tracing = "0.1.41" diff --git a/docs/service_resolver/service_resolver_class_diagram.puml b/docs/service_resolver/service_resolver_class_diagram.puml index ee38b4b..82e3c5f 100644 --- a/docs/service_resolver/service_resolver_class_diagram.puml +++ b/docs/service_resolver/service_resolver_class_diagram.puml @@ -19,8 +19,8 @@ skinparam classFontSize 12 ' โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ' proxy-core::service_resolver -' Facade (ServiceResolver) owns CdaEcuManager and ecu_name. -' Sub-components are public fields (not accessors): +' ServiceResolver owns CdaEcuManager. +' Sub-components are private fields, exposed via delegating methods: ' resolver : DidResolver (resolve.rs) -- DID-to-service resolution ' encoder : ResponseEncoder (response.rs) -- UDS response encoding ' metadata : MetadataProvider (metadata.rs) -- MDD parameter queries @@ -30,46 +30,48 @@ package "proxy-core::service_resolver" { class ServiceResolver <> { - manager : CdaEcuManager - - ecu_name : String - + resolver : DidResolver - + encoder : ResponseEncoder - + metadata : MetadataProvider + - resolver : DidResolver + - encoder : ResponseEncoder + - metadata : MetadataProvider == mod.rs -- construction == - + {static} <> new(ecu_name, db, logical, tester) : Result + + {static} <> new(db, logical, tester) : Result - {static} <> activate_base_variant(manager) : Result<()> - {static} default_com_params(logical, tester: u16) : ComParams - + ecu_name() : &str + == mod.rs -- public API == + + <> resolve(service_type, did, uds) : Option + + <> build_response(name, sid, did, data) : Result> + + <> get_response_metadata(name, did) : Result> } together { - class DidResolver { + class DidResolver <> { - manager : CdaEcuManager == resolve.rs -- DID --> service name == - + <> resolve(service_type, did, uds) : Option + ~ <> resolve(service_type, did, uds) : Option - <> resolve_service_did(sid, did, label) : Option - {static} build_did_candidates(manager, did_prefix, sid, did, label) : Option> - {static} <> match_candidate_did(manager, name, sid, did) : bool - {static} <> probe_service_did(manager, name, sid, meta) : Option } - class ResponseEncoder { + class ResponseEncoder <> { - manager : CdaEcuManager - metadata : MetadataProvider == response.rs -- encode UDS response == - + <> build_response(name, sid, did, data) : Result> + ~ <> build_response(name, sid, did, data) : Result> - <> encode_response_from_metadata(name, sid, did, data) : Option<(Vec, String)> - <> validate_response(name, sid, bytes) : () } - class MetadataProvider { + class MetadataProvider <> { - manager : CdaEcuManager == metadata.rs -- MDD parameter queries == - + <> get_request_params(name) : Result> - + <> get_response_params(name) : Result> - + <> get_enriched_response_metadata(name, did) : Result> - + <> get_enriched_response_metadata_with_source(name, did) : Result<(Vec, String)> - + <> lookup_service_names_by_sid(sid) : Result> - + <> get_mux_cases_for_service(name) : Result> + ~ <> get_request_params(name) : Result> + ~ <> get_response_params(name) : Result> + ~ <> get_enriched_response_metadata(name, did) : Result> + ~ <> get_enriched_response_metadata_with_source(name, did) : Result<(Vec, String)> + ~ <> lookup_service_names_by_sid(sid) : Result> + ~ <> get_response_metadata(name, did) : Result> } } @@ -122,9 +124,9 @@ package "proxy-core::service_resolver" { + params : Map } - ServiceResolver *--> DidResolver : resolver (pub field) - ServiceResolver *--> ResponseEncoder : encoder (pub field) - ServiceResolver *--> MetadataProvider : metadata (pub field) + ServiceResolver *--> DidResolver : resolver (private) + ServiceResolver *--> ResponseEncoder : encoder (private) + ServiceResolver *--> MetadataProvider : metadata (private) ResponseEncoder o--> MetadataProvider : holds (explicit dependency) DidResolver ..> uds_helpers : uses ResponseEncoder ..> uds_helpers : uses diff --git a/docs/service_resolver/service_resolver_class_diagram.svg b/docs/service_resolver/service_resolver_class_diagram.svg index 83190e5..550c25d 100644 --- a/docs/service_resolver/service_resolver_class_diagram.svg +++ b/docs/service_resolver/service_resolver_class_diagram.svg @@ -1 +1 @@ -Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-ecu_name : String+resolver : DidResolver+encoder : ResponseEncoder+metadata : MetadataProvider+«async» new(ecu_name, db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParams+ecu_name() : &strmod.rs -- constructionDidResolver-manager : CdaEcuManager+«async» resolve(service_type, did, uds) : Option<ResolvedService>-«async» resolve_service_did(sid, did, label) : Option<String>-build_did_candidates(manager, did_prefix, sid, did, label) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service nameResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider+«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS responseMetadataProvider-manager : CdaEcuManager+«async» get_request_params(name) : Result<Vec<Param>>+«async» get_response_params(name) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>+«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>+«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>+«async» get_mux_cases_for_service(name) : Result<Vec<MuxCase>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rs.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>resolver (pub field)encoder (pub field)metadata (pub field)holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. +Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-resolver : DidResolver-encoder : ResponseEncoder-metadata : MetadataProvider+«async» new(db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParamsmod.rs -- construction+«async» resolve(service_type, did, uds) : Option<ResolvedService>+«async» build_response(name, sid, did, data) : Result<Vec<u8>>+«async» get_response_metadata(name, did) : Result<Vec<RespParam>>mod.rs -- public API«crate-internal»DidResolver-manager : CdaEcuManager~«async» resolve(service_type, did, uds) : Option<ResolvedService>-«async» resolve_service_did(sid, did, label) : Option<String>-build_did_candidates(manager, did_prefix, sid, did, label) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service name«crate-internal»ResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider~«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS response«crate-internal»MetadataProvider-manager : CdaEcuManager~«async» get_request_params(name) : Result<Vec<Param>>~«async» get_response_params(name) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>~«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>~«async» get_response_metadata(name, did) : Result<Vec<RespParam>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rs.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>resolver (private)encoder (private)metadata (private)holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. \ No newline at end of file diff --git a/docs/service_resolver/service_resolver_sequence_diagram.puml b/docs/service_resolver/service_resolver_sequence_diagram.puml index 8c234fb..d7b3bef 100644 --- a/docs/service_resolver/service_resolver_sequence_diagram.puml +++ b/docs/service_resolver/service_resolver_sequence_diagram.puml @@ -13,7 +13,7 @@ title ServiceResolver: DID Resolution & Response Building\nEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd) actor "SovdDiagHandler\n(proxy-sovd)" as Client -participant "ServiceResolver\n(mod.rs facade)" as Facade +participant "ServiceResolver\n(mod.rs)" as Facade participant "DidResolver\n(resolve.rs)" as Resolver participant "MetadataProvider\n(metadata.rs)" as Meta participant "ResponseEncoder\n(response.rs)" as Resp @@ -21,76 +21,83 @@ participant "CDA EcuManager" as CDA == READ Service Resolution == -Client -> Resolver: resolve(ServiceType::Read, did, uds_bytes) -activate Resolver +Client -> Facade: resolve(ServiceType::Read, did, uds_bytes) +activate Facade - Resolver -> Resolver: resolve_service_did(sid=0x22, did, label="READ") + Facade -> Resolver: resolve(service_type, did, uds_bytes) activate Resolver - Resolver -> CDA: lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO]) - activate CDA - CDA --> Resolver: matching_services - deactivate CDA - - Resolver -> Resolver: build_did_candidates(manager, did_prefix, sid, did, label) + Resolver -> Resolver: resolve_service_did(sid=0x22, did, label="READ") activate Resolver - Resolver -> CDA: get_components_data_info() or\nget_components_configurations_info() - activate CDA - CDA --> Resolver: all SID-matching service names - deactivate CDA - deactivate Resolver - loop for each candidate service name - Resolver -> Resolver: match_candidate_did(manager, name, sid, did) - activate Resolver + Resolver -> CDA: lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO]) + activate CDA + CDA --> Resolver: matching_services + deactivate CDA - Resolver -> CDA: get_request_parameter_metadata(candidate_name) + Resolver -> Resolver: build_did_candidates(manager, did_prefix, sid, did, label) + activate Resolver + Resolver -> CDA: get_components_data_info() or\nget_components_configurations_info() activate CDA - CDA --> Resolver: param metadata + CDA --> Resolver: all SID-matching service names deactivate CDA + deactivate Resolver - alt CodedConst DID - Resolver -> Resolver: parse_u64_literal(coded_value) - else PhysConst DID (coded_value absent) - Resolver -> Resolver: probe_service_did(manager, name, sid, meta) + loop for each candidate service name + Resolver -> Resolver: match_candidate_did(manager, name, sid, did) activate Resolver - Resolver -> CDA: create_uds_payload(diag_comm, plugin, params) + + Resolver -> CDA: get_request_parameter_metadata(candidate_name) activate CDA - CDA --> Resolver: encoded payload + CDA --> Resolver: param metadata deactivate CDA - Resolver -> Resolver: extract_did_from_uds(payload.data) + + alt CodedConst DID + Resolver -> Resolver: parse_u64_literal(coded_value) + else PhysConst DID (coded_value absent) + Resolver -> Resolver: probe_service_did(manager, name, sid, meta) + activate Resolver + Resolver -> CDA: create_uds_payload(diag_comm, plugin, params) + activate CDA + CDA --> Resolver: encoded payload + deactivate CDA + Resolver -> Resolver: extract_did_from_uds(payload.data) + deactivate Resolver + else Value DID + Resolver -> Resolver: did_matches_compu_scales(scales, did) + end + deactivate Resolver - else Value DID - Resolver -> Resolver: did_matches_compu_scales(scales, did) end - deactivate Resolver - end - - deactivate Resolver + deactivate Resolver - Resolver -> CDA: convert_request_from_uds(diag_comm, payload, strict=true) - activate CDA - CDA --> Resolver: parsed JSON params - deactivate CDA + Resolver -> CDA: convert_request_from_uds(diag_comm, payload, strict=true) + activate CDA + CDA --> Resolver: parsed JSON params + deactivate CDA -deactivate Resolver + Resolver --> Facade: Option + deactivate Resolver -Resolver --> Client: Option -deactivate Resolver +Facade --> Client: Option +deactivate Facade == WRITE Service Handling == note right of Client Similar flow for WRITE services - client calls resolver.resolve(ServiceType::Write, did, uds_bytes) + client calls facade.resolve(ServiceType::Write, did, uds_bytes) which uses sid=0x2E and get_components_configurations_info() end note == Response Building == -Client -> Resp: build_response(service_name, sid, did, response_data) -activate Resp +Client -> Facade: build_response(service_name, sid, did, response_data) +activate Facade + + Facade -> Resp: build_response(service_name, sid, did, response_data) + activate Resp Resp -> Resp: encode_response_from_metadata(service_name, sid, did, data) activate Resp @@ -146,14 +153,18 @@ alt DEBUG level enabled deactivate Resp end -Resp --> Client: Result, DiagServiceError> +Resp --> Facade: Result, DiagServiceError> deactivate Resp +Facade --> Client: Result, DiagServiceError> +deactivate Facade + note right of Client - - **ServiceResolver (mod.rs)**: construction, - variant activation. Sub-components: - resolver, encoder, metadata + - **ServiceResolver (mod.rs)**: public entry point โ€” + construction, variant activation, and delegating + resolve() / build_response() / get_response_metadata() + to internal sub-components. - **DidResolver (resolve.rs)**: DID -> service resolution, candidate building, metadata matching - **ResponseEncoder (response.rs)**: UDS response encoding, @@ -164,9 +175,9 @@ note right of Client encoding, decoding, MUX matching **Data flow:** - Caller accesses resolver, encoder, metadata as - direct pub fields on ServiceResolver, then calls methods - on those sub-components directly. + Caller invokes facade methods on ServiceResolver. + ServiceResolver delegates internally to sub-components + (all private: resolver, encoder, metadata). ResponseEncoder holds MetadataProvider internally for the cross-module enrichment dependency. end note diff --git a/docs/service_resolver/service_resolver_sequence_diagram.svg b/docs/service_resolver/service_resolver_sequence_diagram.svg index e61421a..2fcfb0e 100644 --- a/docs/service_resolver/service_resolver_sequence_diagram.svg +++ b/docs/service_resolver/service_resolver_sequence_diagram.svg @@ -1 +1 @@ -ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs facade)ServiceResolver(mod.rs facade)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve(ServiceType::Read, did, uds_bytes)resolve_service_did(sid=0x22, did, label="READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, did_prefix, sid, did, label)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesclient calls resolver.resolve(ServiceType::Write, did, uds_bytes)which uses sid=0x2E and get_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): construction,variant activation. Sub-components:resolver, encoder, metadata-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure free functions --encoding, decoding, MUX matching Data flow:Caller accesses resolver, encoder, metadata asdirect pub fields on ServiceResolver, then calls methodson those sub-components directly.ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. +ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs)ServiceResolver(mod.rs)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve(ServiceType::Read, did, uds_bytes)resolve(service_type, did, uds_bytes)resolve_service_did(sid=0x22, did, label="READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, did_prefix, sid, did, label)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>Option<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesclient calls facade.resolve(ServiceType::Write, did, uds_bytes)which uses sid=0x2E and get_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)build_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError>Result<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): public entry point —construction, variant activation, and delegatingresolve() / build_response() / get_response_metadata()to internal sub-components.-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure free functions --encoding, decoding, MUX matching Data flow:Caller invokes facade methods on ServiceResolver.ServiceResolver delegates internally to sub-components(all private: resolver, encoder, metadata).ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. \ No newline at end of file diff --git a/proxy-core/Cargo.toml b/proxy-core/Cargo.toml index e8f76e0..2f8ed1c 100644 --- a/proxy-core/Cargo.toml +++ b/proxy-core/Cargo.toml @@ -28,6 +28,8 @@ serde_json = { workspace = true } tokio = { workspace = true, features = ["full"] } tracing = { workspace = true } toml = { workspace = true } +url = { workspace = true } +clap = { workspace = true, features = ["derive", "env"] } [lints] workspace = true diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index 91ad685..4d4d6b9 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -12,33 +12,17 @@ use std::{ net::{IpAddr, Ipv4Addr}, - path::Path, + path::PathBuf, }; +use clap::Parser; use serde::{Deserialize, Deserializer, de}; +use url::Url; use crate::error::{ProxyError, Result}; -/// Required byte length for EID and GID fields per ISO 13400-2. -const EID_GID_BYTE_LENGTH: usize = 6; - -// Default values for ServerConfig. -const DEFAULT_DOIP_PORT: u16 = 13400; -const DEFAULT_MAX_CONNECTIONS: usize = 10; -/// `DoIP` source address (tester logical address used in response messages). -const DEFAULT_SOURCE_ADDRESS: u16 = 0x0E80; - -// Default values for SovdConfig. -const DEFAULT_GATEWAY_URL: &str = "http://localhost:20002"; -const DEFAULT_CLIENT_ID: &str = "uds2sovd_proxy"; -const DEFAULT_CLIENT_SECRET: &str = "test_secret"; -const DEFAULT_TIMEOUT_MS: u64 = 5000; -const DEFAULT_API_VERSION: &str = "v15"; - -// Default values for EcuConfig. -const DEFAULT_ECU_NAME: &str = "ECU"; -/// Top-level proxy configuration loaded from a TOML file. -#[derive(Debug, Clone, Deserialize, Default)] +#[derive(Deserialize, Default)] +#[serde(default)] pub struct Config { /// `DoIP` server settings (port, bind address, source address). pub server: ServerConfig, @@ -50,23 +34,33 @@ pub struct Config { pub logging: LoggingConfig, } -/// `DoIP` server configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Deserialize)] +#[serde(default)] pub struct ServerConfig { - /// TCP port for the `DoIP` server (default: 13400). + /// TCP port for the `DoIP` server (default: 13 400). #[serde(deserialize_with = "deserialize_nonzero_u16")] pub doip_port: u16, - /// IP address to bind the server socket to. - #[serde(deserialize_with = "deserialize_ip_addr")] + /// IP address to bind the server socket to (default: `0.0.0.0`). pub bind_address: IpAddr, - /// Maximum number of concurrent connections. + /// Maximum number of concurrent connections (default: 10). #[serde(deserialize_with = "deserialize_max_connections")] pub max_connections: usize, - /// `DoIP` source address used in response messages. + /// `DoIP` source address used in response messages (default: `0x0E80`). #[serde(deserialize_with = "deserialize_nonzero_u16")] pub source_address: u16, } +impl Default for ServerConfig { + fn default() -> Self { + Self { + doip_port: 13_400, + bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), + max_connections: 10, + source_address: 0x0E80, + } + } +} + fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -77,16 +71,6 @@ fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( Ok(v) } -/// Deserialize IP address string into `std::net::IpAddr`. -fn deserialize_ip_addr<'de, D: Deserializer<'de>>( - deserializer: D, -) -> std::result::Result { - let s = String::deserialize(deserializer)?; - s.parse::() - .map_err(|_| de::Error::custom(format!("invalid IP address: {s}"))) -} - -/// Reject zero during deserialization for `usize` fields. fn deserialize_max_connections<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -97,22 +81,11 @@ fn deserialize_max_connections<'de, D: Deserializer<'de>>( Ok(v) } -/// Reject empty gateway URL strings during deserialization. -fn deserialize_nonempty_gateway_url<'de, D: Deserializer<'de>>( - deserializer: D, -) -> std::result::Result { - let s = String::deserialize(deserializer)?; - if s.is_empty() { - return Err(de::Error::custom("gateway_url must not be empty")); - } - Ok(s) -} -/// SOVD gateway connection configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Clone, Deserialize)] +#[serde(default)] pub struct SovdConfig { /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). - #[serde(deserialize_with = "deserialize_nonempty_gateway_url")] - pub gateway_url: String, + pub gateway_url: Url, /// `OAuth2` client ID for gateway authentication. pub client_id: String, /// `OAuth2` client secret for gateway authentication. @@ -122,291 +95,541 @@ pub struct SovdConfig { /// SOVD API version path segment (e.g. `v15`). pub api_version: String, /// Whether to request inline schema in data responses. - #[serde(default = "SovdConfig::default_include_schema")] pub include_schema: bool, /// When `true`, bypass HTTP calls and generate synthetic responses. - #[serde(default)] pub mock_gateway: bool, } -impl SovdConfig { - fn default_include_schema() -> bool { - true +impl Default for SovdConfig { + fn default() -> Self { + Self { + gateway_url: "http://localhost:20002" + .parse() + .expect("hard-coded URL is always valid"), + client_id: "uds2sovd_proxy".into(), + client_secret: "test_secret".into(), + timeout_ms: 5_000, + api_version: "v15".into(), + include_schema: true, + mock_gateway: true, + } + } +} + +#[derive(Clone, Copy, Deserialize)] +pub struct EidGid([u8; 6]); + +impl EidGid { + fn is_all_zeros(self) -> bool { + self.0 == [0u8; 6] + } +} + +impl Default for EidGid { + fn default() -> Self { + Self([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]) } } -/// ECU identity and addressing configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Deserialize)] +#[serde(default)] pub struct EcuConfig { /// Default ECU name used for SOVD component path. pub default_name: String, /// ISO 13400 logical address of the target ECU. #[serde(deserialize_with = "deserialize_nonzero_u16")] pub logical_address: u16, - /// 6-byte Entity Identification (MAC address). - pub eid: [u8; EID_GID_BYTE_LENGTH], + /// 6-byte Entity Identification + pub eid: EidGid, /// 6-byte Group Identification. - pub gid: [u8; EID_GID_BYTE_LENGTH], + pub gid: EidGid, +} + +impl Default for EcuConfig { + fn default() -> Self { + Self { + default_name: "ECU".into(), + logical_address: 0x0001, + eid: EidGid::default(), + gid: EidGid::default(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum LogLevel { + Error, + Warn, + #[default] + Info, + Debug, + Trace, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum LogFormat { + /// Human-readable coloured output (default). + #[default] + Pretty, + /// Machine-readable JSON (suitable for log aggregators). + Json, } /// Logging output configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Deserialize, Default)] +#[serde(default)] pub struct LoggingConfig { - /// Log level filter (e.g. `info`, `debug`, `trace`). - pub level: String, - /// Output format: `pretty` (default) or `json`. - pub format: String, + /// Log level filter. + pub level: LogLevel, + /// Output format. + pub format: LogFormat, +} + +/// Any flag set here overrides the corresponding value from the TOML file. +#[derive(Parser)] +#[command(name = "uds2sovd-proxy", version)] +pub struct Cli { + /// Path to the TOML configuration file. + #[arg( + short, + long, + value_name = "FILE", + env = "PROXY_CONFIG", + default_value = "config/config.toml" + )] + pub config: PathBuf, + + /// Override the IP address to bind to. + #[arg(long, value_name = "ADDR", env = "PROXY_BIND_ADDRESS")] + pub bind_address: Option, + + /// Override the SOVD gateway URL. + #[arg(long, value_name = "URL", env = "PROXY_GATEWAY_URL")] + pub gateway_url: Option, + + /// Enable mock gateway mode (no real HTTP calls). + #[arg(long, env = "PROXY_MOCK_GATEWAY")] + pub mock_gateway: bool, + + /// Override the log level. + #[arg(long, value_enum, value_name = "LEVEL", env = "PROXY_LOG_LEVEL")] + pub log_level: Option, + + /// Override the log output format. + #[arg(long, value_enum, value_name = "FORMAT", env = "PROXY_LOG_FORMAT")] + pub log_format: Option, + + /// MDD file to load (absolute path, or filename resolved under `--mdd-dir`). + #[arg(short, long)] + pub mdd_file: PathBuf, + + /// Directory searched when `--mdd-file` is a relative filename. + #[arg(long, default_value = "testcontainer/mdd")] + pub mdd_dir: PathBuf, } impl Config { - /// Load configuration from TOML file + /// Build a fully-validated [`Config`] by layering defaults, a TOML file, + /// and CLI overrides. + /// + /// # Layer order + /// 1. [`Default`] values + /// 2. TOML file at the path given by `cli.config` + /// 3. CLI flags + /// + /// # Errors + /// Returns [`ProxyError::Config`] if the TOML file cannot be read/parsed + /// or if the merged configuration fails validation. + pub fn load(cli: &Cli) -> Result { + // defaults + TOML file + let mut config = if cli.config.exists() { + Self::from_file(&cli.config)? + } else { + Self::default() + }; + + // CLI overrides + if let Some(addr) = cli.bind_address { + config.server.bind_address = addr; + } + if let Some(ref url) = cli.gateway_url { + config.sovd.gateway_url = url.clone(); + } + if cli.mock_gateway { + config.sovd.mock_gateway = true; + } + if let Some(level) = cli.log_level { + config.logging.level = level; + } + if let Some(format) = cli.log_format { + config.logging.format = format; + } + + config.validate()?; + Ok(config) + } + + /// Load and validate configuration from a TOML file (without CLI overrides). /// /// # Errors - /// Returns an error if the file cannot be read or parsed. - pub fn from_file>(path: P) -> Result { + /// Returns [`ProxyError::Config`] if the file cannot be read, parsed, or + /// if the resulting configuration fails validation. + pub fn from_file>(path: P) -> Result { + let path = path.as_ref(); let content = std::fs::read_to_string(path) - .map_err(|e| ProxyError::Config(format!("Failed to read config file: {e}")))?; + .map_err(|e| ProxyError::Config(format!("cannot read `{}`: {e}", path.display())))?; - toml::from_str(&content) - .map_err(|e| ProxyError::Config(format!("Failed to parse config: {e}"))) + let config: Self = toml::from_str(&content) + .map_err(|e| ProxyError::Config(format!("cannot parse `{}`: {e}", path.display())))?; + + config.validate()?; + Ok(config) } -} -impl Default for ServerConfig { - fn default() -> Self { - Self { - doip_port: DEFAULT_DOIP_PORT, - bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), - max_connections: DEFAULT_MAX_CONNECTIONS, - source_address: DEFAULT_SOURCE_ADDRESS, + /// Validate the fully-merged configuration. + fn validate(&self) -> Result<()> { + let mut errors: Vec = Vec::new(); + + if self.server.max_connections == 0 { + errors.push("[server] max_connections must be greater than zero".into()); + } + if self.sovd.client_id.is_empty() { + errors.push("[sovd] client_id must not be empty".into()); + } + if self.sovd.api_version.is_empty() { + errors.push("[sovd] api_version must not be empty".into()); + } + if self.ecu.default_name.is_empty() { + errors.push("[ecu] default_name must not be empty".into()); + } + if self.ecu.eid.is_all_zeros() { + errors.push("[ecu] eid must not be all zeros".into()); + } + if self.ecu.gid.is_all_zeros() { + errors.push("[ecu] gid must not be all zeros".into()); } - } -} -impl Default for SovdConfig { - fn default() -> Self { - Self { - gateway_url: DEFAULT_GATEWAY_URL.to_string(), - client_id: DEFAULT_CLIENT_ID.to_string(), - client_secret: DEFAULT_CLIENT_SECRET.to_string(), - timeout_ms: DEFAULT_TIMEOUT_MS, - api_version: DEFAULT_API_VERSION.to_string(), - include_schema: true, - mock_gateway: false, + if errors.is_empty() { + Ok(()) + } else { + Err(ProxyError::Config(format!( + "configuration validation failed:\n - {}", + errors.join("\n - ") + ))) } } } -impl Default for EcuConfig { - fn default() -> Self { - Self { - default_name: DEFAULT_ECU_NAME.to_string(), - logical_address: 0x0001, - eid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], - gid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eid_gid_holds_expected_bytes() { + let eid = EidGid([0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); + assert_eq!(eid.0, [0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); + } + + #[test] + fn eid_gid_all_zeros_detected() { + let eid = EidGid([0u8; 6]); + assert!(eid.is_all_zeros()); + + let eid2 = EidGid([0, 1, 2, 3, 4, 5]); + assert!(!eid2.is_all_zeros()); + } + + #[test] + fn log_level_deserializes_all_variants_from_toml() { + #[derive(Deserialize)] + struct Wrapper { + level: LogLevel, + } + + for (raw, expected) in [ + ("error", LogLevel::Error), + ("warn", LogLevel::Warn), + ("info", LogLevel::Info), + ("debug", LogLevel::Debug), + ("trace", LogLevel::Trace), + ] { + let parsed: Wrapper = + toml::from_str(&format!("level = \"{raw}\"")).expect("valid level"); + assert_eq!(parsed.level, expected); } } -} -impl Default for LoggingConfig { - fn default() -> Self { - Self { - level: "info".to_string(), - format: "pretty".to_string(), + #[test] + fn log_format_deserializes_all_variants_from_toml() { + #[derive(Deserialize)] + struct Wrapper { + format: LogFormat, + } + + for (raw, expected) in [("pretty", LogFormat::Pretty), ("json", LogFormat::Json)] { + let parsed: Wrapper = + toml::from_str(&format!("format = \"{raw}\"")).expect("valid format"); + assert_eq!(parsed.format, expected); } } -} -#[cfg(test)] -mod tests { - use super::*; + #[test] + fn server_defaults_are_sane() { + let s = ServerConfig::default(); + assert_eq!(s.doip_port, 13_400); + assert_eq!(s.max_connections, 10); + } #[test] - fn test_default_config() { - let config = Config::default(); - assert_eq!(config.server.doip_port, 13400); - assert_eq!(config.sovd.api_version, "v15"); - assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); + fn sovd_defaults_are_sane() { + let s = SovdConfig::default(); + assert!(s.mock_gateway); + assert!(s.include_schema); + assert_eq!(s.timeout_ms, 5_000); } #[test] - fn test_deserialize_valid_config() { - let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; - let config: Config = toml::from_str(toml_str).expect("valid config should parse"); - assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); - assert_eq!(config.server.doip_port, 13400); + fn validation_rejects_empty_client_id() { + let mut config = Config::default(); + config.sovd.client_id = String::new(); + assert!(config.validate().is_err()); } #[test] - fn test_deserialize_rejects_zero_port() { - let toml_str = r#" - [server] - doip_port = 0 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; - let result = toml::from_str::(toml_str); - assert!(result.is_err(), "doip_port=0 should be rejected"); + fn validation_rejects_all_zero_eid() { + let mut config = Config::default(); + config.ecu.eid = EidGid([0u8; 6]); + assert!(config.validate().is_err()); + } + + #[test] + fn validation_rejects_zero_max_connections() { + let mut config = Config::default(); + config.server.max_connections = 0; + assert!(config.validate().is_err()); + } + + #[test] + fn validation_accumulates_multiple_errors() { + let mut config = Config::default(); + config.sovd.client_id = String::new(); + config.sovd.api_version = String::new(); + config.ecu.eid = EidGid([0u8; 6]); + let err = config.validate().unwrap_err().to_string(); + // Three separate bullets should appear. + assert_eq!(err.matches(" - ").count(), 3); + } + + #[test] + fn toml_parses_complete_config() { + let raw = r#" +[server] +bind_address = "127.0.0.1" +max_connections = 5 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 3000 +api_version = "v15" +include_schema = false +mock_gateway = true + +[ecu] +default_name = "TEST_ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "debug" +format = "json" +"#; + let cfg: Config = toml::from_str(raw).expect("valid TOML"); + assert!(cfg.sovd.mock_gateway); + assert_eq!(cfg.logging.level, LogLevel::Debug); + assert_eq!(cfg.logging.format, LogFormat::Json); } #[test] - fn test_deserialize_rejects_zero_max_connections() { + fn deserialize_rejects_zero_max_connections() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 0 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 0 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "max_connections=0 should be rejected"); } #[test] - fn test_deserialize_rejects_zero_logical_address() { + fn deserialize_rejects_zero_logical_address() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 0 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 0 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "logical_address=0 should be rejected"); } #[test] - fn test_deserialize_rejects_wrong_eid_length() { + fn deserialize_rejects_wrong_eid_length() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "eid with wrong length should be rejected"); } #[test] - fn test_deserialize_rejects_empty_gateway_url() { + fn deserialize_rejects_invalid_gateway_url() { + let toml_str = r#" +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "not a valid url" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "invalid gateway_url should be rejected"); + } + + #[test] + fn deserialize_rejects_invalid_log_level() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "verbose" +format = "pretty" +"#; let result = toml::from_str::(toml_str); - assert!(result.is_err(), "empty gateway_url should be rejected"); + assert!(result.is_err(), "invalid log level should be rejected"); + } + + // โ”€โ”€ CLI integration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + #[test] + fn cli_overrides_default_values() { + let cli = Cli::parse_from([ + "uds2sovd-proxy", + "--config", + "/nonexistent/path.toml", + "--log-level", + "debug", + "--mock-gateway", + "--mdd-file", + "test.mdd", + ]); + + let config = Config::load(&cli).expect("should build from defaults + CLI"); + assert_eq!(config.logging.level, LogLevel::Debug); + assert!(config.sovd.mock_gateway); + } + + #[test] + fn toml_with_missing_sections_uses_defaults() { + let raw = r#" +[server] +bind_address = "127.0.0.1" +max_connections = 5 +source_address = 3712 +"#; + let cfg: Config = toml::from_str(raw).expect("partial TOML should parse"); + assert_eq!(cfg.sovd.api_version, "v15"); + assert_eq!(cfg.logging.level, LogLevel::Info); } } diff --git a/proxy-core/src/lib.rs b/proxy-core/src/lib.rs index 84d5ad6..5a10e48 100644 --- a/proxy-core/src/lib.rs +++ b/proxy-core/src/lib.rs @@ -10,21 +10,12 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -//! Core types and traits shared across all proxy crates. -//! -//! Defines configuration, error types, and the MDD-driven [`ServiceResolver`] facade -//! with three composable sub-components: -//! -//! - [`DidResolver`] โ€” DID-to-service resolution -//! - [`ResponseEncoder`] โ€” UDS response encoding -//! - [`MetadataProvider`] โ€” MDD parameter metadata queries - pub mod config; pub mod error; -pub mod service_resolver; +pub(crate) mod service_resolver; -pub use config::Config; +pub use config::{Cli, Config, EidGid, LogFormat, LogLevel}; pub use error::{ProxyError, Result}; pub use service_resolver::{ - DidResolver, MetadataProvider, ResolvedService, ResponseEncoder, ServiceResolver, ServiceType, + ResolvedService, ServiceResolver, ServiceType, find_mux_case_prefix, uds_service_ids, }; diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs index 7065d98..9aeefdb 100644 --- a/proxy-core/src/service_resolver/metadata.rs +++ b/proxy-core/src/service_resolver/metadata.rs @@ -16,29 +16,34 @@ //! MDD, looks up services by SID, and retrieves MUX case information. use cda_interfaces::{ - DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, MuxCaseInfo, - ServiceParameterMetadata, + DiagServiceError, DynamicPlugin, EcuManager as EcuManagerTrait, ServiceParameterMetadata, }; use super::{ManagerHandle, uds_helpers::has_mux_case_for_did_exact, uds_service_ids}; #[derive(Clone)] -pub struct MetadataProvider { +pub(crate) struct MetadataProvider { manager: ManagerHandle, } impl MetadataProvider { - pub fn new(manager: ManagerHandle) -> Self { + pub(crate) fn new(manager: ManagerHandle) -> Self { Self { manager } } /// Return the request parameter layout for `service_name`. /// + /// # Note + /// + /// This function is retained for debug/inspection purposes and is not + /// part of the main request processing flow. + /// /// # Errors /// /// Returns `DiagServiceError` when the service is unknown or the MDD /// does not contain request metadata. - pub async fn get_request_params( + #[allow(dead_code)] + pub(crate) async fn get_request_params( &self, service_name: &str, ) -> Result, DiagServiceError> { @@ -52,7 +57,7 @@ impl MetadataProvider { /// /// Returns `DiagServiceError` when the service is unknown or no response /// metadata exists. - pub async fn get_response_params( + pub(crate) async fn get_response_params( &self, service_name: &str, ) -> Result, DiagServiceError> { @@ -75,7 +80,7 @@ impl MetadataProvider { /// # Errors /// /// Returns `DiagServiceError` when the base metadata lookup fails. - pub async fn get_enriched_response_metadata( + pub(crate) async fn get_enriched_response_metadata( &self, service_name: &str, did: u16, @@ -90,10 +95,16 @@ impl MetadataProvider { /// Returns READ services for SID 0x22, WRITE services for SID 0x2E, /// or an empty vector for unrecognised SIDs. /// + /// # Note + /// + /// This function is retained for debug/inspection purposes and is not + /// part of the main request processing flow. + /// /// # Errors /// /// Returns `DiagServiceError` when the service name lookup fails. - pub async fn lookup_service_names_by_sid( + #[allow(dead_code)] + pub(crate) async fn lookup_service_names_by_sid( &self, sid: u8, ) -> Result, DiagServiceError> { @@ -116,21 +127,31 @@ impl MetadataProvider { Ok(names) } - /// Return MUX case definitions for `service_name`. + /// Return the best available POS-RESPONSE metadata for `service_name` + `did`. /// - /// Queries the MDD for all MUX cases associated with the service, - /// used to determine which parameters are active for each MUX value. + /// Tries the enriched (MUX-substituted) path first; falls back to the plain + /// POS-RESPONSE layout when the enriched path fails. /// /// # Errors /// - /// Returns `DiagServiceError` when the service is unknown or the MDD - /// query fails. - pub async fn get_mux_cases_for_service( + /// Returns `DiagServiceError` when both the enriched and plain paths fail. + pub(crate) async fn get_response_metadata( &self, service_name: &str, - ) -> Result, DiagServiceError> { - let manager = self.manager.read().await; - manager.get_mux_cases_for_service(service_name) + did: u16, + ) -> Result, DiagServiceError> { + match self.get_enriched_response_metadata(service_name, did).await { + Ok(meta) => Ok(meta), + Err(enriched_err) => { + tracing::debug!( + "[MDD] Enriched metadata unavailable for '{}': {}. Falling back to basic \ + POS-RESPONSE metadata", + service_name, + enriched_err + ); + self.get_response_params(service_name).await + } + } } /// Retrieve enriched POS-RESPONSE metadata with the source service name. @@ -145,7 +166,7 @@ impl MetadataProvider { /// # Errors /// /// Returns `DiagServiceError` when the base metadata lookup fails. - pub async fn get_enriched_response_metadata_with_source( + pub(crate) async fn get_enriched_response_metadata_with_source( &self, service_name: &str, did: u16, diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs index 1bf1fb8..a46023d 100644 --- a/proxy-core/src/service_resolver/mod.rs +++ b/proxy-core/src/service_resolver/mod.rs @@ -19,7 +19,7 @@ pub(crate) mod metadata; pub(crate) mod resolve; pub(crate) mod response; -pub mod uds_helpers; +pub(crate) mod uds_helpers; use std::sync::Arc; @@ -27,14 +27,15 @@ use cda_core::{DiagServiceResponseStruct, EcuManager as CdaEcuManager}; use cda_database::datatypes::DiagnosticDatabase; use cda_interfaces::{ DiagComm, DiagCommType, DiagServiceError, EcuManager as EcuManagerTrait, EcuManagerType, - FunctionalDescriptionConfig, HashMap, Protocol, + FunctionalDescriptionConfig, HashMap, Protocol, ResponseParameterInfo, datatypes::{ComParams, DatabaseNamingConvention, DiagnosticServiceAffixPosition}, diagservices::DiagServiceResponseType, }; use cda_plugin_security::DefaultSecurityPluginData; -pub use metadata::MetadataProvider; -pub use resolve::{DidResolver, ResolvedService, ServiceType}; -pub use response::ResponseEncoder; +pub(crate) use metadata::MetadataProvider; +pub(crate) use resolve::DidResolver; +pub use resolve::{ResolvedService, ServiceType}; +pub(crate) use response::ResponseEncoder; use tokio::sync::RwLock; pub use uds_helpers::find_mux_case_prefix; @@ -85,23 +86,21 @@ pub mod uds_service_ids { pub struct ServiceResolver { /// DID-to-service resolution. - pub resolver: DidResolver, + resolver: DidResolver, /// UDS response encoding from SOVD JSON data. - pub encoder: ResponseEncoder, + encoder: ResponseEncoder, /// MDD metadata queries (request/response parameter info, MUX cases). - pub metadata: MetadataProvider, - ecu_name: String, + metadata: MetadataProvider, } impl ServiceResolver { - /// Initialise from an ECU name and a loaded MDD database. + /// Initialise from a loaded MDD database. /// /// # Errors /// /// Returns `DiagServiceError` when the CDA `EcuManager` cannot be created /// or the base variant fails to activate. pub async fn new( - ecu_name: String, db: DiagnosticDatabase, logical_address: u16, tester_address: u16, @@ -138,7 +137,6 @@ impl ServiceResolver { resolver: DidResolver::new(Arc::clone(&handle)), encoder: ResponseEncoder::new(Arc::clone(&handle), metadata.clone()), metadata, - ecu_name, }) } @@ -152,7 +150,7 @@ impl ServiceResolver { /// state-chart and pins the engine to a determinate base state. /// /// #`TODO:` real variant detection - /// + /// /// Replace the dummy response with actual variant-identification DID /// reads from a live ECU connection: /// 1. Read variant-identification DIDs from the ECU. @@ -173,7 +171,7 @@ impl ServiceResolver { type_: DiagCommType::Data, lookup_name: None, }, - data: vec![], + data: Vec::new(), mapped_data: None, response_type: DiagServiceResponseType::Positive, }; @@ -197,10 +195,53 @@ impl ServiceResolver { }) } - /// Get ECU name. - #[must_use] - pub fn ecu_name(&self) -> &str { - &self.ecu_name + /// Resolve the best-matching MDD service for a UDS DID request. + /// + /// Returns `None` when no matching service is found in the MDD. + pub async fn resolve( + &self, + service_type: ServiceType, + did: u16, + uds_bytes: &[u8], + ) -> Option { + self.resolver.resolve(service_type, did, uds_bytes).await + } + + /// Build UDS response bytes from SOVD JSON data using MDD metadata. + /// + /// # Errors + /// + /// Returns `DiagServiceError` when the response cannot be encoded. + pub async fn build_response( + &self, + service_name: &str, + sid: u8, + did: u16, + response_data: HashMap, + ) -> Result, DiagServiceError> { + self.encoder + .build_response(service_name, sid, did, response_data) + .await + } + + /// Return the best available POS-RESPONSE metadata for `service_name` + `did`. + /// + /// Tries enriched (MUX-substituted) metadata first; falls back to the plain + /// POS-RESPONSE layout when the enriched path fails. + /// NOTE: + /// This is intended for the mock response path only. Once the SOVD server + /// supplies real data this accessor is no longer required externally. + /// + /// # Errors + /// + /// Returns `DiagServiceError` when both the enriched and plain metadata + /// lookups fail. + pub async fn get_response_metadata( + &self, + service_name: &str, + did: u16, + ) -> Result, DiagServiceError> { + self.metadata.get_response_metadata(service_name, did).await } fn default_com_params(logical_address: u16, tester_address: u16) -> ComParams { diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs index 2877edb..e9fdf7e 100644 --- a/proxy-core/src/service_resolver/resolve.rs +++ b/proxy-core/src/service_resolver/resolve.rs @@ -69,18 +69,18 @@ pub struct ResolvedService { } /// Resolves UDS DID values to MDD service names. -pub struct DidResolver { +pub(crate) struct DidResolver { manager: ManagerHandle, } impl DidResolver { /// Create a new resolver backed by the given manager handle. - pub fn new(manager: ManagerHandle) -> Self { + pub(crate) fn new(manager: ManagerHandle) -> Self { Self { manager } } /// Resolve the best-matching service for a UDS DID request. - pub async fn resolve( + pub(crate) async fn resolve( &self, service_type: ServiceType, did: u16, @@ -94,7 +94,7 @@ impl DidResolver { // Attempt parse-validation to extract structured parameter data. let manager = self.manager.read().await; - let payload: cda_interfaces::ServicePayload = make_service_payload(uds_bytes); + let payload = make_service_payload(uds_bytes); let diag_comm = make_diag_comm(&service_name, sid); if let Ok(parsed) = manager diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index efe52a8..b7fc21c 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -29,14 +29,14 @@ use super::{ }; /// Encodes SOVD JSON data into UDS response bytes using MDD metadata. -pub struct ResponseEncoder { +pub(crate) struct ResponseEncoder { manager: ManagerHandle, metadata: MetadataProvider, } impl ResponseEncoder { /// Create a new response encoder. - pub fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { + pub(crate) fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { Self { manager, metadata } } @@ -60,7 +60,7 @@ impl ResponseEncoder { /// -- /// once the SOVD server returns pre-encoded UDS bytes, both encoding /// paths can be removed. - pub async fn build_response( + pub(crate) async fn build_response( &self, service_name: &str, sid: u8, @@ -105,6 +105,9 @@ impl ResponseEncoder { response.extend(encode_unsigned_be(num)); } else if let Some(num) = n.as_i64() { let unsigned = num.cast_unsigned(); + // For negative numbers: if they fit in one byte, use direct cast; + // otherwise, split into high and low bytes. Truncation is intentional + // for single-byte encoding of small negative values. #[allow(clippy::cast_possible_truncation)] if u8::try_from(unsigned).is_ok() { response.push(unsigned as u8); @@ -116,6 +119,8 @@ impl ResponseEncoder { } serde_json::Value::Array(arr) => { for item in arr { + // Array elements are expected to represent raw bytes; + // values > 255 are truncated to the low byte by design. #[allow(clippy::cast_possible_truncation)] if let Some(byte) = item.as_u64() { response.push(byte as u8); @@ -171,56 +176,10 @@ impl ResponseEncoder { return None; } - // Find the MUX case matching this DID (floor-based). let mux_case_prefix = find_mux_case_prefix(&meta, did); + let active_params = filter_active_params(&meta, mux_case_prefix.as_deref()); + let effective_sizes = compute_effective_sizes(&active_params, response_data); - // Derive the case marker name for total_size computation. - let mux_marker_name: Option = mux_case_prefix - .as_deref() - .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - - // Keep top-level params (no '/') plus matching MUX case sub-params. - let active_params: Vec<_> = meta - .iter() - .filter(|p| { - if !p.name.contains('/') { - true - } else if let Some(prefix) = &mux_case_prefix { - p.name.starts_with(prefix.as_str()) - || mux_marker_name.as_deref() == Some(&p.name) - } else { - !p.name.starts_with("__mux_case__/") - } - }) - .collect(); - - // Resolve effective size: for VALUE params with `byte_size: None` - // (variable-length DOPs), infer the size from actual response data. - let effective_sizes: Vec = active_params - .iter() - .map(|p| { - if let Some(s) = p.byte_size { - return s as usize; - } - // Variable-size VALUE param -- infer size from the data. - if !matches!( - &p.param_type, - cda_interfaces::ParameterTypeMetadata::Value { .. } - ) { - return 0; - } - let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); - let value = response_data - .get(&p.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - value_to_bytes(value).len() - }) - .collect(); - - // Determine total response size from filtered params. let total_size = active_params .iter() .zip(effective_sizes.iter()) @@ -229,74 +188,13 @@ impl ResponseEncoder { .unwrap_or(UDS_POSITIVE_RESPONSE_MIN_SIZE); let mut response = vec![0u8; total_size]; - - for (param, &eff_size) in active_params.iter().zip(effective_sizes.iter()) { - // Skip MUX case markers โ€” they're only used for total_size computation. - if param.name.starts_with("__mux_case__/") { - continue; - } - let pos = param.byte_position as usize; - - if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { - continue; - } - - match ¶m.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - // The SID byte is stored as a decimal string (e.g. "98" for 0x62). - if let Ok(val) = coded_value.parse::() { - let bytes = encode_unsigned_be(val); - let copy_len = bytes.len().min(eff_size); - // Right-align in the field (big-endian convention). - let offset = eff_size.saturating_sub(copy_len); - let dst_start = pos.saturating_add(offset); - let dst_end = dst_start.saturating_add(copy_len); - let src_start = bytes.len().saturating_sub(copy_len); - if let (Some(dst), Some(src)) = - (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) - { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { - // DID bytes from the original request, big-endian. - let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; - let copy_len = did_bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - did_bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // For MUX case params, try the short name (after '/') as well. - let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); - let value = response_data - .get(¶m.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - - if param.byte_size.is_some() { - encode_value_at(&mut response, pos, eff_size, value); - } else { - // Variable-size param: write the raw byte representation. - let bytes = value_to_bytes(value); - let copy_len = bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} - } - } + encode_params_into_response( + &mut response, + &active_params, + &effective_sizes, + response_data, + did, + ); tracing::debug!( "[MDD] Built UDS response via metadata for '{}'): {:02X?}", @@ -335,12 +233,161 @@ impl ResponseEncoder { } } +/// Keep only the parameters that are active for the given MUX case. +/// +/// - Top-level params (no `/` in name) are always included. +/// - When `mux_case_prefix` is `Some`, only sub-params whose name starts with +/// that prefix (plus the corresponding `__mux_case__` marker) are kept. +/// - When `mux_case_prefix` is `None`, all params without `/` are kept and +/// any `__mux_case__/` entries are dropped. +fn filter_active_params<'a>( + meta: &'a [cda_interfaces::ResponseParameterInfo], + mux_case_prefix: Option<&str>, +) -> Vec<&'a cda_interfaces::ResponseParameterInfo> { + let mux_marker_name: Option = + mux_case_prefix.map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + meta.iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = mux_case_prefix { + p.name.starts_with(prefix) || mux_marker_name.as_deref() == Some(p.name.as_str()) + } else { + !p.name.starts_with("__mux_case__/") + } + }) + .collect() +} + +/// Determine the effective byte size of each active parameter. +/// +/// Fixed-size params use `byte_size` directly. Variable-size `VALUE` params +/// (where `byte_size` is `None`) infer their size from the serialised form of +/// the matching value in `response_data`. +fn compute_effective_sizes( + active_params: &[&cda_interfaces::ResponseParameterInfo], + response_data: &HashMap, +) -> Vec { + active_params + .iter() + .map(|p| { + if let Some(s) = p.byte_size { + return s as usize; + } + // Variable-size VALUE param -- infer size from the data. + if !matches!( + &p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + ) { + return 0; + } + let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); + let value = response_data + .get(&p.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + value_to_bytes(value).len() + }) + .collect() +} + +/// Write each active parameter into `response` at its MDD-defined byte position. +/// +/// - `__mux_case__/` markers are skipped (used only for size computation). +/// - Out-of-bounds or zero-size writes are silently ignored. +/// +/// # Note on casts +/// +/// `u16 >> 8` and `u16 & 0xFF` both fit in a `u8`; the truncating casts are +/// intentional and cannot overflow. +#[allow(clippy::cast_possible_truncation)] +fn encode_params_into_response( + response: &mut [u8], + active_params: &[&cda_interfaces::ResponseParameterInfo], + effective_sizes: &[usize], + response_data: &HashMap, + did: u16, +) { + for (param, &eff_size) in active_params.iter().zip(effective_sizes) { + // MUX case markers are only used for total_size computation. + if param.name.starts_with("__mux_case__/") { + continue; + } + let pos = param.byte_position as usize; + + if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { + continue; + } + + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // The SID byte is stored as a decimal string (e.g. "98" for 0x62). + if let Ok(val) = coded_value.parse::() { + let bytes = encode_unsigned_be(val); + let copy_len = bytes.len().min(eff_size); + // Right-align in the field (big-endian convention). + let offset = eff_size.saturating_sub(copy_len); + let dst_start = pos.saturating_add(offset); + let dst_end = dst_start.saturating_add(copy_len); + let src_start = bytes.len().saturating_sub(copy_len); + if let (Some(dst), Some(src)) = + (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) + { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { + // DID bytes from the original request, big-endian. + let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; + let copy_len = did_bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + did_bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // For MUX case params, try the short name (after '/') as well. + let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); + let value = response_data + .get(¶m.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + if param.byte_size.is_some() { + encode_value_at(response, pos, eff_size, value); + } else { + // Variable-size param: write the raw byte representation. + let bytes = value_to_bytes(value); + let copy_len = bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} + } + } +} + #[cfg(test)] mod tests { - use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; + use cda_interfaces::{HashMap, ParameterTypeMetadata, ResponseParameterInfo}; - use super::super::uds_helpers::{ - encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, + use super::{ + super::uds_helpers::{ + encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, + }, + compute_effective_sizes, filter_active_params, }; /// Numbers are right-aligned (big-endian) in the target field. @@ -515,22 +562,8 @@ mod tests { ]; let mux_case_prefix = find_mux_case_prefix(&meta, did); - let mux_marker_name: Option = mux_case_prefix - .as_deref() - .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - - let active: Vec<_> = meta - .iter() - .filter(|p| { - if !p.name.contains('/') { - true - } else if let Some(prefix) = &mux_case_prefix { - p.name.starts_with(prefix.as_str()) - || mux_marker_name.as_deref() == Some(p.name.as_str()) - } else { - !p.name.starts_with("__mux_case__/") - } - }) + let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) + .into_iter() .map(|p| p.name.as_str()) .collect(); @@ -556,9 +589,8 @@ mod tests { let mux_case_prefix = find_mux_case_prefix(&meta, did); assert!(mux_case_prefix.is_none()); - let active: Vec<_> = meta - .iter() - .filter(|p| !p.name.contains('/') || p.name.starts_with("__mux_case__/")) + let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) + .into_iter() .map(|p| p.name.as_str()) .collect(); @@ -573,12 +605,11 @@ mod tests { value_param("DID", 1, 2), value_param("DATA", 3, 17), ]; - let effective_sizes: Vec = params - .iter() - .map(|p| p.byte_size.map_or(0, |s| s as usize)) - .collect(); + let active_refs: Vec<&_> = params.iter().collect(); + // All params have fixed byte_size, so response_data is not consulted. + let effective_sizes = compute_effective_sizes(&active_refs, &HashMap::default()); - let total = params + let total = active_refs .iter() .zip(effective_sizes.iter()) .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) From b33b7bfb52b94e7c0e081ca03bb48d14fac40537 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 12 May 2026 15:05:04 +0200 Subject: [PATCH 12/33] fix: address review comments for service_parsing --- .../service_resolver_class_diagram.svg | 2 +- .../service_resolver_sequence_diagram.svg | 2 +- proxy-core/src/lib.rs | 2 +- proxy-core/src/service_resolver/mod.rs | 1 - proxy-core/src/service_resolver/response.rs | 323 ++++++++---------- .../src/service_resolver/uds_helpers.rs | 2 +- 6 files changed, 150 insertions(+), 182 deletions(-) diff --git a/docs/service_resolver/service_resolver_class_diagram.svg b/docs/service_resolver/service_resolver_class_diagram.svg index 550c25d..39bc6a7 100644 --- a/docs/service_resolver/service_resolver_class_diagram.svg +++ b/docs/service_resolver/service_resolver_class_diagram.svg @@ -1 +1 @@ -Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-resolver : DidResolver-encoder : ResponseEncoder-metadata : MetadataProvider+«async» new(db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParamsmod.rs -- construction+«async» resolve(service_type, did, uds) : Option<ResolvedService>+«async» build_response(name, sid, did, data) : Result<Vec<u8>>+«async» get_response_metadata(name, did) : Result<Vec<RespParam>>mod.rs -- public API«crate-internal»DidResolver-manager : CdaEcuManager~«async» resolve(service_type, did, uds) : Option<ResolvedService>-«async» resolve_service_did(sid, did, label) : Option<String>-build_did_candidates(manager, did_prefix, sid, did, label) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service name«crate-internal»ResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider~«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS response«crate-internal»MetadataProvider-manager : CdaEcuManager~«async» get_request_params(name) : Result<Vec<Param>>~«async» get_response_params(name) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>~«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>~«async» get_response_metadata(name, did) : Result<Vec<RespParam>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rs.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>resolver (private)encoder (private)metadata (private)holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. \ No newline at end of file +Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-resolver : DidResolver-encoder : ResponseEncoder-metadata : MetadataProvider+«async» new(db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParamsmod.rs -- construction+«async» resolve(service_type, did, uds) : Option<ResolvedService>+«async» build_response(name, sid, did, data) : Result<Vec<u8>>+«async» get_response_metadata(name, did) : Result<Vec<RespParam>>mod.rs -- public API«crate-internal»DidResolver-manager : CdaEcuManager~«async» resolve(service_type, did, uds) : Option<ResolvedService>-«async» resolve_service_did(sid, did, label) : Option<String>-build_did_candidates(manager, did_prefix, sid, did, label) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service name«crate-internal»ResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider~«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS response«crate-internal»MetadataProvider-manager : CdaEcuManager~«async» get_request_params(name) : Result<Vec<Param>>~«async» get_response_params(name) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>~«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>~«async» get_response_metadata(name, did) : Result<Vec<RespParam>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rs.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>resolver (private)encoder (private)metadata (private)holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. diff --git a/docs/service_resolver/service_resolver_sequence_diagram.svg b/docs/service_resolver/service_resolver_sequence_diagram.svg index 2fcfb0e..b698f09 100644 --- a/docs/service_resolver/service_resolver_sequence_diagram.svg +++ b/docs/service_resolver/service_resolver_sequence_diagram.svg @@ -1 +1 @@ -ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs)ServiceResolver(mod.rs)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve(ServiceType::Read, did, uds_bytes)resolve(service_type, did, uds_bytes)resolve_service_did(sid=0x22, did, label="READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, did_prefix, sid, did, label)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>Option<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesclient calls facade.resolve(ServiceType::Write, did, uds_bytes)which uses sid=0x2E and get_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)build_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError>Result<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): public entry point —construction, variant activation, and delegatingresolve() / build_response() / get_response_metadata()to internal sub-components.-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure free functions --encoding, decoding, MUX matching Data flow:Caller invokes facade methods on ServiceResolver.ServiceResolver delegates internally to sub-components(all private: resolver, encoder, metadata).ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. \ No newline at end of file +ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs)ServiceResolver(mod.rs)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve(ServiceType::Read, did, uds_bytes)resolve(service_type, did, uds_bytes)resolve_service_did(sid=0x22, did, label="READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, did_prefix, sid, did, label)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>Option<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesclient calls facade.resolve(ServiceType::Write, did, uds_bytes)which uses sid=0x2E and get_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)build_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError>Result<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): public entry point —construction, variant activation, and delegatingresolve() / build_response() / get_response_metadata()to internal sub-components.-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure free functions --encoding, decoding, MUX matching Data flow:Caller invokes facade methods on ServiceResolver.ServiceResolver delegates internally to sub-components(all private: resolver, encoder, metadata).ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. diff --git a/proxy-core/src/lib.rs b/proxy-core/src/lib.rs index 5a10e48..2a47f49 100644 --- a/proxy-core/src/lib.rs +++ b/proxy-core/src/lib.rs @@ -17,5 +17,5 @@ pub(crate) mod service_resolver; pub use config::{Cli, Config, EidGid, LogFormat, LogLevel}; pub use error::{ProxyError, Result}; pub use service_resolver::{ - ResolvedService, ServiceResolver, ServiceType, find_mux_case_prefix, uds_service_ids, + ResolvedService, ServiceResolver, ServiceType, uds_service_ids, }; diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs index a46023d..eaaa23d 100644 --- a/proxy-core/src/service_resolver/mod.rs +++ b/proxy-core/src/service_resolver/mod.rs @@ -37,7 +37,6 @@ pub(crate) use resolve::DidResolver; pub use resolve::{ResolvedService, ServiceType}; pub(crate) use response::ResponseEncoder; use tokio::sync::RwLock; -pub use uds_helpers::find_mux_case_prefix; pub(crate) type ManagerHandle = Arc>>; diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index b7fc21c..efe52a8 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -29,14 +29,14 @@ use super::{ }; /// Encodes SOVD JSON data into UDS response bytes using MDD metadata. -pub(crate) struct ResponseEncoder { +pub struct ResponseEncoder { manager: ManagerHandle, metadata: MetadataProvider, } impl ResponseEncoder { /// Create a new response encoder. - pub(crate) fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { + pub fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { Self { manager, metadata } } @@ -60,7 +60,7 @@ impl ResponseEncoder { /// -- /// once the SOVD server returns pre-encoded UDS bytes, both encoding /// paths can be removed. - pub(crate) async fn build_response( + pub async fn build_response( &self, service_name: &str, sid: u8, @@ -105,9 +105,6 @@ impl ResponseEncoder { response.extend(encode_unsigned_be(num)); } else if let Some(num) = n.as_i64() { let unsigned = num.cast_unsigned(); - // For negative numbers: if they fit in one byte, use direct cast; - // otherwise, split into high and low bytes. Truncation is intentional - // for single-byte encoding of small negative values. #[allow(clippy::cast_possible_truncation)] if u8::try_from(unsigned).is_ok() { response.push(unsigned as u8); @@ -119,8 +116,6 @@ impl ResponseEncoder { } serde_json::Value::Array(arr) => { for item in arr { - // Array elements are expected to represent raw bytes; - // values > 255 are truncated to the low byte by design. #[allow(clippy::cast_possible_truncation)] if let Some(byte) = item.as_u64() { response.push(byte as u8); @@ -176,10 +171,56 @@ impl ResponseEncoder { return None; } + // Find the MUX case matching this DID (floor-based). let mux_case_prefix = find_mux_case_prefix(&meta, did); - let active_params = filter_active_params(&meta, mux_case_prefix.as_deref()); - let effective_sizes = compute_effective_sizes(&active_params, response_data); + // Derive the case marker name for total_size computation. + let mux_marker_name: Option = mux_case_prefix + .as_deref() + .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + // Keep top-level params (no '/') plus matching MUX case sub-params. + let active_params: Vec<_> = meta + .iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = &mux_case_prefix { + p.name.starts_with(prefix.as_str()) + || mux_marker_name.as_deref() == Some(&p.name) + } else { + !p.name.starts_with("__mux_case__/") + } + }) + .collect(); + + // Resolve effective size: for VALUE params with `byte_size: None` + // (variable-length DOPs), infer the size from actual response data. + let effective_sizes: Vec = active_params + .iter() + .map(|p| { + if let Some(s) = p.byte_size { + return s as usize; + } + // Variable-size VALUE param -- infer size from the data. + if !matches!( + &p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + ) { + return 0; + } + let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); + let value = response_data + .get(&p.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + value_to_bytes(value).len() + }) + .collect(); + + // Determine total response size from filtered params. let total_size = active_params .iter() .zip(effective_sizes.iter()) @@ -188,13 +229,74 @@ impl ResponseEncoder { .unwrap_or(UDS_POSITIVE_RESPONSE_MIN_SIZE); let mut response = vec![0u8; total_size]; - encode_params_into_response( - &mut response, - &active_params, - &effective_sizes, - response_data, - did, - ); + + for (param, &eff_size) in active_params.iter().zip(effective_sizes.iter()) { + // Skip MUX case markers โ€” they're only used for total_size computation. + if param.name.starts_with("__mux_case__/") { + continue; + } + let pos = param.byte_position as usize; + + if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { + continue; + } + + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // The SID byte is stored as a decimal string (e.g. "98" for 0x62). + if let Ok(val) = coded_value.parse::() { + let bytes = encode_unsigned_be(val); + let copy_len = bytes.len().min(eff_size); + // Right-align in the field (big-endian convention). + let offset = eff_size.saturating_sub(copy_len); + let dst_start = pos.saturating_add(offset); + let dst_end = dst_start.saturating_add(copy_len); + let src_start = bytes.len().saturating_sub(copy_len); + if let (Some(dst), Some(src)) = + (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) + { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { + // DID bytes from the original request, big-endian. + let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; + let copy_len = did_bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + did_bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // For MUX case params, try the short name (after '/') as well. + let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); + let value = response_data + .get(¶m.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + + if param.byte_size.is_some() { + encode_value_at(&mut response, pos, eff_size, value); + } else { + // Variable-size param: write the raw byte representation. + let bytes = value_to_bytes(value); + let copy_len = bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} + } + } tracing::debug!( "[MDD] Built UDS response via metadata for '{}'): {:02X?}", @@ -233,161 +335,12 @@ impl ResponseEncoder { } } -/// Keep only the parameters that are active for the given MUX case. -/// -/// - Top-level params (no `/` in name) are always included. -/// - When `mux_case_prefix` is `Some`, only sub-params whose name starts with -/// that prefix (plus the corresponding `__mux_case__` marker) are kept. -/// - When `mux_case_prefix` is `None`, all params without `/` are kept and -/// any `__mux_case__/` entries are dropped. -fn filter_active_params<'a>( - meta: &'a [cda_interfaces::ResponseParameterInfo], - mux_case_prefix: Option<&str>, -) -> Vec<&'a cda_interfaces::ResponseParameterInfo> { - let mux_marker_name: Option = - mux_case_prefix.map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - - meta.iter() - .filter(|p| { - if !p.name.contains('/') { - true - } else if let Some(prefix) = mux_case_prefix { - p.name.starts_with(prefix) || mux_marker_name.as_deref() == Some(p.name.as_str()) - } else { - !p.name.starts_with("__mux_case__/") - } - }) - .collect() -} - -/// Determine the effective byte size of each active parameter. -/// -/// Fixed-size params use `byte_size` directly. Variable-size `VALUE` params -/// (where `byte_size` is `None`) infer their size from the serialised form of -/// the matching value in `response_data`. -fn compute_effective_sizes( - active_params: &[&cda_interfaces::ResponseParameterInfo], - response_data: &HashMap, -) -> Vec { - active_params - .iter() - .map(|p| { - if let Some(s) = p.byte_size { - return s as usize; - } - // Variable-size VALUE param -- infer size from the data. - if !matches!( - &p.param_type, - cda_interfaces::ParameterTypeMetadata::Value { .. } - ) { - return 0; - } - let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); - let value = response_data - .get(&p.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - value_to_bytes(value).len() - }) - .collect() -} - -/// Write each active parameter into `response` at its MDD-defined byte position. -/// -/// - `__mux_case__/` markers are skipped (used only for size computation). -/// - Out-of-bounds or zero-size writes are silently ignored. -/// -/// # Note on casts -/// -/// `u16 >> 8` and `u16 & 0xFF` both fit in a `u8`; the truncating casts are -/// intentional and cannot overflow. -#[allow(clippy::cast_possible_truncation)] -fn encode_params_into_response( - response: &mut [u8], - active_params: &[&cda_interfaces::ResponseParameterInfo], - effective_sizes: &[usize], - response_data: &HashMap, - did: u16, -) { - for (param, &eff_size) in active_params.iter().zip(effective_sizes) { - // MUX case markers are only used for total_size computation. - if param.name.starts_with("__mux_case__/") { - continue; - } - let pos = param.byte_position as usize; - - if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { - continue; - } - - match ¶m.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - // The SID byte is stored as a decimal string (e.g. "98" for 0x62). - if let Ok(val) = coded_value.parse::() { - let bytes = encode_unsigned_be(val); - let copy_len = bytes.len().min(eff_size); - // Right-align in the field (big-endian convention). - let offset = eff_size.saturating_sub(copy_len); - let dst_start = pos.saturating_add(offset); - let dst_end = dst_start.saturating_add(copy_len); - let src_start = bytes.len().saturating_sub(copy_len); - if let (Some(dst), Some(src)) = - (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) - { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { - // DID bytes from the original request, big-endian. - let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; - let copy_len = did_bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - did_bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // For MUX case params, try the short name (after '/') as well. - let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); - let value = response_data - .get(¶m.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - if param.byte_size.is_some() { - encode_value_at(response, pos, eff_size, value); - } else { - // Variable-size param: write the raw byte representation. - let bytes = value_to_bytes(value); - let copy_len = bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} - } - } -} - #[cfg(test)] mod tests { - use cda_interfaces::{HashMap, ParameterTypeMetadata, ResponseParameterInfo}; + use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; - use super::{ - super::uds_helpers::{ - encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, - }, - compute_effective_sizes, filter_active_params, + use super::super::uds_helpers::{ + encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, }; /// Numbers are right-aligned (big-endian) in the target field. @@ -562,8 +515,22 @@ mod tests { ]; let mux_case_prefix = find_mux_case_prefix(&meta, did); - let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) - .into_iter() + let mux_marker_name: Option = mux_case_prefix + .as_deref() + .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + let active: Vec<_> = meta + .iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = &mux_case_prefix { + p.name.starts_with(prefix.as_str()) + || mux_marker_name.as_deref() == Some(p.name.as_str()) + } else { + !p.name.starts_with("__mux_case__/") + } + }) .map(|p| p.name.as_str()) .collect(); @@ -589,8 +556,9 @@ mod tests { let mux_case_prefix = find_mux_case_prefix(&meta, did); assert!(mux_case_prefix.is_none()); - let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) - .into_iter() + let active: Vec<_> = meta + .iter() + .filter(|p| !p.name.contains('/') || p.name.starts_with("__mux_case__/")) .map(|p| p.name.as_str()) .collect(); @@ -605,11 +573,12 @@ mod tests { value_param("DID", 1, 2), value_param("DATA", 3, 17), ]; - let active_refs: Vec<&_> = params.iter().collect(); - // All params have fixed byte_size, so response_data is not consulted. - let effective_sizes = compute_effective_sizes(&active_refs, &HashMap::default()); + let effective_sizes: Vec = params + .iter() + .map(|p| p.byte_size.map_or(0, |s| s as usize)) + .collect(); - let total = active_refs + let total = params .iter() .zip(effective_sizes.iter()) .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) diff --git a/proxy-core/src/service_resolver/uds_helpers.rs b/proxy-core/src/service_resolver/uds_helpers.rs index 40bd778..f96060e 100644 --- a/proxy-core/src/service_resolver/uds_helpers.rs +++ b/proxy-core/src/service_resolver/uds_helpers.rs @@ -95,7 +95,7 @@ pub(super) fn parse_mux_coded_value(coded_value: &str) -> Option { /// that does not exceed the DID. This correctly handles both single-value /// MUX cases (e.g. 0x7007) and range cases (e.g. 0xD100โ€“0xD150). #[must_use] -pub fn find_mux_case_prefix(meta: &[ResponseParameterInfo], did: u16) -> Option { +pub(crate) fn find_mux_case_prefix(meta: &[ResponseParameterInfo], did: u16) -> Option { let did_val = u64::from(did); // Collect (lower_bound, case_name) for all MUX case entries. From 9b6cc02864af6266f8d38e2e90fae908d058926d Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 7 May 2026 11:55:18 +0200 Subject: [PATCH 13/33] fix: parsing cli, used clap and url crate --- proxy-core/src/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index 4d4d6b9..52f6ba9 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -385,7 +385,7 @@ mod tests { #[test] fn sovd_defaults_are_sane() { let s = SovdConfig::default(); - assert!(s.mock_gateway); + assert!(!s.mock_gateway); assert!(s.include_schema); assert_eq!(s.timeout_ms, 5_000); } From 930c472e3faf88f87fe468583709ca681dd41c90 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 12 May 2026 14:06:34 +0200 Subject: [PATCH 14/33] refactor: encapsulate ServiceResolver internals behind facade methods --- .../service_resolver_class_diagram.svg | 2 +- .../service_resolver_sequence_diagram.svg | 2 +- proxy-core/src/config.rs | 2 +- proxy-core/src/lib.rs | 4 +- proxy-core/src/service_resolver/response.rs | 323 ++++++++++-------- 5 files changed, 181 insertions(+), 152 deletions(-) diff --git a/docs/service_resolver/service_resolver_class_diagram.svg b/docs/service_resolver/service_resolver_class_diagram.svg index 39bc6a7..550c25d 100644 --- a/docs/service_resolver/service_resolver_class_diagram.svg +++ b/docs/service_resolver/service_resolver_class_diagram.svg @@ -1 +1 @@ -Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-resolver : DidResolver-encoder : ResponseEncoder-metadata : MetadataProvider+«async» new(db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParamsmod.rs -- construction+«async» resolve(service_type, did, uds) : Option<ResolvedService>+«async» build_response(name, sid, did, data) : Result<Vec<u8>>+«async» get_response_metadata(name, did) : Result<Vec<RespParam>>mod.rs -- public API«crate-internal»DidResolver-manager : CdaEcuManager~«async» resolve(service_type, did, uds) : Option<ResolvedService>-«async» resolve_service_did(sid, did, label) : Option<String>-build_did_candidates(manager, did_prefix, sid, did, label) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service name«crate-internal»ResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider~«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS response«crate-internal»MetadataProvider-manager : CdaEcuManager~«async» get_request_params(name) : Result<Vec<Param>>~«async» get_response_params(name) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>~«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>~«async» get_response_metadata(name, did) : Result<Vec<RespParam>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rs.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>resolver (private)encoder (private)metadata (private)holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. +Service Resolver - Class Diagramproxy-core::service_resolver — MDD-driven UDS encoding / decodingproxy-core::service_resolvercda-core(external path dep)proxy-core(public API)«facade»ServiceResolver-manager : CdaEcuManager-resolver : DidResolver-encoder : ResponseEncoder-metadata : MetadataProvider+«async» new(db, logical, tester) : Result<Self>-«async» activate_base_variant(manager) : Result<()>-default_com_params(logical, tester: u16) : ComParamsmod.rs -- construction+«async» resolve(service_type, did, uds) : Option<ResolvedService>+«async» build_response(name, sid, did, data) : Result<Vec<u8>>+«async» get_response_metadata(name, did) : Result<Vec<RespParam>>mod.rs -- public API«crate-internal»DidResolver-manager : CdaEcuManager~«async» resolve(service_type, did, uds) : Option<ResolvedService>-«async» resolve_service_did(sid, did, label) : Option<String>-build_did_candidates(manager, did_prefix, sid, did, label) : Option<Vec<String>>-«async» match_candidate_did(manager, name, sid, did) : bool-«async» probe_service_did(manager, name, sid, meta) : Option<u16>resolve.rsDID> service name«crate-internal»ResponseEncoder-manager : CdaEcuManager-metadata : MetadataProvider~«async» build_response(name, sid, did, data) : Result<Vec<u8>>-«async» encode_response_from_metadata(name, sid, did, data) : Option<(Vec<u8>, String)>-«async» validate_response(name, sid, bytes) : ()response.rs -- encode UDS response«crate-internal»MetadataProvider-manager : CdaEcuManager~«async» get_request_params(name) : Result<Vec<Param>>~«async» get_response_params(name) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata(name, did) : Result<Vec<RespParam>>~«async» get_enriched_response_metadata_with_source(name, did) : Result<(Vec<RespParam>, String)>~«async» lookup_service_names_by_sid(sid) : Result<Vec<String>>~«async» get_response_metadata(name, did) : Result<Vec<RespParam>>metadata.rs -- MDD parameter queries Resolution algorithm:1. lookup_diagcomms_by_request_prefix([SID,DID_HI,DID_LO])2. Single match --> service name found (fast path)3. Multiple candidates --> inspect request parameter metadata:* CodedConst -- exact DID value match* PhysConst -- coded_value or create_uds_payload probe* Value -- coded_default or CompuScale range match4. No match --> log error, return None (no fallback)Response encoding:Walk MDD POS-RESPONSE parameters:CODED-CONST --> fixed byte (e.g. response SID 0x62)MatchingRequestParam --> echo DID bytes from requestVALUE --> SOVD JSON value at MDD-defined offsetOpaque STRUCTURE types trigger MUX sibling lookupvia MetadataProvider.get_enriched_response_metadata_with_source().«module: free functions»uds_helpers+parse_mux_coded_value(coded) : Option<u64>+find_mux_case_prefix(meta, did) : Option<String>+has_mux_case_for_did_exact(meta, did) : bool~extract_did_from_uds(data) : Option<u16>~diag_comm_type(sid) : DiagCommType~make_diag_comm(name, sid) : DiagComm~make_service_payload(data) : ServicePayload~encode_unsigned_be(num) : Vec<u8>~parse_u64_literal(value) : Option<u64>~find_did_param(meta, sid) : Option<Param>~did_matches_compu_scales(scales, did) : bool~encode_value_at(buf, pos, size, value) : ()~value_to_bytes(value) : Vec<u8>internal helpersTop 3 are pub re-exported from mod.rs.«struct»ResolvedService+name : String+params : Map«cda-interfaces»EcuManagerTrait+lookup_diagcomms_by_request_prefix(prefix)+get_request_parameter_metadata(service)+get_response_parameter_metadata(service)+get_components_data_info(plugin)+get_components_configurations_info(plugin)+get_mux_cases_for_service(service)+create_uds_payload(service, plugin, params)+convert_from_uds(service, payload, true)+convert_request_from_uds(service, payload, true)+detect_variant(responses)CdaEcuManager<DefaultSecurityPluginData>Config+server : ServerConfig+sovd : SovdConfig+ecu : EcuConfig+logging : LoggingConfig+from_file(path) : Result<Self>resolver (private)encoder (private)metadata (private)holds (explicit dependency)usesusesreturnsowns via Arc<RwLock>(shared with callers)CdaEcuManager = Arc<RwLock<EcuManager<DefaultSecurityPluginData>>>.Each sub-component receives an Arc::cloneto allow concurrent async read access. \ No newline at end of file diff --git a/docs/service_resolver/service_resolver_sequence_diagram.svg b/docs/service_resolver/service_resolver_sequence_diagram.svg index b698f09..2fcfb0e 100644 --- a/docs/service_resolver/service_resolver_sequence_diagram.svg +++ b/docs/service_resolver/service_resolver_sequence_diagram.svg @@ -1 +1 @@ -ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs)ServiceResolver(mod.rs)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve(ServiceType::Read, did, uds_bytes)resolve(service_type, did, uds_bytes)resolve_service_did(sid=0x22, did, label="READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, did_prefix, sid, did, label)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>Option<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesclient calls facade.resolve(ServiceType::Write, did, uds_bytes)which uses sid=0x2E and get_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)build_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError>Result<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): public entry point —construction, variant activation, and delegatingresolve() / build_response() / get_response_metadata()to internal sub-components.-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure free functions --encoding, decoding, MUX matching Data flow:Caller invokes facade methods on ServiceResolver.ServiceResolver delegates internally to sub-components(all private: resolver, encoder, metadata).ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. +ServiceResolver: DID Resolution & Response BuildingEntry points: SovdDiagHandler.handle_read_did() / handle_write_did() (proxy-sovd)SovdDiagHandler(proxy-sovd)SovdDiagHandler(proxy-sovd)ServiceResolver(mod.rs)ServiceResolver(mod.rs)DidResolver(resolve.rs)DidResolver(resolve.rs)MetadataProvider(metadata.rs)MetadataProvider(metadata.rs)ResponseEncoder(response.rs)ResponseEncoder(response.rs)CDA EcuManagerCDA EcuManagerREAD Service Resolutionresolve(ServiceType::Read, did, uds_bytes)resolve(service_type, did, uds_bytes)resolve_service_did(sid=0x22, did, label="READ")lookup_diagcomms_by_request_prefix([0x22, DID_HI, DID_LO])matching_servicesbuild_did_candidates(manager, did_prefix, sid, did, label)get_components_data_info() orget_components_configurations_info()all SID-matching service namesloop[for each candidate service name]match_candidate_did(manager, name, sid, did)get_request_parameter_metadata(candidate_name)param metadataalt[CodedConst DID]parse_u64_literal(coded_value)[PhysConst DID (coded_value absent)]probe_service_did(manager, name, sid, meta)create_uds_payload(diag_comm, plugin, params)encoded payloadextract_did_from_uds(payload.data)[Value DID]did_matches_compu_scales(scales, did)convert_request_from_uds(diag_comm, payload, strict=true)parsed JSON paramsOption<ResolvedService { name, params }>Option<ResolvedService { name, params }>WRITE Service HandlingSimilar flow for WRITE servicesclient calls facade.resolve(ServiceType::Write, did, uds_bytes)which uses sid=0x2E and get_components_configurations_info()Response Buildingbuild_response(service_name, sid, did, response_data)build_response(service_name, sid, did, response_data)encode_response_from_metadata(service_name, sid, did, data)get_enriched_response_metadata_with_source(service_name, did)get_response_parameter_metadata(service_name)response param layoutalt[opaque STRUCTURE detected]get_components_data_info()READ service componentsloop[for each sibling candidate]get_response_parameter_metadata(candidate)sibling response layouthas_mux_case_for_did_exact(sibling_meta, did)(enriched_meta, sibling_service_name)[standard response](base_meta, service_name)find_mux_case_prefix(meta, did)filter active params by mux_case_prefixfor each active param: encode at byte_positionalt[encode_response_from_metadata returned Some][no metadata available (fallback)]naive encoding via value_to_bytes()alt[DEBUG level enabled]validate_response(effective_service, sid, bytes)convert_from_uds(diag_comm, payload, strict=true)JSONRound-trip validationResult<Vec<u8>, DiagServiceError>Result<Vec<u8>, DiagServiceError> -ServiceResolver (mod.rs): public entry point —construction, variant activation, and delegatingresolve() / build_response() / get_response_metadata()to internal sub-components.-DidResolver (resolve.rs): DID -> service resolution,candidate building, metadata matching-ResponseEncoder (response.rs): UDS response encoding,round-trip validation (debug only)-MetadataProvider (metadata.rs): MDD metadata queries,MUX sibling enrichment-uds_helpers.rs: Pure free functions --encoding, decoding, MUX matching Data flow:Caller invokes facade methods on ServiceResolver.ServiceResolver delegates internally to sub-components(all private: resolver, encoder, metadata).ResponseEncoder holds MetadataProvider internallyfor the cross-module enrichment dependency. \ No newline at end of file diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index 52f6ba9..4d4d6b9 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -385,7 +385,7 @@ mod tests { #[test] fn sovd_defaults_are_sane() { let s = SovdConfig::default(); - assert!(!s.mock_gateway); + assert!(s.mock_gateway); assert!(s.include_schema); assert_eq!(s.timeout_ms, 5_000); } diff --git a/proxy-core/src/lib.rs b/proxy-core/src/lib.rs index 2a47f49..9ef4ff0 100644 --- a/proxy-core/src/lib.rs +++ b/proxy-core/src/lib.rs @@ -16,6 +16,4 @@ pub(crate) mod service_resolver; pub use config::{Cli, Config, EidGid, LogFormat, LogLevel}; pub use error::{ProxyError, Result}; -pub use service_resolver::{ - ResolvedService, ServiceResolver, ServiceType, uds_service_ids, -}; +pub use service_resolver::{ResolvedService, ServiceResolver, ServiceType, uds_service_ids}; diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index efe52a8..b7fc21c 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -29,14 +29,14 @@ use super::{ }; /// Encodes SOVD JSON data into UDS response bytes using MDD metadata. -pub struct ResponseEncoder { +pub(crate) struct ResponseEncoder { manager: ManagerHandle, metadata: MetadataProvider, } impl ResponseEncoder { /// Create a new response encoder. - pub fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { + pub(crate) fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { Self { manager, metadata } } @@ -60,7 +60,7 @@ impl ResponseEncoder { /// -- /// once the SOVD server returns pre-encoded UDS bytes, both encoding /// paths can be removed. - pub async fn build_response( + pub(crate) async fn build_response( &self, service_name: &str, sid: u8, @@ -105,6 +105,9 @@ impl ResponseEncoder { response.extend(encode_unsigned_be(num)); } else if let Some(num) = n.as_i64() { let unsigned = num.cast_unsigned(); + // For negative numbers: if they fit in one byte, use direct cast; + // otherwise, split into high and low bytes. Truncation is intentional + // for single-byte encoding of small negative values. #[allow(clippy::cast_possible_truncation)] if u8::try_from(unsigned).is_ok() { response.push(unsigned as u8); @@ -116,6 +119,8 @@ impl ResponseEncoder { } serde_json::Value::Array(arr) => { for item in arr { + // Array elements are expected to represent raw bytes; + // values > 255 are truncated to the low byte by design. #[allow(clippy::cast_possible_truncation)] if let Some(byte) = item.as_u64() { response.push(byte as u8); @@ -171,56 +176,10 @@ impl ResponseEncoder { return None; } - // Find the MUX case matching this DID (floor-based). let mux_case_prefix = find_mux_case_prefix(&meta, did); + let active_params = filter_active_params(&meta, mux_case_prefix.as_deref()); + let effective_sizes = compute_effective_sizes(&active_params, response_data); - // Derive the case marker name for total_size computation. - let mux_marker_name: Option = mux_case_prefix - .as_deref() - .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - - // Keep top-level params (no '/') plus matching MUX case sub-params. - let active_params: Vec<_> = meta - .iter() - .filter(|p| { - if !p.name.contains('/') { - true - } else if let Some(prefix) = &mux_case_prefix { - p.name.starts_with(prefix.as_str()) - || mux_marker_name.as_deref() == Some(&p.name) - } else { - !p.name.starts_with("__mux_case__/") - } - }) - .collect(); - - // Resolve effective size: for VALUE params with `byte_size: None` - // (variable-length DOPs), infer the size from actual response data. - let effective_sizes: Vec = active_params - .iter() - .map(|p| { - if let Some(s) = p.byte_size { - return s as usize; - } - // Variable-size VALUE param -- infer size from the data. - if !matches!( - &p.param_type, - cda_interfaces::ParameterTypeMetadata::Value { .. } - ) { - return 0; - } - let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); - let value = response_data - .get(&p.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - value_to_bytes(value).len() - }) - .collect(); - - // Determine total response size from filtered params. let total_size = active_params .iter() .zip(effective_sizes.iter()) @@ -229,74 +188,13 @@ impl ResponseEncoder { .unwrap_or(UDS_POSITIVE_RESPONSE_MIN_SIZE); let mut response = vec![0u8; total_size]; - - for (param, &eff_size) in active_params.iter().zip(effective_sizes.iter()) { - // Skip MUX case markers โ€” they're only used for total_size computation. - if param.name.starts_with("__mux_case__/") { - continue; - } - let pos = param.byte_position as usize; - - if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { - continue; - } - - match ¶m.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - // The SID byte is stored as a decimal string (e.g. "98" for 0x62). - if let Ok(val) = coded_value.parse::() { - let bytes = encode_unsigned_be(val); - let copy_len = bytes.len().min(eff_size); - // Right-align in the field (big-endian convention). - let offset = eff_size.saturating_sub(copy_len); - let dst_start = pos.saturating_add(offset); - let dst_end = dst_start.saturating_add(copy_len); - let src_start = bytes.len().saturating_sub(copy_len); - if let (Some(dst), Some(src)) = - (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) - { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { - // DID bytes from the original request, big-endian. - let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; - let copy_len = did_bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - did_bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // For MUX case params, try the short name (after '/') as well. - let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); - let value = response_data - .get(¶m.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - - if param.byte_size.is_some() { - encode_value_at(&mut response, pos, eff_size, value); - } else { - // Variable-size param: write the raw byte representation. - let bytes = value_to_bytes(value); - let copy_len = bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} - } - } + encode_params_into_response( + &mut response, + &active_params, + &effective_sizes, + response_data, + did, + ); tracing::debug!( "[MDD] Built UDS response via metadata for '{}'): {:02X?}", @@ -335,12 +233,161 @@ impl ResponseEncoder { } } +/// Keep only the parameters that are active for the given MUX case. +/// +/// - Top-level params (no `/` in name) are always included. +/// - When `mux_case_prefix` is `Some`, only sub-params whose name starts with +/// that prefix (plus the corresponding `__mux_case__` marker) are kept. +/// - When `mux_case_prefix` is `None`, all params without `/` are kept and +/// any `__mux_case__/` entries are dropped. +fn filter_active_params<'a>( + meta: &'a [cda_interfaces::ResponseParameterInfo], + mux_case_prefix: Option<&str>, +) -> Vec<&'a cda_interfaces::ResponseParameterInfo> { + let mux_marker_name: Option = + mux_case_prefix.map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + meta.iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = mux_case_prefix { + p.name.starts_with(prefix) || mux_marker_name.as_deref() == Some(p.name.as_str()) + } else { + !p.name.starts_with("__mux_case__/") + } + }) + .collect() +} + +/// Determine the effective byte size of each active parameter. +/// +/// Fixed-size params use `byte_size` directly. Variable-size `VALUE` params +/// (where `byte_size` is `None`) infer their size from the serialised form of +/// the matching value in `response_data`. +fn compute_effective_sizes( + active_params: &[&cda_interfaces::ResponseParameterInfo], + response_data: &HashMap, +) -> Vec { + active_params + .iter() + .map(|p| { + if let Some(s) = p.byte_size { + return s as usize; + } + // Variable-size VALUE param -- infer size from the data. + if !matches!( + &p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + ) { + return 0; + } + let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); + let value = response_data + .get(&p.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + value_to_bytes(value).len() + }) + .collect() +} + +/// Write each active parameter into `response` at its MDD-defined byte position. +/// +/// - `__mux_case__/` markers are skipped (used only for size computation). +/// - Out-of-bounds or zero-size writes are silently ignored. +/// +/// # Note on casts +/// +/// `u16 >> 8` and `u16 & 0xFF` both fit in a `u8`; the truncating casts are +/// intentional and cannot overflow. +#[allow(clippy::cast_possible_truncation)] +fn encode_params_into_response( + response: &mut [u8], + active_params: &[&cda_interfaces::ResponseParameterInfo], + effective_sizes: &[usize], + response_data: &HashMap, + did: u16, +) { + for (param, &eff_size) in active_params.iter().zip(effective_sizes) { + // MUX case markers are only used for total_size computation. + if param.name.starts_with("__mux_case__/") { + continue; + } + let pos = param.byte_position as usize; + + if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { + continue; + } + + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // The SID byte is stored as a decimal string (e.g. "98" for 0x62). + if let Ok(val) = coded_value.parse::() { + let bytes = encode_unsigned_be(val); + let copy_len = bytes.len().min(eff_size); + // Right-align in the field (big-endian convention). + let offset = eff_size.saturating_sub(copy_len); + let dst_start = pos.saturating_add(offset); + let dst_end = dst_start.saturating_add(copy_len); + let src_start = bytes.len().saturating_sub(copy_len); + if let (Some(dst), Some(src)) = + (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) + { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { + // DID bytes from the original request, big-endian. + let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; + let copy_len = did_bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + did_bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // For MUX case params, try the short name (after '/') as well. + let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); + let value = response_data + .get(¶m.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get("data")); + if param.byte_size.is_some() { + encode_value_at(response, pos, eff_size, value); + } else { + // Variable-size param: write the raw byte representation. + let bytes = value_to_bytes(value); + let copy_len = bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} + } + } +} + #[cfg(test)] mod tests { - use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; + use cda_interfaces::{HashMap, ParameterTypeMetadata, ResponseParameterInfo}; - use super::super::uds_helpers::{ - encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, + use super::{ + super::uds_helpers::{ + encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, + }, + compute_effective_sizes, filter_active_params, }; /// Numbers are right-aligned (big-endian) in the target field. @@ -515,22 +562,8 @@ mod tests { ]; let mux_case_prefix = find_mux_case_prefix(&meta, did); - let mux_marker_name: Option = mux_case_prefix - .as_deref() - .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - - let active: Vec<_> = meta - .iter() - .filter(|p| { - if !p.name.contains('/') { - true - } else if let Some(prefix) = &mux_case_prefix { - p.name.starts_with(prefix.as_str()) - || mux_marker_name.as_deref() == Some(p.name.as_str()) - } else { - !p.name.starts_with("__mux_case__/") - } - }) + let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) + .into_iter() .map(|p| p.name.as_str()) .collect(); @@ -556,9 +589,8 @@ mod tests { let mux_case_prefix = find_mux_case_prefix(&meta, did); assert!(mux_case_prefix.is_none()); - let active: Vec<_> = meta - .iter() - .filter(|p| !p.name.contains('/') || p.name.starts_with("__mux_case__/")) + let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) + .into_iter() .map(|p| p.name.as_str()) .collect(); @@ -573,12 +605,11 @@ mod tests { value_param("DID", 1, 2), value_param("DATA", 3, 17), ]; - let effective_sizes: Vec = params - .iter() - .map(|p| p.byte_size.map_or(0, |s| s as usize)) - .collect(); + let active_refs: Vec<&_> = params.iter().collect(); + // All params have fixed byte_size, so response_data is not consulted. + let effective_sizes = compute_effective_sizes(&active_refs, &HashMap::default()); - let total = params + let total = active_refs .iter() .zip(effective_sizes.iter()) .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) From caee347a76f794d11831121d2c2f9c96b814b285 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 30 Apr 2026 11:45:00 +0200 Subject: [PATCH 15/33] refactor: address review comments for service_parsing --- Cargo.lock | 4 +- proxy-core/src/config.rs | 757 +++++++------------- proxy-core/src/service_resolver/resolve.rs | 7 +- proxy-core/src/service_resolver/response.rs | 328 ++++----- 4 files changed, 426 insertions(+), 670 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3c84452..de0fdde 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2669,9 +2669,9 @@ dependencies = [ [[package]] name = "zerofrom" -version = "0.1.8" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" dependencies = [ "zerofrom-derive", ] diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index 4d4d6b9..b2cdafd 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -12,17 +12,33 @@ use std::{ net::{IpAddr, Ipv4Addr}, - path::PathBuf, + path::Path, }; -use clap::Parser; use serde::{Deserialize, Deserializer, de}; -use url::Url; use crate::error::{ProxyError, Result}; -#[derive(Deserialize, Default)] -#[serde(default)] +/// Required byte length for EID and GID fields per ISO 13400-2. +const EID_GID_BYTE_LENGTH: usize = 6; + +// Default values for ServerConfig. +const DEFAULT_DOIP_PORT: u16 = 13400; +const DEFAULT_MAX_CONNECTIONS: usize = 10; +/// DoIP source address (tester logical address used in response messages). +const DEFAULT_SOURCE_ADDRESS: u16 = 0x0E80; + +// Default values for SovdConfig. +const DEFAULT_GATEWAY_URL: &str = "http://localhost:20002"; +const DEFAULT_CLIENT_ID: &str = "uds2sovd_proxy"; +const DEFAULT_CLIENT_SECRET: &str = "test_secret"; +const DEFAULT_TIMEOUT_MS: u64 = 5000; +const DEFAULT_API_VERSION: &str = "v15"; + +// Default values for EcuConfig. +const DEFAULT_ECU_NAME: &str = "ECU"; +/// Top-level proxy configuration loaded from a TOML file. +#[derive(Debug, Clone, Deserialize, Default)] pub struct Config { /// `DoIP` server settings (port, bind address, source address). pub server: ServerConfig, @@ -34,33 +50,23 @@ pub struct Config { pub logging: LoggingConfig, } -#[derive(Deserialize)] -#[serde(default)] +/// `DoIP` server configuration. +#[derive(Debug, Clone, Deserialize)] pub struct ServerConfig { - /// TCP port for the `DoIP` server (default: 13 400). + /// TCP port for the `DoIP` server (default: 13400). #[serde(deserialize_with = "deserialize_nonzero_u16")] pub doip_port: u16, - /// IP address to bind the server socket to (default: `0.0.0.0`). + /// IP address to bind the server socket to. + #[serde(deserialize_with = "deserialize_ip_addr")] pub bind_address: IpAddr, - /// Maximum number of concurrent connections (default: 10). + /// Maximum number of concurrent connections. #[serde(deserialize_with = "deserialize_max_connections")] pub max_connections: usize, - /// `DoIP` source address used in response messages (default: `0x0E80`). + /// `DoIP` source address used in response messages. #[serde(deserialize_with = "deserialize_nonzero_u16")] pub source_address: u16, } -impl Default for ServerConfig { - fn default() -> Self { - Self { - doip_port: 13_400, - bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), - max_connections: 10, - source_address: 0x0E80, - } - } -} - fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -71,6 +77,16 @@ fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( Ok(v) } +/// Deserialize IP address string into `std::net::IpAddr`. +fn deserialize_ip_addr<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let s = String::deserialize(deserializer)?; + s.parse::() + .map_err(|_| de::Error::custom(format!("invalid IP address: {s}"))) +} + +/// Reject zero during deserialization for `usize` fields. fn deserialize_max_connections<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -81,11 +97,22 @@ fn deserialize_max_connections<'de, D: Deserializer<'de>>( Ok(v) } -#[derive(Clone, Deserialize)] -#[serde(default)] +/// Reject empty gateway URL strings during deserialization. +fn deserialize_nonempty_gateway_url<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let s = String::deserialize(deserializer)?; + if s.is_empty() { + return Err(de::Error::custom("gateway_url must not be empty")); + } + Ok(s) +} +/// SOVD gateway connection configuration. +#[derive(Debug, Clone, Deserialize)] pub struct SovdConfig { /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). - pub gateway_url: Url, + #[serde(deserialize_with = "deserialize_nonempty_gateway_url")] + pub gateway_url: String, /// `OAuth2` client ID for gateway authentication. pub client_id: String, /// `OAuth2` client secret for gateway authentication. @@ -95,541 +122,291 @@ pub struct SovdConfig { /// SOVD API version path segment (e.g. `v15`). pub api_version: String, /// Whether to request inline schema in data responses. + #[serde(default = "SovdConfig::default_include_schema")] pub include_schema: bool, /// When `true`, bypass HTTP calls and generate synthetic responses. + #[serde(default)] pub mock_gateway: bool, } -impl Default for SovdConfig { - fn default() -> Self { - Self { - gateway_url: "http://localhost:20002" - .parse() - .expect("hard-coded URL is always valid"), - client_id: "uds2sovd_proxy".into(), - client_secret: "test_secret".into(), - timeout_ms: 5_000, - api_version: "v15".into(), - include_schema: true, - mock_gateway: true, - } - } -} - -#[derive(Clone, Copy, Deserialize)] -pub struct EidGid([u8; 6]); - -impl EidGid { - fn is_all_zeros(self) -> bool { - self.0 == [0u8; 6] - } -} - -impl Default for EidGid { - fn default() -> Self { - Self([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]) +impl SovdConfig { + fn default_include_schema() -> bool { + true } } -#[derive(Deserialize)] -#[serde(default)] +/// ECU identity and addressing configuration. +#[derive(Debug, Clone, Deserialize)] pub struct EcuConfig { /// Default ECU name used for SOVD component path. pub default_name: String, /// ISO 13400 logical address of the target ECU. #[serde(deserialize_with = "deserialize_nonzero_u16")] pub logical_address: u16, - /// 6-byte Entity Identification - pub eid: EidGid, + /// 6-byte Entity Identification (MAC address). + pub eid: [u8; EID_GID_BYTE_LENGTH], /// 6-byte Group Identification. - pub gid: EidGid, -} - -impl Default for EcuConfig { - fn default() -> Self { - Self { - default_name: "ECU".into(), - logical_address: 0x0001, - eid: EidGid::default(), - gid: EidGid::default(), - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] -#[serde(rename_all = "lowercase")] -pub enum LogLevel { - Error, - Warn, - #[default] - Info, - Debug, - Trace, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] -#[serde(rename_all = "lowercase")] -pub enum LogFormat { - /// Human-readable coloured output (default). - #[default] - Pretty, - /// Machine-readable JSON (suitable for log aggregators). - Json, + pub gid: [u8; EID_GID_BYTE_LENGTH], } /// Logging output configuration. -#[derive(Deserialize, Default)] -#[serde(default)] +#[derive(Debug, Clone, Deserialize)] pub struct LoggingConfig { - /// Log level filter. - pub level: LogLevel, - /// Output format. - pub format: LogFormat, -} - -/// Any flag set here overrides the corresponding value from the TOML file. -#[derive(Parser)] -#[command(name = "uds2sovd-proxy", version)] -pub struct Cli { - /// Path to the TOML configuration file. - #[arg( - short, - long, - value_name = "FILE", - env = "PROXY_CONFIG", - default_value = "config/config.toml" - )] - pub config: PathBuf, - - /// Override the IP address to bind to. - #[arg(long, value_name = "ADDR", env = "PROXY_BIND_ADDRESS")] - pub bind_address: Option, - - /// Override the SOVD gateway URL. - #[arg(long, value_name = "URL", env = "PROXY_GATEWAY_URL")] - pub gateway_url: Option, - - /// Enable mock gateway mode (no real HTTP calls). - #[arg(long, env = "PROXY_MOCK_GATEWAY")] - pub mock_gateway: bool, - - /// Override the log level. - #[arg(long, value_enum, value_name = "LEVEL", env = "PROXY_LOG_LEVEL")] - pub log_level: Option, - - /// Override the log output format. - #[arg(long, value_enum, value_name = "FORMAT", env = "PROXY_LOG_FORMAT")] - pub log_format: Option, - - /// MDD file to load (absolute path, or filename resolved under `--mdd-dir`). - #[arg(short, long)] - pub mdd_file: PathBuf, - - /// Directory searched when `--mdd-file` is a relative filename. - #[arg(long, default_value = "testcontainer/mdd")] - pub mdd_dir: PathBuf, + /// Log level filter (e.g. `info`, `debug`, `trace`). + pub level: String, + /// Output format: `pretty` (default) or `json`. + pub format: String, } impl Config { - /// Build a fully-validated [`Config`] by layering defaults, a TOML file, - /// and CLI overrides. - /// - /// # Layer order - /// 1. [`Default`] values - /// 2. TOML file at the path given by `cli.config` - /// 3. CLI flags - /// - /// # Errors - /// Returns [`ProxyError::Config`] if the TOML file cannot be read/parsed - /// or if the merged configuration fails validation. - pub fn load(cli: &Cli) -> Result { - // defaults + TOML file - let mut config = if cli.config.exists() { - Self::from_file(&cli.config)? - } else { - Self::default() - }; - - // CLI overrides - if let Some(addr) = cli.bind_address { - config.server.bind_address = addr; - } - if let Some(ref url) = cli.gateway_url { - config.sovd.gateway_url = url.clone(); - } - if cli.mock_gateway { - config.sovd.mock_gateway = true; - } - if let Some(level) = cli.log_level { - config.logging.level = level; - } - if let Some(format) = cli.log_format { - config.logging.format = format; - } - - config.validate()?; - Ok(config) - } - - /// Load and validate configuration from a TOML file (without CLI overrides). + /// Load configuration from TOML file /// /// # Errors - /// Returns [`ProxyError::Config`] if the file cannot be read, parsed, or - /// if the resulting configuration fails validation. - pub fn from_file>(path: P) -> Result { - let path = path.as_ref(); + /// Returns an error if the file cannot be read or parsed. + pub fn from_file>(path: P) -> Result { let content = std::fs::read_to_string(path) - .map_err(|e| ProxyError::Config(format!("cannot read `{}`: {e}", path.display())))?; + .map_err(|e| ProxyError::Config(format!("Failed to read config file: {e}")))?; - let config: Self = toml::from_str(&content) - .map_err(|e| ProxyError::Config(format!("cannot parse `{}`: {e}", path.display())))?; - - config.validate()?; - Ok(config) + toml::from_str(&content) + .map_err(|e| ProxyError::Config(format!("Failed to parse config: {e}"))) } +} - /// Validate the fully-merged configuration. - fn validate(&self) -> Result<()> { - let mut errors: Vec = Vec::new(); - - if self.server.max_connections == 0 { - errors.push("[server] max_connections must be greater than zero".into()); - } - if self.sovd.client_id.is_empty() { - errors.push("[sovd] client_id must not be empty".into()); - } - if self.sovd.api_version.is_empty() { - errors.push("[sovd] api_version must not be empty".into()); - } - if self.ecu.default_name.is_empty() { - errors.push("[ecu] default_name must not be empty".into()); - } - if self.ecu.eid.is_all_zeros() { - errors.push("[ecu] eid must not be all zeros".into()); - } - if self.ecu.gid.is_all_zeros() { - errors.push("[ecu] gid must not be all zeros".into()); - } - - if errors.is_empty() { - Ok(()) - } else { - Err(ProxyError::Config(format!( - "configuration validation failed:\n - {}", - errors.join("\n - ") - ))) +impl Default for ServerConfig { + fn default() -> Self { + Self { + doip_port: DEFAULT_DOIP_PORT, + bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), + max_connections: DEFAULT_MAX_CONNECTIONS, + source_address: DEFAULT_SOURCE_ADDRESS, } } } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn eid_gid_holds_expected_bytes() { - let eid = EidGid([0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); - assert_eq!(eid.0, [0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); - } - - #[test] - fn eid_gid_all_zeros_detected() { - let eid = EidGid([0u8; 6]); - assert!(eid.is_all_zeros()); - - let eid2 = EidGid([0, 1, 2, 3, 4, 5]); - assert!(!eid2.is_all_zeros()); - } - - #[test] - fn log_level_deserializes_all_variants_from_toml() { - #[derive(Deserialize)] - struct Wrapper { - level: LogLevel, - } - - for (raw, expected) in [ - ("error", LogLevel::Error), - ("warn", LogLevel::Warn), - ("info", LogLevel::Info), - ("debug", LogLevel::Debug), - ("trace", LogLevel::Trace), - ] { - let parsed: Wrapper = - toml::from_str(&format!("level = \"{raw}\"")).expect("valid level"); - assert_eq!(parsed.level, expected); +impl Default for SovdConfig { + fn default() -> Self { + Self { + gateway_url: DEFAULT_GATEWAY_URL.to_string(), + client_id: DEFAULT_CLIENT_ID.to_string(), + client_secret: DEFAULT_CLIENT_SECRET.to_string(), + timeout_ms: DEFAULT_TIMEOUT_MS, + api_version: DEFAULT_API_VERSION.to_string(), + include_schema: true, + mock_gateway: false, } } +} - #[test] - fn log_format_deserializes_all_variants_from_toml() { - #[derive(Deserialize)] - struct Wrapper { - format: LogFormat, - } - - for (raw, expected) in [("pretty", LogFormat::Pretty), ("json", LogFormat::Json)] { - let parsed: Wrapper = - toml::from_str(&format!("format = \"{raw}\"")).expect("valid format"); - assert_eq!(parsed.format, expected); +impl Default for EcuConfig { + fn default() -> Self { + Self { + default_name: DEFAULT_ECU_NAME.to_string(), + logical_address: 0x0001, + eid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], + gid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], } } +} - #[test] - fn server_defaults_are_sane() { - let s = ServerConfig::default(); - assert_eq!(s.doip_port, 13_400); - assert_eq!(s.max_connections, 10); - } - - #[test] - fn sovd_defaults_are_sane() { - let s = SovdConfig::default(); - assert!(s.mock_gateway); - assert!(s.include_schema); - assert_eq!(s.timeout_ms, 5_000); - } - - #[test] - fn validation_rejects_empty_client_id() { - let mut config = Config::default(); - config.sovd.client_id = String::new(); - assert!(config.validate().is_err()); +impl Default for LoggingConfig { + fn default() -> Self { + Self { + level: "info".to_string(), + format: "pretty".to_string(), + } } +} - #[test] - fn validation_rejects_all_zero_eid() { - let mut config = Config::default(); - config.ecu.eid = EidGid([0u8; 6]); - assert!(config.validate().is_err()); - } +#[cfg(test)] +mod tests { + use super::*; #[test] - fn validation_rejects_zero_max_connections() { - let mut config = Config::default(); - config.server.max_connections = 0; - assert!(config.validate().is_err()); + fn test_default_config() { + let config = Config::default(); + assert_eq!(config.server.doip_port, 13400); + assert_eq!(config.sovd.api_version, "v15"); + assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); } #[test] - fn validation_accumulates_multiple_errors() { - let mut config = Config::default(); - config.sovd.client_id = String::new(); - config.sovd.api_version = String::new(); - config.ecu.eid = EidGid([0u8; 6]); - let err = config.validate().unwrap_err().to_string(); - // Three separate bullets should appear. - assert_eq!(err.matches(" - ").count(), 3); + fn test_deserialize_valid_config() { + let toml_str = r#" + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let config: Config = toml::from_str(toml_str).expect("valid config should parse"); + assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); + assert_eq!(config.server.doip_port, 13400); } #[test] - fn toml_parses_complete_config() { - let raw = r#" -[server] -bind_address = "127.0.0.1" -max_connections = 5 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 3000 -api_version = "v15" -include_schema = false -mock_gateway = true - -[ecu] -default_name = "TEST_ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "debug" -format = "json" -"#; - let cfg: Config = toml::from_str(raw).expect("valid TOML"); - assert!(cfg.sovd.mock_gateway); - assert_eq!(cfg.logging.level, LogLevel::Debug); - assert_eq!(cfg.logging.format, LogFormat::Json); + fn test_deserialize_rejects_zero_port() { + let toml_str = r#" + [server] + doip_port = 0 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "doip_port=0 should be rejected"); } #[test] - fn deserialize_rejects_zero_max_connections() { + fn test_deserialize_rejects_zero_max_connections() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 0 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 0 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "max_connections=0 should be rejected"); } #[test] - fn deserialize_rejects_zero_logical_address() { + fn test_deserialize_rejects_zero_logical_address() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 0 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 0 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "logical_address=0 should be rejected"); } #[test] - fn deserialize_rejects_wrong_eid_length() { + fn test_deserialize_rejects_wrong_eid_length() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "eid with wrong length should be rejected"); } #[test] - fn deserialize_rejects_invalid_gateway_url() { - let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "not a valid url" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; - let result = toml::from_str::(toml_str); - assert!(result.is_err(), "invalid gateway_url should be rejected"); - } - - #[test] - fn deserialize_rejects_invalid_log_level() { + fn test_deserialize_rejects_empty_gateway_url() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "verbose" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); - assert!(result.is_err(), "invalid log level should be rejected"); - } - - // โ”€โ”€ CLI integration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - - #[test] - fn cli_overrides_default_values() { - let cli = Cli::parse_from([ - "uds2sovd-proxy", - "--config", - "/nonexistent/path.toml", - "--log-level", - "debug", - "--mock-gateway", - "--mdd-file", - "test.mdd", - ]); - - let config = Config::load(&cli).expect("should build from defaults + CLI"); - assert_eq!(config.logging.level, LogLevel::Debug); - assert!(config.sovd.mock_gateway); - } - - #[test] - fn toml_with_missing_sections_uses_defaults() { - let raw = r#" -[server] -bind_address = "127.0.0.1" -max_connections = 5 -source_address = 3712 -"#; - let cfg: Config = toml::from_str(raw).expect("partial TOML should parse"); - assert_eq!(cfg.sovd.api_version, "v15"); - assert_eq!(cfg.logging.level, LogLevel::Info); + assert!(result.is_err(), "empty gateway_url should be rejected"); } } diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs index e9fdf7e..d660271 100644 --- a/proxy-core/src/service_resolver/resolve.rs +++ b/proxy-core/src/service_resolver/resolve.rs @@ -136,7 +136,12 @@ impl DidResolver { // `did` is `u16`; `did >> 8` is at most 0xFF and `did & 0xFF` is at most 0xFF, // so both narrowing casts to `u8` are safe and can never truncate. #[allow(clippy::cast_possible_truncation)] - async fn resolve_service_did(&self, sid: u8, did: u16, label: &str) -> Option { + async fn resolve_service_did( + &self, + sid: u8, + did: u16, + label: &str, + ) -> Option { let manager = self.manager.read().await; // Step 1 + 2: prefix lookup and candidate list construction. diff --git a/proxy-core/src/service_resolver/response.rs b/proxy-core/src/service_resolver/response.rs index b7fc21c..c11729c 100644 --- a/proxy-core/src/service_resolver/response.rs +++ b/proxy-core/src/service_resolver/response.rs @@ -28,15 +28,20 @@ use super::{ }, }; +/// Fallback JSON key for SOVD `ObjectDataItem` responses where the value is +/// stored under a generic `"data"` field (used when MDD parameter names do +/// not match any key in the SOVD response map). +const SOVD_DATA_FIELD_KEY: &str = "data"; + /// Encodes SOVD JSON data into UDS response bytes using MDD metadata. -pub(crate) struct ResponseEncoder { +pub struct ResponseEncoder { manager: ManagerHandle, metadata: MetadataProvider, } impl ResponseEncoder { /// Create a new response encoder. - pub(crate) fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { + pub fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { Self { manager, metadata } } @@ -60,7 +65,7 @@ impl ResponseEncoder { /// -- /// once the SOVD server returns pre-encoded UDS bytes, both encoding /// paths can be removed. - pub(crate) async fn build_response( + pub async fn build_response( &self, service_name: &str, sid: u8, @@ -105,9 +110,6 @@ impl ResponseEncoder { response.extend(encode_unsigned_be(num)); } else if let Some(num) = n.as_i64() { let unsigned = num.cast_unsigned(); - // For negative numbers: if they fit in one byte, use direct cast; - // otherwise, split into high and low bytes. Truncation is intentional - // for single-byte encoding of small negative values. #[allow(clippy::cast_possible_truncation)] if u8::try_from(unsigned).is_ok() { response.push(unsigned as u8); @@ -119,8 +121,6 @@ impl ResponseEncoder { } serde_json::Value::Array(arr) => { for item in arr { - // Array elements are expected to represent raw bytes; - // values > 255 are truncated to the low byte by design. #[allow(clippy::cast_possible_truncation)] if let Some(byte) = item.as_u64() { response.push(byte as u8); @@ -176,10 +176,56 @@ impl ResponseEncoder { return None; } + // Find the MUX case matching this DID (floor-based). let mux_case_prefix = find_mux_case_prefix(&meta, did); - let active_params = filter_active_params(&meta, mux_case_prefix.as_deref()); - let effective_sizes = compute_effective_sizes(&active_params, response_data); + // Derive the case marker name for total_size computation. + let mux_marker_name: Option = mux_case_prefix + .as_deref() + .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + // Keep top-level params (no '/') plus matching MUX case sub-params. + let active_params: Vec<_> = meta + .iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = &mux_case_prefix { + p.name.starts_with(prefix.as_str()) + || mux_marker_name.as_deref() == Some(&p.name) + } else { + !p.name.starts_with("__mux_case__/") + } + }) + .collect(); + + // Resolve effective size: for VALUE params with `byte_size: None` + // (variable-length DOPs), infer the size from actual response data. + let effective_sizes: Vec = active_params + .iter() + .map(|p| { + if let Some(s) = p.byte_size { + return s as usize; + } + // Variable-size VALUE param -- infer size from the data. + if !matches!( + &p.param_type, + cda_interfaces::ParameterTypeMetadata::Value { .. } + ) { + return 0; + } + let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); + let value = response_data + .get(&p.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get(SOVD_DATA_FIELD_KEY)); + value_to_bytes(value).len() + }) + .collect(); + + // Determine total response size from filtered params. let total_size = active_params .iter() .zip(effective_sizes.iter()) @@ -188,13 +234,74 @@ impl ResponseEncoder { .unwrap_or(UDS_POSITIVE_RESPONSE_MIN_SIZE); let mut response = vec![0u8; total_size]; - encode_params_into_response( - &mut response, - &active_params, - &effective_sizes, - response_data, - did, - ); + + for (param, &eff_size) in active_params.iter().zip(effective_sizes.iter()) { + // Skip MUX case markers โ€” they're only used for total_size computation. + if param.name.starts_with("__mux_case__/") { + continue; + } + let pos = param.byte_position as usize; + + if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { + continue; + } + + match ¶m.param_type { + cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { + // The SID byte is stored as a decimal string (e.g. "98" for 0x62). + if let Ok(val) = coded_value.parse::() { + let bytes = encode_unsigned_be(val); + let copy_len = bytes.len().min(eff_size); + // Right-align in the field (big-endian convention). + let offset = eff_size.saturating_sub(copy_len); + let dst_start = pos.saturating_add(offset); + let dst_end = dst_start.saturating_add(copy_len); + let src_start = bytes.len().saturating_sub(copy_len); + if let (Some(dst), Some(src)) = + (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) + { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { + // DID bytes from the original request, big-endian. + let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; + let copy_len = did_bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + did_bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + cda_interfaces::ParameterTypeMetadata::Value { .. } => { + // For MUX case params, try the short name (after '/') as well. + let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); + let value = response_data + .get(¶m.name) + .or_else(|| response_data.get(short_name)) + .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) + .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) + .or_else(|| response_data.get(SOVD_DATA_FIELD_KEY)); + + if param.byte_size.is_some() { + encode_value_at(&mut response, pos, eff_size, value); + } else { + // Variable-size param: write the raw byte representation. + let bytes = value_to_bytes(value); + let copy_len = bytes.len().min(eff_size); + if let (Some(dst), Some(src)) = ( + response.get_mut(pos..pos.saturating_add(copy_len)), + bytes.get(..copy_len), + ) { + dst.copy_from_slice(src); + } + } + } + cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} + } + } tracing::debug!( "[MDD] Built UDS response via metadata for '{}'): {:02X?}", @@ -233,161 +340,12 @@ impl ResponseEncoder { } } -/// Keep only the parameters that are active for the given MUX case. -/// -/// - Top-level params (no `/` in name) are always included. -/// - When `mux_case_prefix` is `Some`, only sub-params whose name starts with -/// that prefix (plus the corresponding `__mux_case__` marker) are kept. -/// - When `mux_case_prefix` is `None`, all params without `/` are kept and -/// any `__mux_case__/` entries are dropped. -fn filter_active_params<'a>( - meta: &'a [cda_interfaces::ResponseParameterInfo], - mux_case_prefix: Option<&str>, -) -> Vec<&'a cda_interfaces::ResponseParameterInfo> { - let mux_marker_name: Option = - mux_case_prefix.map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); - - meta.iter() - .filter(|p| { - if !p.name.contains('/') { - true - } else if let Some(prefix) = mux_case_prefix { - p.name.starts_with(prefix) || mux_marker_name.as_deref() == Some(p.name.as_str()) - } else { - !p.name.starts_with("__mux_case__/") - } - }) - .collect() -} - -/// Determine the effective byte size of each active parameter. -/// -/// Fixed-size params use `byte_size` directly. Variable-size `VALUE` params -/// (where `byte_size` is `None`) infer their size from the serialised form of -/// the matching value in `response_data`. -fn compute_effective_sizes( - active_params: &[&cda_interfaces::ResponseParameterInfo], - response_data: &HashMap, -) -> Vec { - active_params - .iter() - .map(|p| { - if let Some(s) = p.byte_size { - return s as usize; - } - // Variable-size VALUE param -- infer size from the data. - if !matches!( - &p.param_type, - cda_interfaces::ParameterTypeMetadata::Value { .. } - ) { - return 0; - } - let short_name = p.name.rsplit('/').next().unwrap_or(&p.name); - let value = response_data - .get(&p.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(&p.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - value_to_bytes(value).len() - }) - .collect() -} - -/// Write each active parameter into `response` at its MDD-defined byte position. -/// -/// - `__mux_case__/` markers are skipped (used only for size computation). -/// - Out-of-bounds or zero-size writes are silently ignored. -/// -/// # Note on casts -/// -/// `u16 >> 8` and `u16 & 0xFF` both fit in a `u8`; the truncating casts are -/// intentional and cannot overflow. -#[allow(clippy::cast_possible_truncation)] -fn encode_params_into_response( - response: &mut [u8], - active_params: &[&cda_interfaces::ResponseParameterInfo], - effective_sizes: &[usize], - response_data: &HashMap, - did: u16, -) { - for (param, &eff_size) in active_params.iter().zip(effective_sizes) { - // MUX case markers are only used for total_size computation. - if param.name.starts_with("__mux_case__/") { - continue; - } - let pos = param.byte_position as usize; - - if eff_size == 0 || pos.saturating_add(eff_size) > response.len() { - continue; - } - - match ¶m.param_type { - cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } => { - // The SID byte is stored as a decimal string (e.g. "98" for 0x62). - if let Ok(val) = coded_value.parse::() { - let bytes = encode_unsigned_be(val); - let copy_len = bytes.len().min(eff_size); - // Right-align in the field (big-endian convention). - let offset = eff_size.saturating_sub(copy_len); - let dst_start = pos.saturating_add(offset); - let dst_end = dst_start.saturating_add(copy_len); - let src_start = bytes.len().saturating_sub(copy_len); - if let (Some(dst), Some(src)) = - (response.get_mut(dst_start..dst_end), bytes.get(src_start..)) - { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::MatchingRequestParam { .. } => { - // DID bytes from the original request, big-endian. - let did_bytes = [(did >> 8) as u8, (did & 0xFF) as u8]; - let copy_len = did_bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - did_bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - cda_interfaces::ParameterTypeMetadata::Value { .. } => { - // For MUX case params, try the short name (after '/') as well. - let short_name = param.name.rsplit('/').next().unwrap_or(¶m.name); - let value = response_data - .get(¶m.name) - .or_else(|| response_data.get(short_name)) - .or_else(|| response_data.get(¶m.name.to_ascii_lowercase())) - .or_else(|| response_data.get(&short_name.to_ascii_lowercase())) - .or_else(|| response_data.get("data")); - if param.byte_size.is_some() { - encode_value_at(response, pos, eff_size, value); - } else { - // Variable-size param: write the raw byte representation. - let bytes = value_to_bytes(value); - let copy_len = bytes.len().min(eff_size); - if let (Some(dst), Some(src)) = ( - response.get_mut(pos..pos.saturating_add(copy_len)), - bytes.get(..copy_len), - ) { - dst.copy_from_slice(src); - } - } - } - cda_interfaces::ParameterTypeMetadata::PhysConst { .. } => {} - } - } -} - #[cfg(test)] mod tests { - use cda_interfaces::{HashMap, ParameterTypeMetadata, ResponseParameterInfo}; + use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; - use super::{ - super::uds_helpers::{ - encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, - }, - compute_effective_sizes, filter_active_params, + use super::super::uds_helpers::{ + encode_unsigned_be, encode_value_at, find_mux_case_prefix, value_to_bytes, }; /// Numbers are right-aligned (big-endian) in the target field. @@ -562,8 +520,22 @@ mod tests { ]; let mux_case_prefix = find_mux_case_prefix(&meta, did); - let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) - .into_iter() + let mux_marker_name: Option = mux_case_prefix + .as_deref() + .map(|pfx| format!("__mux_case__/{}", pfx.trim_end_matches('/'))); + + let active: Vec<_> = meta + .iter() + .filter(|p| { + if !p.name.contains('/') { + true + } else if let Some(prefix) = &mux_case_prefix { + p.name.starts_with(prefix.as_str()) + || mux_marker_name.as_deref() == Some(p.name.as_str()) + } else { + !p.name.starts_with("__mux_case__/") + } + }) .map(|p| p.name.as_str()) .collect(); @@ -589,8 +561,9 @@ mod tests { let mux_case_prefix = find_mux_case_prefix(&meta, did); assert!(mux_case_prefix.is_none()); - let active: Vec<_> = filter_active_params(&meta, mux_case_prefix.as_deref()) - .into_iter() + let active: Vec<_> = meta + .iter() + .filter(|p| !p.name.contains('/') || p.name.starts_with("__mux_case__/")) .map(|p| p.name.as_str()) .collect(); @@ -605,11 +578,12 @@ mod tests { value_param("DID", 1, 2), value_param("DATA", 3, 17), ]; - let active_refs: Vec<&_> = params.iter().collect(); - // All params have fixed byte_size, so response_data is not consulted. - let effective_sizes = compute_effective_sizes(&active_refs, &HashMap::default()); + let effective_sizes: Vec = params + .iter() + .map(|p| p.byte_size.map_or(0, |s| s as usize)) + .collect(); - let total = active_refs + let total = params .iter() .zip(effective_sizes.iter()) .map(|(p, &sz)| (p.byte_position as usize).saturating_add(sz)) From d3f52796a170493a419cb9e944f23b59f93c3e70 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Wed, 22 Apr 2026 09:57:49 +0200 Subject: [PATCH 16/33] feat: add proxy-sovd crate with SOVD REST client and UDS<->SOVD mapper Signed-off-by: Arvind Rathod --- Cargo.lock | 741 ++++++++++++++++++++++++++------- Cargo.toml | 5 +- proxy-sovd/Cargo.toml | 31 ++ proxy-sovd/src/client.rs | 703 +++++++++++++++++++++++++++++++ proxy-sovd/src/diag_handler.rs | 101 +++++ proxy-sovd/src/lib.rs | 26 ++ proxy-sovd/src/mapper.rs | 285 +++++++++++++ proxy-sovd/src/schema.rs | 92 ++++ 8 files changed, 1841 insertions(+), 143 deletions(-) create mode 100644 proxy-sovd/Cargo.toml create mode 100644 proxy-sovd/src/client.rs create mode 100644 proxy-sovd/src/diag_handler.rs create mode 100644 proxy-sovd/src/lib.rs create mode 100644 proxy-sovd/src/mapper.rs create mode 100644 proxy-sovd/src/schema.rs diff --git a/Cargo.lock b/Cargo.lock index de0fdde..b749c0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,56 +46,6 @@ dependencies = [ "libc", ] -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys", -] - [[package]] name = "anyhow" version = "1.0.102" @@ -113,6 +63,12 @@ dependencies = [ "syn", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.0" @@ -349,6 +305,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + [[package]] name = "chrono" version = "0.4.44" @@ -362,52 +324,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - [[package]] name = "const-oid" version = "0.9.6" @@ -436,7 +352,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", - "rand_core", + "rand_core 0.6.4", "subtle", "zeroize", ] @@ -586,7 +502,7 @@ dependencies = [ "hkdf", "pem-rfc7468", "pkcs8", - "rand_core", + "rand_core 0.6.4", "sec1", "subtle", "zeroize", @@ -605,7 +521,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -620,7 +536,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -778,8 +694,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", ] [[package]] @@ -790,7 +722,7 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", "wasip2", "wasip3", ] @@ -802,7 +734,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -914,12 +846,77 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "httparse" +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 = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -1045,9 +1042,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.2" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" dependencies = [ "icu_normalizer", "icu_properties", @@ -1066,10 +1063,20 @@ dependencies = [ ] [[package]] -name = "is_terminal_polyfill" -version = "1.70.2" +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" +dependencies = [ + "memchr", + "serde", +] [[package]] name = "itertools" @@ -1092,6 +1099,8 @@ version = "0.3.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" dependencies = [ + "cfg-if", + "futures-util", "once_cell", "wasm-bindgen", ] @@ -1110,7 +1119,7 @@ dependencies = [ "p256", "p384", "pem", - "rand", + "rand 0.8.6", "rsa", "serde", "serde_json", @@ -1136,9 +1145,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.185" +version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" [[package]] name = "libm" @@ -1173,6 +1182,12 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "lzma-sys" version = "0.1.20" @@ -1219,7 +1234,7 @@ checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1249,7 +1264,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand", + "rand 0.8.6", "smallvec", "zeroize", ] @@ -1296,12 +1311,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - [[package]] name = "ouroboros" version = "0.18.5" @@ -1566,14 +1575,81 @@ dependencies = [ "cda-database", "cda-interfaces", "cda-plugin-security", - "clap", "serde", "serde_json", "thiserror", "tokio", "toml", "tracing", - "url", +] + +[[package]] +name = "proxy-sovd" +version = "0.1.0" +dependencies = [ + "async-trait", + "cda-interfaces", + "proxy-core", + "reqwest", + "serde", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.4", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", ] [[package]] @@ -1585,6 +1661,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -1598,8 +1680,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", ] [[package]] @@ -1609,7 +1701,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -1621,6 +1723,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1679,6 +1790,44 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -1689,6 +1838,20 @@ dependencies = [ "subtle", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rsa" version = "0.9.10" @@ -1702,13 +1865,19 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", "signature", "spki", "subtle", "zeroize", ] +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + [[package]] name = "rustc_version" version = "0.4.1" @@ -1728,7 +1897,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c2c118cb077cca2822033836dfb1b975355dfb784b5e8da48f7b6c5db74e60e" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -1884,6 +2088,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1" version = "0.10.6" @@ -1929,7 +2145,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1963,7 +2179,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2007,12 +2223,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - [[package]] name = "strum" version = "0.27.2" @@ -2056,6 +2266,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -2078,7 +2291,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2142,6 +2355,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" version = "1.52.1" @@ -2156,7 +2384,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2170,6 +2398,16 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -2219,6 +2457,25 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", "tower-layer", "tower-service", ] @@ -2266,6 +2523,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.0" @@ -2284,6 +2547,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -2294,7 +2563,6 @@ dependencies = [ "idna", "percent-encoding", "serde", - "serde_derive", ] [[package]] @@ -2303,12 +2571,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "uuid" version = "1.23.1" @@ -2326,6 +2588,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2363,6 +2634,16 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.118" @@ -2429,6 +2710,35 @@ dependencies = [ "semver", ] +[[package]] +name = "web-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -2488,6 +2798,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -2497,6 +2825,135 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.7.15" diff --git a/Cargo.toml b/Cargo.toml index 3f3c127..df5fdcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,10 @@ homepage = "https://github.com/eclipse-opensovd/uds2sovd-proxy" [workspace] resolver = "3" -members = ["proxy-core"] +members = [ + "proxy-core", + "proxy-sovd", +] [workspace.dependencies] proxy-core = { path = "proxy-core" } diff --git a/proxy-sovd/Cargo.toml b/proxy-sovd/Cargo.toml new file mode 100644 index 0000000..4962dc1 --- /dev/null +++ b/proxy-sovd/Cargo.toml @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License Version 2.0 which is available at +# https://www.apache.org/licenses/LICENSE-2.0 + +[package] +name = "proxy-sovd" +version.workspace = true +edition.workspace = true +publish = false +description = "SOVD REST client and UDS mapper for the UDS2SOVD proxy" +homepage.workspace = true +license.workspace = true + +[dependencies] +proxy-core = { workspace = true } +async-trait = { workspace = true } +cda-interfaces = { workspace = true } +reqwest = { workspace = true, features = ["json", "rustls-tls"] } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["full"] } +tracing = { workspace = true } + +[lints] +workspace = true diff --git a/proxy-sovd/src/client.rs b/proxy-sovd/src/client.rs new file mode 100644 index 0000000..1b5fef3 --- /dev/null +++ b/proxy-sovd/src/client.rs @@ -0,0 +1,703 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use std::{sync::Arc, time::Duration}; + +use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; +use proxy_core::{ + config::SovdConfig, + error::{Result, SovdError}, + service_resolver::find_mux_case_prefix, +}; +use reqwest::{Client, StatusCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use tokio::sync::RwLock; +use tracing::{debug, info}; + +use crate::schema::DataResponse; + +/// `OAuth2` token request body. +#[derive(Serialize)] +struct AuthRequest { + client_id: String, + client_secret: String, +} + +/// `OAuth2` token response body. +#[derive(Deserialize)] +struct AuthResponse { + access_token: String, +} + +/// SOVD write request body. +#[derive(Serialize)] +struct WriteDataRequest { + data: Value, +} + +/// HTTP client for communicating with a SOVD gateway. +/// +/// Handles authentication, data reads, and data writes against the +/// SOVD REST API. Supports a mock mode for offline testing. +pub struct SovdClient { + /// SOVD gateway connection settings. + config: SovdConfig, + /// HTTP client with configured timeouts. + client: Client, + /// Cached `OAuth2` access token + access_token: Arc>>, +} + +impl SovdClient { + /// Create a new SOVD client with the given configuration. + /// + /// # Errors + /// Returns an error if the HTTP client cannot be created. + pub fn new(config: SovdConfig) -> Result { + let timeout = Duration::from_millis(config.timeout_ms); + let client = Client::builder() + .timeout(timeout) + .build() + .map_err(|e| SovdError::Http(e.to_string()))?; + + Ok(Self { + config, + client, + access_token: Arc::new(RwLock::new(None)), + }) + } + + /// Authenticate with the SOVD gateway and cache the access token. + /// + /// # Errors + /// Returns an error if authentication fails. + pub async fn authenticate(&self) -> Result { + if self.config.mock_gateway { + let token = "mock-access-token".to_string(); + *self.access_token.write().await = Some(token.clone()); + info!("[SOVD] Mock authentication enabled"); + return Ok(token); + } + + let url = format!( + "{}/vehicle/{}/authorize", + self.config.gateway_url, self.config.api_version + ); + + let auth_req = AuthRequest { + client_id: self.config.client_id.clone(), + client_secret: self.config.client_secret.clone(), + }; + + let response = self + .client + .post(&url) + .json(&auth_req) + .send() + .await + .map_err(|e| SovdError::Http(e.to_string()))?; + if !response.status().is_success() { + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + return Err(SovdError::Auth(format!("HTTP {status}: {body}")).into()); + } + + let auth_resp: AuthResponse = response + .json() + .await + .map_err(|e| SovdError::Http(e.to_string()))?; + + *self.access_token.write().await = Some(auth_resp.access_token.clone()); + Ok(auth_resp.access_token) + } + + async fn get_token(&self) -> Result { + { + let token_guard = self.access_token.read().await; + if let Some(token) = token_guard.as_ref() { + return Ok(token.clone()); + } + } + self.authenticate().await + } + + /// Read diagnostic data from the SOVD gateway. + /// + /// # Errors + /// Returns an error if the read request fails. + pub async fn read_data(&self, component: &str, data_id: &str) -> Result { + let token = self.get_token().await?; + let url = format!( + "{}/vehicle/{}/components/{}/data/{}", + self.config.gateway_url, self.config.api_version, component, data_id + ); + + info!("[SOVD] GET {}", url); + + let mut request = self.client.get(&url).bearer_auth(&token); + if self.config.include_schema { + request = request.query(&[("include_schema", "true")]); + } + + let response = request + .send() + .await + .map_err(|e| SovdError::Http(e.to_string()))?; + + match response.status() { + StatusCode::OK => { + let data: DataResponse = response + .json() + .await + .map_err(|e| SovdError::Http(e.to_string()))?; + info!("[SOVD] Response: HTTP 200 OK"); + debug!("[SOVD] Data: {} = {:?}", data.id, data.data); + Ok(data) + } + StatusCode::NOT_FOUND => Err(SovdError::DataIdNotFound(data_id.to_string()).into()), + status => { + let body = response.text().await.unwrap_or_default(); + Err(SovdError::Http(format!("HTTP {status}: {body}")).into()) + } + } + } + + /// Write diagnostic data to the SOVD gateway. + /// + /// # Errors + /// Returns an error if the write request fails. + pub async fn write_data( + &self, + component: &str, + data_id: &str, + data: serde_json::Map, + ) -> Result<()> { + if self.config.mock_gateway { + // SID 0x2E (WriteDataByIdentifier) maps to SOVD /configurations/{service} + info!( + "[SOVD MOCK] PUT /components/{}/configurations/{}", + component, data_id + ); + return Ok(()); + } + + let token = self.get_token().await?; + + let url = format!( + "{}/vehicle/{}/components/{}/configurations/{}", + self.config.gateway_url, self.config.api_version, component, data_id + ); + + info!("[SOVD] PUT {}", url); + + let write_req = WriteDataRequest { + data: Value::Object(data), + }; + + let response = self + .client + .put(&url) + .bearer_auth(&token) + .json(&write_req) + .send() + .await + .map_err(|e| SovdError::Http(e.to_string()))?; + + match response.status() { + StatusCode::NO_CONTENT | StatusCode::OK | StatusCode::ACCEPTED => { + info!("[SOVD] Write successful: HTTP {}", response.status()); + Ok(()) + } + StatusCode::BAD_REQUEST => { + let body = response.text().await.unwrap_or_default(); + Err(SovdError::SchemaMismatch(format!("Invalid request: {body}")).into()) + } + StatusCode::NOT_FOUND => Err(SovdError::DataIdNotFound(data_id.to_string()).into()), + status => { + let body = response.text().await.unwrap_or_default(); + Err(SovdError::Http(format!("HTTP {status}: {body}")).into()) + } + } + } + + /// Generate a mock SOVD response from MDD POS-RESPONSE metadata. + /// + /// For each VALUE/PhysConst parameter in the response structure, emits a + /// realistic default derived from the ODX parameter definition: + /// + /// - **`PhysConst`**: uses the `coded_value` from MDD (e.g. diagnostic + /// session `1` for default session). + /// - **VALUE with known `byte_size`**: uses a sensible value for the + /// field width (e.g. VIN string for 17-byte fields, small counters + /// for 1-2 byte fields). + /// - **`CodedConst` / `MatchingRequestParam`**: skipped โ€” the MDD response + /// encoder fills those automatically. + /// + /// When the service uses MUX cases, only parameters belonging to the + /// case that matches `did` are included. + #[must_use] + pub fn generate_mock_response_data( + &self, + _data_id: &str, + response_meta: &[ResponseParameterInfo], + did: u16, + ) -> Map { + // Find the MUX case prefix matching this DID using floor-based matching. + // Response MUX cases store only the lower_limit as coded_value, so + // range cases (e.g. a case with lower=61697) need floor matching + // for DIDs like 0xF103 (61699) that fall within the range. + let mux_case_prefix = find_mux_case_prefix(response_meta, did); + + // Detect truly opaque response layouts: after MUX filtering, a single + // VALUE parameter with unknown size carries the whole payload blob. + let active_value_like: Vec<&ResponseParameterInfo> = response_meta + .iter() + .filter(|p| { + if p.name.starts_with("__mux_case__/") { + return false; + } + if p.name.contains('/') { + if let Some(prefix) = &mux_case_prefix { + if !p.name.starts_with(prefix.as_str()) { + return false; + } + } else { + return false; + } + } + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + + let opaque_single_value = active_value_like.len() == 1 + && active_value_like.first().is_some_and(|p| { + matches!(p.param_type, ParameterTypeMetadata::Value { .. }) && p.byte_size.is_none() + }); + + let mut data = Map::new(); + for p in response_meta { + // Skip MUX case markers. + if p.name.starts_with("__mux_case__/") { + continue; + } + // Skip params from non-matching MUX cases. + if p.name.contains('/') { + if let Some(prefix) = &mux_case_prefix { + if !p.name.starts_with(prefix.as_str()) { + continue; + } + } else { + continue; + } + } + // Skip coded const and matching request params โ€” encoder fills those. + match &p.param_type { + ParameterTypeMetadata::CodedConst { .. } + | ParameterTypeMetadata::MatchingRequestParam { .. } => {} + ParameterTypeMetadata::PhysConst { coded_value, .. } => { + let key = p.name.rsplit('/').next().unwrap_or(&p.name).to_string(); + // Use the resolved coded_value from the MDD text-table. + let value = coded_value + .map(|cv| Value::Number(cv.into())) + .unwrap_or_else(|| Value::Number(0.into())); + data.insert(key, value); + } + ParameterTypeMetadata::Value { .. } => { + let key = p.name.rsplit('/').next().unwrap_or(&p.name).to_string(); + let value = if p.byte_size.is_none() && opaque_single_value { + // Opaque STRUCTURE references come through as VALUE with + // unknown byte size. Generate a realistic-length mock + // payload based on the DID; the real payload length + // comes from the ECU / SOVD server in production. + Self::mock_opaque_payload(did) + } else { + Self::default_value_for_param(&key, p.byte_size, p.semantic.as_deref()) + }; + data.insert(key, value); + } + } + } + + data + } + + /// Derive a generic default value for a VALUE parameter based on its + /// byte size only. + /// + /// This is MDD-agnostic โ€” no ECU-specific name patterns or DID heuristics. + /// Produces zero-valued numerics or zero-filled byte arrays that satisfy + /// the MDD response encoder without assuming a particular ECU. + fn default_value_for_param( + _name: &str, + byte_size: Option, + _semantic: Option<&str>, + ) -> Value { + match byte_size { + Some(sz @ 1..=8) => Value::Number(0u64.wrapping_add(u64::from(sz)).into()), + Some(sz) => { + // Large fields: zero-filled byte array. + Value::Array(vec![Value::Number(0.into()); sz as usize]) + } + None => Value::Number(0.into()), + } + } + + /// Generate a generic mock payload for an opaque STRUCTURE parameter + /// whose `byte_size` is unknown (END-OF-PDU / variable-length). + /// + /// Uses a fixed conservative size (4 bytes of zeros) that satisfies the + /// MDD response encoder without assuming any ECU-specific layout. + fn mock_opaque_payload(_did: u16) -> Value { + const DEFAULT_OPAQUE_SIZE: usize = 4; + Value::Array(vec![Value::Number(0.into()); DEFAULT_OPAQUE_SIZE]) + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn create_test_config() -> SovdConfig { + SovdConfig { + gateway_url: "http://localhost:20002".to_string(), + client_id: "test-client".to_string(), + client_secret: "test-secret".to_string(), + timeout_ms: 5000, + api_version: "v15".to_string(), + include_schema: true, + mock_gateway: false, + } + } + + #[test] + fn test_create_client() { + let config = create_test_config(); + assert!(SovdClient::new(config).is_ok()); + } + + #[test] + fn test_auth_request_serialization() { + let auth_req = AuthRequest { + client_id: "test".to_string(), + client_secret: "secret".to_string(), + }; + let json_str = serde_json::to_string(&auth_req).expect("failed to serialize auth request"); + assert!(json_str.contains("test")); + } + + #[test] + fn test_write_data_request_serialization() { + let write_req = WriteDataRequest { + data: json!({"VIN": "ABC12345678901234"}), + }; + let json_str = + serde_json::to_string(&write_req).expect("failed to serialize write request"); + assert!(json_str.contains("ABC12345678901234")); + } + + #[test] + fn test_data_response_deserialization() { + let json_str = r#"{ + "id": "VIN", + "data": { "VIN": "ABC12345678901234" } + }"#; + let response: DataResponse = + serde_json::from_str(json_str).expect("failed to deserialize data response"); + assert_eq!(response.id, "VIN"); + assert_eq!( + response.data.get("VIN").expect("VIN field not found"), + &json!("ABC12345678901234") + ); + } + + #[test] + fn test_auth_response_deserialization() { + let json_str = r#"{ + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", + "expires_in": 3600 + }"#; + let response: AuthResponse = + serde_json::from_str(json_str).expect("failed to deserialize auth response"); + assert!(response.access_token.starts_with("eyJ")); + } + + // โ”€โ”€ generate_mock_response_data tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + #[test] + fn test_mock_includes_value_params_skips_const() { + let client = SovdClient::new(create_test_config()).expect("failed to create SOVD client"); + let meta = vec![ + ResponseParameterInfo { + name: "sid".to_string(), + semantic: Some("SERVICE-ID".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "98".to_string(), + }, + byte_position: 0, + bit_position: 0, + byte_size: Some(1), + }, + ResponseParameterInfo { + name: "RDBI_DID".to_string(), + semantic: Some("DATA-IDENTIFIER".to_string()), + param_type: ParameterTypeMetadata::MatchingRequestParam { byte_length: 2 }, + byte_position: 1, + bit_position: 0, + byte_size: Some(2), + }, + ResponseParameterInfo { + name: "NUMBER_OF_XWES".to_string(), + semantic: Some("DATA".to_string()), + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: Some(1), + }, + ResponseParameterInfo { + name: "XWES_RECORDS".to_string(), + semantic: Some("DATA".to_string()), + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 4, + bit_position: 0, + byte_size: None, + }, + ]; + + let data = client.generate_mock_response_data("rsu_mirror_status", &meta, 0x25A4); + + assert!(data.contains_key("NUMBER_OF_XWES")); + assert!(data.contains_key("XWES_RECORDS")); + assert!(!data.contains_key("sid")); + assert!(!data.contains_key("RDBI_DID")); + // NUMBER_OF_XWES: 1-byte VALUE -> generic default (sz=1 -> 1) + assert_eq!(data.get("NUMBER_OF_XWES"), Some(&Value::Number(1.into()))); + // XWES_RECORDS: no byte_size -> 0 + assert_eq!(data.get("XWES_RECORDS"), Some(&Value::Number(0.into()))); + } + + #[test] + fn test_mock_filters_mux_case() { + let client = SovdClient::new(create_test_config()).expect("failed to create SOVD client"); + let meta = vec![ + ResponseParameterInfo { + name: "__mux_case__/case_a".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61840".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: Some(2), + }, + ResponseParameterInfo { + name: "__mux_case__/case_b".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61841".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: Some(2), + }, + ResponseParameterInfo { + name: "case_a/ADS".to_string(), + semantic: Some("DATA".to_string()), + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: Some(1), + }, + ResponseParameterInfo { + name: "case_b/ADS".to_string(), + semantic: Some("DATA".to_string()), + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: Some(1), + }, + ]; + + let data = client.generate_mock_response_data("rdbi_ads", &meta, 61840); + assert!(data.contains_key("ADS")); + assert_eq!(data.len(), 1); + } + + #[test] + fn test_mock_filters_mux_case_float_coded_value() { + // MDD may store MUX case limits as float-formatted strings (e.g. "61840.0") + let client = SovdClient::new(create_test_config()).expect("failed to create SOVD client"); + let meta = vec![ + ResponseParameterInfo { + name: "__mux_case__/case_a".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61840.0".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: Some(2), + }, + ResponseParameterInfo { + name: "case_a/ADS".to_string(), + semantic: Some("DATA".to_string()), + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: Some(1), + }, + ]; + + let data = client.generate_mock_response_data("rdbi_ads", &meta, 61840); + assert!( + data.contains_key("ADS"), + "Float-formatted coded_value must match DID" + ); + assert_eq!(data.len(), 1); + } + + #[test] + fn test_mock_floor_matching_range_mux_case() { + // Range MUX case: lower_limit 61697 (0xF101) covers DIDs up to next case. + // DID 0xF103 (61699) should floor-match to this case. + let client = SovdClient::new(create_test_config()).expect("failed to create SOVD client"); + let meta = vec![ + ResponseParameterInfo { + name: "__mux_case__/DID_RANGE_F101_F140".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61697".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + ResponseParameterInfo { + name: "__mux_case__/DID_POINT_F141".to_string(), + semantic: Some("MUX-CASE".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + coded_value: "61761".to_string(), + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + ResponseParameterInfo { + name: "DID_RANGE_F101_F140/DATA".to_string(), + semantic: Some("DATA".to_string()), + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + ResponseParameterInfo { + name: "DID_POINT_F141/DATA".to_string(), + semantic: Some("DATA".to_string()), + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }, + ]; + + // DID 0xF103 = 61699, floor matches to DID_RANGE_F101_F140 (lower=61697) + let data = client.generate_mock_response_data("rdbi_did_range", &meta, 0xF103); + assert!( + data.contains_key("DATA"), + "Floor-matched range case should include DATA param" + ); + assert_eq!(data.len(), 1, "Only DATA from DID_RANGE_F101_F140 case"); + // DID 0xF103: opaque DATA with no byte_size -> generic 4-byte mock payload + let data_arr = data + .get("DATA") + .expect("DATA field not found") + .as_array() + .expect("DATA is not an array"); + assert_eq!(data_arr.len(), 4, "Generic opaque mock should be 4 bytes"); + } + + #[test] + fn test_mock_opaque_payload_is_generic() { + // All DIDs produce the same conservative 4-byte zero-filled payload. + let payload = SovdClient::mock_opaque_payload(0xF101); + let arr = payload.as_array().expect("payload is not an array"); + assert_eq!(arr.len(), 4, "Generic opaque payload should be 4 bytes"); + for v in arr { + assert_eq!( + v.as_u64().expect("value is not u64"), + 0, + "Opaque payload should be zero-filled" + ); + } + + // Same size for any DID โ€” no ECU-specific table. + let payload2 = SovdClient::mock_opaque_payload(0x8008); + let arr2 = payload2.as_array().expect("payload2 is not an array"); + assert_eq!(arr2.len(), 4); + } + + #[test] + fn test_default_value_for_param_generic() { + // 1-byte VALUE -> numeric 1 + assert_eq!( + SovdClient::default_value_for_param("ANY_FIELD", Some(1), None), + Value::Number(1.into()), + ); + // 2-byte VALUE -> numeric 2 + assert_eq!( + SovdClient::default_value_for_param("VIN", Some(2), Some("DATA")), + Value::Number(2.into()), + ); + // 17-byte VALUE -> zero-filled array (no VIN heuristic) + let val = SovdClient::default_value_for_param("VIN", Some(17), None); + let arr = val.as_array().unwrap(); + assert_eq!(arr.len(), 17); + // None byte_size -> 0 + assert_eq!( + SovdClient::default_value_for_param("X", None, None), + Value::Number(0.into()), + ); + } +} diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs new file mode 100644 index 0000000..3309c07 --- /dev/null +++ b/proxy-sovd/src/diag_handler.rs @@ -0,0 +1,101 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use std::{collections::HashMap, sync::Arc}; + +use async_trait::async_trait; +use proxy_core::{Config, DiagHandler, ProxyError, Result, ServiceResolver, error::UdsError}; +use tracing::info; + +use crate::mapper::SovdMapper; + +/// SOVD-backed implementation of [`DiagHandler`]. +/// +/// Combines MDD-based service resolution ([`ServiceResolver`]) with SOVD +/// gateway communication ([`SovdMapper`]) to process UDS diagnostic requests. +/// +/// Constructed in `proxy-main` and injected into the `DoIP` server as +/// `Arc`. +pub struct SovdDiagHandler { + /// Shared proxy configuration. + config: Arc, + /// SOVD gateway mapper for request/response translation. + mapper: SovdMapper, + /// Per-ECU service resolvers keyed by ECU name. + ecu_managers: Arc>, +} + +impl SovdDiagHandler { + /// Create a new SOVD diagnostic handler. + #[must_use] + pub fn new( + config: Arc, + mapper: SovdMapper, + ecu_managers: Arc>, + ) -> Self { + Self { + config, + mapper, + ecu_managers, + } + } + + fn ecu_manager(&self) -> Option<&ServiceResolver> { + let ecu_name = &self.config.ecu.default_name; + self.ecu_managers + .get(ecu_name) + .or_else(|| self.ecu_managers.values().next()) + } +} + +#[async_trait] +impl DiagHandler for SovdDiagHandler { + async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result> { + let mgr = self + .ecu_manager() + .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; + + let (service_name, parsed_data) = mgr + .resolve_read_service(did, uds_request) + .await + .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; + + info!("[MDD] READ service found: '{}'", service_name); + + self.mapper + .process_read_data_request( + did, + uds_request, + Some(mgr), + &service_name, + Some(parsed_data), + ) + .await + } + + async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result> { + let mgr = self + .ecu_manager() + .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; + + let (service_name, parsed_data) = mgr + .resolve_write_service(did, uds_request) + .await + .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; + + info!("[MDD] WRITE service found: '{}'", service_name); + + self.mapper + .process_write_data_request(did, uds_request, &service_name, parsed_data) + .await + } +} diff --git a/proxy-sovd/src/lib.rs b/proxy-sovd/src/lib.rs new file mode 100644 index 0000000..7f47e19 --- /dev/null +++ b/proxy-sovd/src/lib.rs @@ -0,0 +1,26 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! SOVD gateway integration for the UDS-to-SOVD proxy. +//! +//! Provides the [`SovdDiagHandler`] implementation of [`proxy_core::DiagHandler`] +//! that translates UDS requests into SOVD REST calls and encodes the +//! responses back to UDS using MDD metadata. + +pub mod client; +pub mod diag_handler; +pub mod mapper; +pub mod schema; + +pub use client::SovdClient; +pub use diag_handler::SovdDiagHandler; +pub use mapper::SovdMapper; diff --git a/proxy-sovd/src/mapper.rs b/proxy-sovd/src/mapper.rs new file mode 100644 index 0000000..5a92e65 --- /dev/null +++ b/proxy-sovd/src/mapper.rs @@ -0,0 +1,285 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use cda_interfaces::service_ids; +use proxy_core::{ + Config, ServiceResolver, + error::{Result, SovdError}, +}; +use serde_json::{Map, Value}; +use tracing::{debug, info, trace}; + +use crate::{client::SovdClient, schema::DataResponse}; + +/// Minimum total WDBI UDS request length: SID (1) + DID high (1) + DID low (1). +/// A valid write request must contain at least one data byte beyond this header. +const MIN_WDBI_REQUEST_HEADER_LENGTH: usize = 3; + +/// Translates UDS diagnostic requests into SOVD REST calls and back. +/// +/// Handles both `ReadDataByIdentifier` (RDBI) and `WriteDataByIdentifier` (WDBI) +/// requests by forwarding them to the SOVD gateway and encoding/decoding +/// the JSON <-> UDS byte mappings via MDD metadata. +/// +/// # Current scope +/// +/// Read and write services with mocked SOVD gateway responses. The mock +/// path generates synthetic JSON from MDD POS-RESPONSE metadata, then +/// encodes it back to UDS bytes โ€” exercising the full translation pipeline +/// without requiring a live SOVD server. +/// +/// - TODO(sovd): When the SOVD server returns real responses, remove the +/// mock path and the `generate_mock_response_data` logic in [`SovdClient`]. +/// - TODO(sovd): Handle SOVD `errors[]` array in [`DataResponse`] โ€” map +/// field-level errors to UDS negative responses. +/// - TODO(sovd): Forward parsed request data to the SOVD gateway for +/// write requests that need request-parameter context. +pub struct SovdMapper { + /// Proxy configuration (ECU, SOVD endpoint, mock settings). + config: Config, + /// HTTP client for the SOVD gateway. + sovd_client: SovdClient, +} + +impl SovdMapper { + /// Create a new mapper with the given configuration and SOVD client. + #[must_use] + pub fn new(config: Config, sovd_client: SovdClient) -> Self { + Self { + config, + sovd_client, + } + } + + /// # Errors + /// Returns an error if the SOVD read request or UDS encoding fails. + pub async fn process_read_data_request( + &self, + did: u16, + uds_request: &[u8], + ecu_manager: Option<&ServiceResolver>, + service_name: &str, + parsed_data: Option>, + ) -> Result> { + debug!( + "[RDBI] DID 0x{:04X} service='{}' request={:02X?}", + did, service_name, uds_request + ); + if let Some(ref parsed) = parsed_data { + trace!( + "[RDBI] Parsed request: {}", + serde_json::to_string_pretty(parsed).unwrap_or_default() + ); + } + + let sovd_endpoint = service_name.to_lowercase(); + let component = &self.config.ecu.default_name; + + let sovd_response = if self.config.sovd.mock_gateway { + self.mock_read_response(did, service_name, &sovd_endpoint, ecu_manager) + .await? + } else { + let resp = self + .sovd_client + .read_data(component, &sovd_endpoint) + .await?; + debug!( + "[RDBI] SOVD response for '{}': {:?}", + sovd_endpoint, resp.data + ); + resp + }; + + let uds_response = self + .sovd_json_to_uds(did, &sovd_response, ecu_manager, service_name) + .await?; + + info!( + "[RDBI] DID 0x{:04X} '{}' -> {} bytes: {:02X?}", + did, + service_name, + uds_response.len(), + uds_response + ); + Ok(uds_response) + } + + /// # Errors + /// Returns an error if the SOVD write request fails. + pub async fn process_write_data_request( + &self, + did: u16, + uds_request: &[u8], + service_name: &str, + parsed_data: Map, + ) -> Result> { + if uds_request.len() <= MIN_WDBI_REQUEST_HEADER_LENGTH { + return Err(SovdError::SchemaMismatch("Write request missing data".to_string()).into()); + } + + let sovd_endpoint = service_name.to_lowercase(); + + let sovd_write_data = parsed_data; + debug!( + "[WDBI] SOVD JSON data: {}", + serde_json::to_string_pretty(&sovd_write_data).unwrap_or_default() + ); + + let component = &self.config.ecu.default_name; + + self.sovd_client + .write_data(component, &sovd_endpoint, sovd_write_data) + .await?; + + let uds_response = vec![ + service_ids::WRITE_DATA_BY_IDENTIFIER | cda_interfaces::UDS_ID_RESPONSE_BITMASK, + (did >> 8) as u8, + (did & 0xFF) as u8, + ]; + + info!( + "[WDBI] DID 0x{:04X} '{}' -> {} bytes", + did, + service_name, + uds_response.len() + ); + Ok(uds_response) + } + + async fn mock_read_response( + &self, + did: u16, + service_name: &str, + sovd_endpoint: &str, + ecu_manager: Option<&ServiceResolver>, + ) -> Result { + let would_be_url = format!( + "{}/vehicle/{}/components/{}/data/{}", + self.config.sovd.gateway_url, + self.config.sovd.api_version, + self.config.ecu.default_name, + sovd_endpoint + ); + info!( + "[SOVD MOCK] GET {} (intercepted โ€”> generating synthetic response)", + would_be_url + ); + + let mgr = ecu_manager.ok_or_else(|| { + SovdError::SchemaMismatch( + "ECU manager required for mock response generation".to_string(), + ) + })?; + + let meta = match mgr.get_enriched_response_metadata(service_name, did).await { + Ok(m) => m, + Err(e) => { + debug!( + "[SOVD MOCK] Enriched metadata unavailable for '{}': {}. Falling back to \ + basic POS-RESPONSE metadata", + service_name, e + ); + mgr.get_response_parameter_metadata(service_name) + .await + .map_err(|inner| { + SovdError::SchemaMismatch(format!( + "Failed to load POS-RESPONSE metadata for '{service_name}': {e} \ + (fallback: {inner})" + )) + })? + } + }; + + if meta.is_empty() { + return Err(SovdError::SchemaMismatch(format!( + "No POS-RESPONSE metadata available for '{service_name}' in mock mode" + )) + .into()); + } + + let data = self + .sovd_client + .generate_mock_response_data(sovd_endpoint, &meta, did); + + debug!( + "[SOVD MOCK] Generated response SOVD JSON data:\n{}", + serde_json::to_string_pretty(&data).unwrap_or_default() + ); + + Ok(DataResponse::new(sovd_endpoint.to_string(), data)) + } + + async fn sovd_json_to_uds( + &self, + did: u16, + sovd_response: &DataResponse, + ecu_manager: Option<&ServiceResolver>, + service_name: &str, + ) -> Result> { + use cda_interfaces::HashMap as CdaHashMap; + + let mgr = ecu_manager.ok_or_else(|| { + SovdError::SchemaMismatch("ECU manager required for MDD encoding".to_string()) + })?; + + let mut response_data: CdaHashMap = CdaHashMap::default(); + + for (k, v) in &sovd_response.data { + response_data.insert(k.clone(), v.clone()); + } + + let uds_bytes = mgr + .build_response( + service_name, + service_ids::READ_DATA_BY_IDENTIFIER, + did, + response_data, + ) + .await + .map_err(|e| { + SovdError::SchemaMismatch(format!( + "MDD failed to encode response for '{service_name}': {e}" + )) + })?; + + debug!( + "[MDD] SOVD JSON -> UDS for '{}': {:02X?}", + service_name, uds_bytes + ); + + Ok(uds_bytes) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn create_test_mapper() -> SovdMapper { + let config = Config::default(); + let sovd_client = + SovdClient::new(config.sovd.clone()).expect("failed to create SOVD client"); + SovdMapper::new(config, sovd_client) + } + + #[test] + fn test_service_to_sovd_endpoint() { + assert_eq!("READ_IDENTIFIER".to_lowercase(), "read_identifier"); + assert_eq!("WRITE_IDENTIFIER".to_lowercase(), "write_identifier"); + } + + #[test] + fn test_mapper_creation() { + let mapper = create_test_mapper(); + assert!(!mapper.config.sovd.gateway_url.is_empty()); + } +} diff --git a/proxy-sovd/src/schema.rs b/proxy-sovd/src/schema.rs new file mode 100644 index 0000000..98d1e2d --- /dev/null +++ b/proxy-sovd/src/schema.rs @@ -0,0 +1,92 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! SOVD REST API types for the proxy. +//! +//! These types mirror [`sovd_interfaces::ObjectDataItem`] from CDA but add +//! `Deserialize` since the proxy acts as a SOVD **client** (CDA's types only +//! derive `Serialize` because CDA is a SOVD server). + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// SOVD data response (mirrors `sovd_interfaces::ObjectDataItem`). +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct DataResponse { + /// Service identifier + pub id: String, + /// Response data as JSON object. + pub data: serde_json::Map, + /// Field-level errors, if any. + #[serde(skip_serializing_if = "Vec::is_empty", default)] + pub errors: Vec, + /// Optional inline schema + #[serde(skip_serializing_if = "Option::is_none", default)] + pub schema: Option, +} + +impl DataResponse { + /// Create a new `DataResponse` with the given service id and data. + #[must_use] + pub fn new(id: String, data: serde_json::Map) -> Self { + Self { + id, + data, + errors: Vec::new(), + schema: None, + } + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn test_data_response_new() { + use serde_json::Map; + + let mut data = Map::new(); + data.insert("identifier".to_string(), json!("ABC12345678901234")); + + let response = DataResponse::new("read_identifier".to_string(), data); + + assert_eq!(response.id, "read_identifier"); + assert_eq!( + response + .data + .get("identifier") + .expect("identifier field not found"), + &json!("ABC12345678901234") + ); + assert!(response.schema.is_none()); + assert!(response.errors.is_empty()); + } + + #[test] + fn test_data_response_roundtrip() { + let json_str = r#"{"id":"vin","data":{"VIN":"WBA00000000000001"}}"#; + let resp: DataResponse = + serde_json::from_str(json_str).expect("failed to deserialize data response"); + assert_eq!(resp.id, "vin"); + assert_eq!( + resp.data.get("VIN").and_then(|v| v.as_str()), + Some("WBA00000000000001") + ); + + let re_serialized = + serde_json::to_string(&resp).expect("failed to serialize data response"); + assert!(re_serialized.contains("WBA00000000000001")); + } +} From b44c19c4faef8c3fe10cc0813443ddb46690bf13 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Fri, 24 Apr 2026 07:51:35 +0200 Subject: [PATCH 17/33] fix: update diag_handler to use ResolvedService struct --- proxy-sovd/src/diag_handler.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 3309c07..3464a90 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -13,7 +13,7 @@ use std::{collections::HashMap, sync::Arc}; use async_trait::async_trait; -use proxy_core::{Config, DiagHandler, ProxyError, Result, ServiceResolver, error::UdsError}; +use proxy_core::{Config, DiagHandler, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError}; use tracing::info; use crate::mapper::SovdMapper; @@ -64,7 +64,7 @@ impl DiagHandler for SovdDiagHandler { .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let (service_name, parsed_data) = mgr + let ResolvedService { name: service_name, params: parsed_data } = mgr .resolve_read_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; @@ -87,7 +87,7 @@ impl DiagHandler for SovdDiagHandler { .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let (service_name, parsed_data) = mgr + let ResolvedService { name: service_name, params: parsed_data } = mgr .resolve_write_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; From 247e82f173d8a591ff47ddbddf31f1f9f410510b Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Mon, 27 Apr 2026 11:37:45 +0200 Subject: [PATCH 18/33] refactor: remove async_trait, convert DiagHandler impl to inherent methods --- Cargo.lock | 1 - proxy-sovd/Cargo.toml | 1 - proxy-sovd/src/diag_handler.rs | 44 ++++++++++++++++++++++++++-------- 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b749c0c..2cc3220 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1587,7 +1587,6 @@ dependencies = [ name = "proxy-sovd" version = "0.1.0" dependencies = [ - "async-trait", "cda-interfaces", "proxy-core", "reqwest", diff --git a/proxy-sovd/Cargo.toml b/proxy-sovd/Cargo.toml index 4962dc1..1b9c21d 100644 --- a/proxy-sovd/Cargo.toml +++ b/proxy-sovd/Cargo.toml @@ -19,7 +19,6 @@ license.workspace = true [dependencies] proxy-core = { workspace = true } -async-trait = { workspace = true } cda-interfaces = { workspace = true } reqwest = { workspace = true, features = ["json", "rustls-tls"] } serde = { workspace = true } diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 3464a90..c4390eb 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -12,19 +12,18 @@ use std::{collections::HashMap, sync::Arc}; -use async_trait::async_trait; -use proxy_core::{Config, DiagHandler, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError}; +use proxy_core::{Config, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError}; use tracing::info; use crate::mapper::SovdMapper; -/// SOVD-backed implementation of [`DiagHandler`]. +/// SOVD-backed diagnostic handler. /// /// Combines MDD-based service resolution ([`ServiceResolver`]) with SOVD /// gateway communication ([`SovdMapper`]) to process UDS diagnostic requests. /// /// Constructed in `proxy-main` and injected into the `DoIP` server as -/// `Arc`. +/// `Arc`. pub struct SovdDiagHandler { /// Shared proxy configuration. config: Arc, @@ -57,14 +56,26 @@ impl SovdDiagHandler { } } -#[async_trait] -impl DiagHandler for SovdDiagHandler { - async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result> { +impl SovdDiagHandler { + /// Process a `ReadDataByIdentifier` (0x22) request. + /// + /// `did` is the extracted 16-bit Data Identifier. + /// `uds_request` is the full UDS request bytes including the SID byte. + /// + /// Returns the complete UDS response bytes (positive or negative). + /// + /// # Errors + /// Returns an error if no MDD database is loaded, the DID is unknown, + /// or the SOVD gateway request fails. + pub async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result> { let mgr = self .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let ResolvedService { name: service_name, params: parsed_data } = mgr + let ResolvedService { + name: service_name, + params: parsed_data, + } = mgr .resolve_read_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; @@ -82,12 +93,25 @@ impl DiagHandler for SovdDiagHandler { .await } - async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result> { + /// Process a `WriteDataByIdentifier` (0x2E) request. + /// + /// `did` is the extracted 16-bit Data Identifier. + /// `uds_request` is the full UDS request bytes including the SID byte. + /// + /// Returns the complete UDS response bytes (positive or negative). + /// + /// # Errors + /// Returns an error if no MDD database is loaded, the DID is unknown, + /// or the SOVD gateway request fails. + pub async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result> { let mgr = self .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let ResolvedService { name: service_name, params: parsed_data } = mgr + let ResolvedService { + name: service_name, + params: parsed_data, + } = mgr .resolve_write_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; From 7281e81dd940cc32782406b96fec59cc65b21160 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 28 Apr 2026 08:44:53 +0200 Subject: [PATCH 19/33] Fix: self review Signed-off-by: Arvind Rathod --- proxy-sovd/src/client.rs | 23 ++++++++++------------- proxy-sovd/src/diag_handler.rs | 20 +++++++++----------- proxy-sovd/src/mapper.rs | 31 ++++++++++++------------------- 3 files changed, 31 insertions(+), 43 deletions(-) diff --git a/proxy-sovd/src/client.rs b/proxy-sovd/src/client.rs index 1b5fef3..15aa2d5 100644 --- a/proxy-sovd/src/client.rs +++ b/proxy-sovd/src/client.rs @@ -324,7 +324,7 @@ impl SovdClient { // comes from the ECU / SOVD server in production. Self::mock_opaque_payload(did) } else { - Self::default_value_for_param(&key, p.byte_size, p.semantic.as_deref()) + Self::default_value_for_param(p.byte_size) }; data.insert(key, value); } @@ -338,15 +338,12 @@ impl SovdClient { /// byte size only. /// /// This is MDD-agnostic โ€” no ECU-specific name patterns or DID heuristics. - /// Produces zero-valued numerics or zero-filled byte arrays that satisfy - /// the MDD response encoder without assuming a particular ECU. - fn default_value_for_param( - _name: &str, - byte_size: Option, - _semantic: Option<&str>, - ) -> Value { + /// For small fields (1โ€“8 bytes), produces a numeric equal to the byte + /// size as a distinguishable non-zero placeholder. Larger fields are + /// emitted as zero-filled byte arrays. + fn default_value_for_param(byte_size: Option) -> Value { match byte_size { - Some(sz @ 1..=8) => Value::Number(0u64.wrapping_add(u64::from(sz)).into()), + Some(sz @ 1..=8) => Value::Number(u64::from(sz).into()), Some(sz) => { // Large fields: zero-filled byte array. Value::Array(vec![Value::Number(0.into()); sz as usize]) @@ -682,21 +679,21 @@ mod tests { fn test_default_value_for_param_generic() { // 1-byte VALUE -> numeric 1 assert_eq!( - SovdClient::default_value_for_param("ANY_FIELD", Some(1), None), + SovdClient::default_value_for_param(Some(1)), Value::Number(1.into()), ); // 2-byte VALUE -> numeric 2 assert_eq!( - SovdClient::default_value_for_param("VIN", Some(2), Some("DATA")), + SovdClient::default_value_for_param(Some(2)), Value::Number(2.into()), ); // 17-byte VALUE -> zero-filled array (no VIN heuristic) - let val = SovdClient::default_value_for_param("VIN", Some(17), None); + let val = SovdClient::default_value_for_param(Some(17)); let arr = val.as_array().unwrap(); assert_eq!(arr.len(), 17); // None byte_size -> 0 assert_eq!( - SovdClient::default_value_for_param("X", None, None), + SovdClient::default_value_for_param(None), Value::Number(0.into()), ); } diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index c4390eb..a8791c9 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -13,7 +13,7 @@ use std::{collections::HashMap, sync::Arc}; use proxy_core::{Config, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError}; -use tracing::info; +use tracing::{info, warn}; use crate::mapper::SovdMapper; @@ -50,9 +50,13 @@ impl SovdDiagHandler { fn ecu_manager(&self) -> Option<&ServiceResolver> { let ecu_name = &self.config.ecu.default_name; - self.ecu_managers - .get(ecu_name) - .or_else(|| self.ecu_managers.values().next()) + self.ecu_managers.get(ecu_name).or_else(|| { + warn!( + "[ECU] Default ECU '{}' not found, falling back to first available", + ecu_name + ); + self.ecu_managers.values().next() + }) } } @@ -83,13 +87,7 @@ impl SovdDiagHandler { info!("[MDD] READ service found: '{}'", service_name); self.mapper - .process_read_data_request( - did, - uds_request, - Some(mgr), - &service_name, - Some(parsed_data), - ) + .process_read_data_request(did, uds_request, mgr, &service_name, Some(parsed_data)) .await } diff --git a/proxy-sovd/src/mapper.rs b/proxy-sovd/src/mapper.rs index 5a92e65..c5c1a70 100644 --- a/proxy-sovd/src/mapper.rs +++ b/proxy-sovd/src/mapper.rs @@ -66,7 +66,7 @@ impl SovdMapper { &self, did: u16, uds_request: &[u8], - ecu_manager: Option<&ServiceResolver>, + ecu_manager: &ServiceResolver, service_name: &str, parsed_data: Option>, ) -> Result> { @@ -128,16 +128,15 @@ impl SovdMapper { let sovd_endpoint = service_name.to_lowercase(); - let sovd_write_data = parsed_data; debug!( "[WDBI] SOVD JSON data: {}", - serde_json::to_string_pretty(&sovd_write_data).unwrap_or_default() + serde_json::to_string_pretty(&parsed_data).unwrap_or_default() ); let component = &self.config.ecu.default_name; self.sovd_client - .write_data(component, &sovd_endpoint, sovd_write_data) + .write_data(component, &sovd_endpoint, parsed_data) .await?; let uds_response = vec![ @@ -160,7 +159,7 @@ impl SovdMapper { did: u16, service_name: &str, sovd_endpoint: &str, - ecu_manager: Option<&ServiceResolver>, + ecu_manager: &ServiceResolver, ) -> Result { let would_be_url = format!( "{}/vehicle/{}/components/{}/data/{}", @@ -174,13 +173,10 @@ impl SovdMapper { would_be_url ); - let mgr = ecu_manager.ok_or_else(|| { - SovdError::SchemaMismatch( - "ECU manager required for mock response generation".to_string(), - ) - })?; - - let meta = match mgr.get_enriched_response_metadata(service_name, did).await { + let meta = match ecu_manager + .get_enriched_response_metadata(service_name, did) + .await + { Ok(m) => m, Err(e) => { debug!( @@ -188,7 +184,8 @@ impl SovdMapper { basic POS-RESPONSE metadata", service_name, e ); - mgr.get_response_parameter_metadata(service_name) + ecu_manager + .get_response_parameter_metadata(service_name) .await .map_err(|inner| { SovdError::SchemaMismatch(format!( @@ -222,22 +219,18 @@ impl SovdMapper { &self, did: u16, sovd_response: &DataResponse, - ecu_manager: Option<&ServiceResolver>, + ecu_manager: &ServiceResolver, service_name: &str, ) -> Result> { use cda_interfaces::HashMap as CdaHashMap; - let mgr = ecu_manager.ok_or_else(|| { - SovdError::SchemaMismatch("ECU manager required for MDD encoding".to_string()) - })?; - let mut response_data: CdaHashMap = CdaHashMap::default(); for (k, v) in &sovd_response.data { response_data.insert(k.clone(), v.clone()); } - let uds_bytes = mgr + let uds_bytes = ecu_manager .build_response( service_name, service_ids::READ_DATA_BY_IDENTIFIER, From 6bbda5126d2ae9c2c57c4327098e0cfdd15ef15e Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Wed, 29 Apr 2026 09:18:59 +0200 Subject: [PATCH 20/33] Fix: address review comments Signed-off-by: Arvind Rathod --- proxy-sovd/src/client.rs | 46 ++++++++++++++++++---------------- proxy-sovd/src/diag_handler.rs | 15 ++++------- proxy-sovd/src/mapper.rs | 23 +++++++++-------- proxy-sovd/src/schema.rs | 5 +++- 4 files changed, 46 insertions(+), 43 deletions(-) diff --git a/proxy-sovd/src/client.rs b/proxy-sovd/src/client.rs index 15aa2d5..72ed8a0 100644 --- a/proxy-sovd/src/client.rs +++ b/proxy-sovd/src/client.rs @@ -22,7 +22,6 @@ use reqwest::{Client, StatusCode}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use tokio::sync::RwLock; -use tracing::{debug, info}; use crate::schema::DataResponse; @@ -85,10 +84,11 @@ impl SovdClient { if self.config.mock_gateway { let token = "mock-access-token".to_string(); *self.access_token.write().await = Some(token.clone()); - info!("[SOVD] Mock authentication enabled"); + tracing::info!("[SOVD] Mock authentication enabled"); return Ok(token); } + // TODO(sovd-server): OAuth2 token exchange - only reached when mock_gateway = false. let url = format!( "{}/vehicle/{}/authorize", self.config.gateway_url, self.config.api_version @@ -121,6 +121,8 @@ impl SovdClient { Ok(auth_resp.access_token) } + // TODO(sovd-server): token cache helper - only called from the read_data / write_data + // paths that are bypassed when mock_gateway = true. async fn get_token(&self) -> Result { { let token_guard = self.access_token.read().await; @@ -135,6 +137,11 @@ impl SovdClient { /// /// # Errors /// Returns an error if the read request fails. + /// + /// # Note + /// Not called when `mock_gateway = true` - [`SovdMapper`] intercepts the request + /// in [`SovdMapper::mock_read_response`] before reaching this function. + // TODO(sovd-server): placeholder - wire up once a real SOVD server is available. pub async fn read_data(&self, component: &str, data_id: &str) -> Result { let token = self.get_token().await?; let url = format!( @@ -142,7 +149,7 @@ impl SovdClient { self.config.gateway_url, self.config.api_version, component, data_id ); - info!("[SOVD] GET {}", url); + tracing::info!("[SOVD] GET {}", url); let mut request = self.client.get(&url).bearer_auth(&token); if self.config.include_schema { @@ -156,12 +163,12 @@ impl SovdClient { match response.status() { StatusCode::OK => { + tracing::info!("[SOVD] Response: HTTP 200 OK"); let data: DataResponse = response .json() .await .map_err(|e| SovdError::Http(e.to_string()))?; - info!("[SOVD] Response: HTTP 200 OK"); - debug!("[SOVD] Data: {} = {:?}", data.id, data.data); + tracing::debug!("[SOVD] Data: {} = {:?}", data.id, data.data); Ok(data) } StatusCode::NOT_FOUND => Err(SovdError::DataIdNotFound(data_id.to_string()).into()), @@ -184,13 +191,15 @@ impl SovdClient { ) -> Result<()> { if self.config.mock_gateway { // SID 0x2E (WriteDataByIdentifier) maps to SOVD /configurations/{service} - info!( + tracing::info!( "[SOVD MOCK] PUT /components/{}/configurations/{}", - component, data_id + component, + data_id ); return Ok(()); } + // TODO(sovd-server): real HTTP PUT - only reached when mock_gateway = false. let token = self.get_token().await?; let url = format!( @@ -198,7 +207,7 @@ impl SovdClient { self.config.gateway_url, self.config.api_version, component, data_id ); - info!("[SOVD] PUT {}", url); + tracing::info!("[SOVD] PUT {}", url); let write_req = WriteDataRequest { data: Value::Object(data), @@ -215,7 +224,7 @@ impl SovdClient { match response.status() { StatusCode::NO_CONTENT | StatusCode::OK | StatusCode::ACCEPTED => { - info!("[SOVD] Write successful: HTTP {}", response.status()); + tracing::info!("[SOVD] Write successful: HTTP {}", response.status()); Ok(()) } StatusCode::BAD_REQUEST => { @@ -245,6 +254,7 @@ impl SovdClient { /// /// When the service uses MUX cases, only parameters belonging to the /// case that matches `did` are included. + /// TODO(sovd-server): Remove this function once sovd-server provides real responses. #[must_use] pub fn generate_mock_response_data( &self, @@ -267,12 +277,9 @@ impl SovdClient { return false; } if p.name.contains('/') { - if let Some(prefix) = &mux_case_prefix { - if !p.name.starts_with(prefix.as_str()) { - return false; - } - } else { - return false; + match &mux_case_prefix { + Some(prefix) if p.name.starts_with(prefix.as_str()) => {} + _ => return false, } } matches!( @@ -295,12 +302,9 @@ impl SovdClient { } // Skip params from non-matching MUX cases. if p.name.contains('/') { - if let Some(prefix) = &mux_case_prefix { - if !p.name.starts_with(prefix.as_str()) { - continue; - } - } else { - continue; + match &mux_case_prefix { + Some(prefix) if p.name.starts_with(prefix.as_str()) => {} + _ => continue, } } // Skip coded const and matching request params โ€” encoder fills those. diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index a8791c9..28e4cdf 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -12,18 +12,13 @@ use std::{collections::HashMap, sync::Arc}; -use proxy_core::{Config, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError}; -use tracing::{info, warn}; +use proxy_core::{ + Config, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError, +}; use crate::mapper::SovdMapper; /// SOVD-backed diagnostic handler. -/// -/// Combines MDD-based service resolution ([`ServiceResolver`]) with SOVD -/// gateway communication ([`SovdMapper`]) to process UDS diagnostic requests. -/// -/// Constructed in `proxy-main` and injected into the `DoIP` server as -/// `Arc`. pub struct SovdDiagHandler { /// Shared proxy configuration. config: Arc, @@ -84,7 +79,7 @@ impl SovdDiagHandler { .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; - info!("[MDD] READ service found: '{}'", service_name); + tracing::info!("[MDD] READ service found: '{}'", service_name); self.mapper .process_read_data_request(did, uds_request, mgr, &service_name, Some(parsed_data)) @@ -114,7 +109,7 @@ impl SovdDiagHandler { .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; - info!("[MDD] WRITE service found: '{}'", service_name); + tracing::info!("[MDD] WRITE service found: '{}'", service_name); self.mapper .process_write_data_request(did, uds_request, &service_name, parsed_data) diff --git a/proxy-sovd/src/mapper.rs b/proxy-sovd/src/mapper.rs index c5c1a70..69dee30 100644 --- a/proxy-sovd/src/mapper.rs +++ b/proxy-sovd/src/mapper.rs @@ -16,7 +16,6 @@ use proxy_core::{ error::{Result, SovdError}, }; use serde_json::{Map, Value}; -use tracing::{debug, info, trace}; use crate::{client::SovdClient, schema::DataResponse}; @@ -70,12 +69,12 @@ impl SovdMapper { service_name: &str, parsed_data: Option>, ) -> Result> { - debug!( + tracing::debug!( "[RDBI] DID 0x{:04X} service='{}' request={:02X?}", did, service_name, uds_request ); if let Some(ref parsed) = parsed_data { - trace!( + tracing::trace!( "[RDBI] Parsed request: {}", serde_json::to_string_pretty(parsed).unwrap_or_default() ); @@ -88,11 +87,12 @@ impl SovdMapper { self.mock_read_response(did, service_name, &sovd_endpoint, ecu_manager) .await? } else { + // TODO(sovd-server): read path - not exercised while mock_gateway = true. let resp = self .sovd_client .read_data(component, &sovd_endpoint) .await?; - debug!( + tracing::debug!( "[RDBI] SOVD response for '{}': {:?}", sovd_endpoint, resp.data ); @@ -103,7 +103,7 @@ impl SovdMapper { .sovd_json_to_uds(did, &sovd_response, ecu_manager, service_name) .await?; - info!( + tracing::info!( "[RDBI] DID 0x{:04X} '{}' -> {} bytes: {:02X?}", did, service_name, @@ -128,7 +128,8 @@ impl SovdMapper { let sovd_endpoint = service_name.to_lowercase(); - debug!( + let sovd_write_data = parsed_data; + tracing::debug!( "[WDBI] SOVD JSON data: {}", serde_json::to_string_pretty(&parsed_data).unwrap_or_default() ); @@ -145,7 +146,7 @@ impl SovdMapper { (did & 0xFF) as u8, ]; - info!( + tracing::info!( "[WDBI] DID 0x{:04X} '{}' -> {} bytes", did, service_name, @@ -168,7 +169,7 @@ impl SovdMapper { self.config.ecu.default_name, sovd_endpoint ); - info!( + tracing::info!( "[SOVD MOCK] GET {} (intercepted โ€”> generating synthetic response)", would_be_url ); @@ -179,7 +180,7 @@ impl SovdMapper { { Ok(m) => m, Err(e) => { - debug!( + tracing::debug!( "[SOVD MOCK] Enriched metadata unavailable for '{}': {}. Falling back to \ basic POS-RESPONSE metadata", service_name, e @@ -207,7 +208,7 @@ impl SovdMapper { .sovd_client .generate_mock_response_data(sovd_endpoint, &meta, did); - debug!( + tracing::debug!( "[SOVD MOCK] Generated response SOVD JSON data:\n{}", serde_json::to_string_pretty(&data).unwrap_or_default() ); @@ -244,7 +245,7 @@ impl SovdMapper { )) })?; - debug!( + tracing::debug!( "[MDD] SOVD JSON -> UDS for '{}': {:02X?}", service_name, uds_bytes ); diff --git a/proxy-sovd/src/schema.rs b/proxy-sovd/src/schema.rs index 98d1e2d..51b0ec9 100644 --- a/proxy-sovd/src/schema.rs +++ b/proxy-sovd/src/schema.rs @@ -26,7 +26,10 @@ pub struct DataResponse { pub id: String, /// Response data as JSON object. pub data: serde_json::Map, - /// Field-level errors, if any. + /// Field-level errors returned by the sovd-server, if any. + /// + /// Parsed from the response but not yet mapped to UDS negative responses. + // TODO(sovd-server): map sovd-server field errors to NRC codes when live gateway is connected. #[serde(skip_serializing_if = "Vec::is_empty", default)] pub errors: Vec, /// Optional inline schema From 925d1e61e34c74dfdf5c1cfe6848fe09470f164d Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 30 Apr 2026 11:45:41 +0200 Subject: [PATCH 21/33] refactor: address review comments for proxy-sovd --- proxy-sovd/src/client.rs | 10 ++++ proxy-sovd/src/diag_handler.rs | 36 ++++++++------ proxy-sovd/src/mapper.rs | 89 ++++++++++++++++++++++------------ 3 files changed, 89 insertions(+), 46 deletions(-) diff --git a/proxy-sovd/src/client.rs b/proxy-sovd/src/client.rs index 72ed8a0..e86b7da 100644 --- a/proxy-sovd/src/client.rs +++ b/proxy-sovd/src/client.rs @@ -121,6 +121,14 @@ impl SovdClient { Ok(auth_resp.access_token) } + /// Return a cached access token, or fetch a fresh one by calling [`authenticate`]. + /// + /// The token is stored in a shared read-write lock so concurrent requests + /// can read it without blocking each other. A new token is only requested + /// when the cache is empty. + /// + /// # Errors + /// Propagates any error returned by [`authenticate`]. // TODO(sovd-server): token cache helper - only called from the read_data / write_data // paths that are bypassed when mock_gateway = true. async fn get_token(&self) -> Result { @@ -361,6 +369,8 @@ impl SovdClient { /// /// Uses a fixed conservative size (4 bytes of zeros) that satisfies the /// MDD response encoder without assuming any ECU-specific layout. + /// Return a fixed-size opaque byte array for services whose response + /// layout cannot be inferred from metadata fn mock_opaque_payload(_did: u16) -> Value { const DEFAULT_OPAQUE_SIZE: usize = 4; Value::Array(vec![Value::Number(0.into()); DEFAULT_OPAQUE_SIZE]) diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 28e4cdf..2e35f9d 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -10,21 +10,32 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -use std::{collections::HashMap, sync::Arc}; - +use cda_interfaces::HashMap; use proxy_core::{ - Config, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError, + Config, ProxyError, ResolvedService, Result, ServiceResolver, ServiceType, error::UdsError, }; +use std::sync::Arc; +use tracing::info; use crate::mapper::SovdMapper; /// SOVD-backed diagnostic handler. +/// +/// Combines MDD-based service resolution ([`ServiceResolver`]) with SOVD +/// gateway communication ([`SovdMapper`]) to process UDS diagnostic requests. +/// +/// Constructed in `proxy-main` and injected into the `DoIP` server as +/// `Arc`. pub struct SovdDiagHandler { /// Shared proxy configuration. config: Arc, /// SOVD gateway mapper for request/response translation. mapper: SovdMapper, /// Per-ECU service resolvers keyed by ECU name. + /// + /// A map is used to support future multi-ECU configurations where a single + /// proxy instance handles requests for more than one ECU. Currently only + /// the ECU named in `config.ecu.default_name` is used. ecu_managers: Arc>, } @@ -44,14 +55,7 @@ impl SovdDiagHandler { } fn ecu_manager(&self) -> Option<&ServiceResolver> { - let ecu_name = &self.config.ecu.default_name; - self.ecu_managers.get(ecu_name).or_else(|| { - warn!( - "[ECU] Default ECU '{}' not found, falling back to first available", - ecu_name - ); - self.ecu_managers.values().next() - }) + self.ecu_managers.get(&self.config.ecu.default_name) } } @@ -75,11 +79,12 @@ impl SovdDiagHandler { name: service_name, params: parsed_data, } = mgr - .resolve_read_service(did, uds_request) + .resolver + .resolve(ServiceType::Read, did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; - tracing::info!("[MDD] READ service found: '{}'", service_name); + info!("[MDD] READ service found: '{}'", service_name); self.mapper .process_read_data_request(did, uds_request, mgr, &service_name, Some(parsed_data)) @@ -105,11 +110,12 @@ impl SovdDiagHandler { name: service_name, params: parsed_data, } = mgr - .resolve_write_service(did, uds_request) + .resolver + .resolve(ServiceType::Write, did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; - tracing::info!("[MDD] WRITE service found: '{}'", service_name); + info!("[MDD] WRITE service found: '{}'", service_name); self.mapper .process_write_data_request(did, uds_request, &service_name, parsed_data) diff --git a/proxy-sovd/src/mapper.rs b/proxy-sovd/src/mapper.rs index 69dee30..416eace 100644 --- a/proxy-sovd/src/mapper.rs +++ b/proxy-sovd/src/mapper.rs @@ -43,18 +43,26 @@ const MIN_WDBI_REQUEST_HEADER_LENGTH: usize = 3; /// - TODO(sovd): Forward parsed request data to the SOVD gateway for /// write requests that need request-parameter context. pub struct SovdMapper { - /// Proxy configuration (ECU, SOVD endpoint, mock settings). - config: Config, + /// ECU component name used in SOVD REST paths. + ecu_name: String, + /// When `true`, bypass HTTP and generate synthetic responses. + mock_gateway: bool, + /// Base URL of the SOVD gateway + gateway_url: String, + /// SOVD API version path segment + api_version: String, /// HTTP client for the SOVD gateway. sovd_client: SovdClient, } impl SovdMapper { - /// Create a new mapper with the given configuration and SOVD client. #[must_use] - pub fn new(config: Config, sovd_client: SovdClient) -> Self { + pub fn new(config: &Config, sovd_client: SovdClient) -> Self { Self { - config, + ecu_name: config.ecu.default_name.clone(), + mock_gateway: config.sovd.mock_gateway, + gateway_url: config.sovd.gateway_url.clone(), + api_version: config.sovd.api_version.clone(), sovd_client, } } @@ -65,13 +73,15 @@ impl SovdMapper { &self, did: u16, uds_request: &[u8], - ecu_manager: &ServiceResolver, + resolver: &ServiceResolver, service_name: &str, parsed_data: Option>, ) -> Result> { tracing::debug!( "[RDBI] DID 0x{:04X} service='{}' request={:02X?}", - did, service_name, uds_request + did, + service_name, + uds_request ); if let Some(ref parsed) = parsed_data { tracing::trace!( @@ -81,26 +91,26 @@ impl SovdMapper { } let sovd_endpoint = service_name.to_lowercase(); - let component = &self.config.ecu.default_name; - let sovd_response = if self.config.sovd.mock_gateway { - self.mock_read_response(did, service_name, &sovd_endpoint, ecu_manager) + let sovd_response = if self.mock_gateway { + self.mock_read_response(did, service_name, &sovd_endpoint, resolver) .await? } else { // TODO(sovd-server): read path - not exercised while mock_gateway = true. let resp = self .sovd_client - .read_data(component, &sovd_endpoint) + .read_data(&self.ecu_name, &sovd_endpoint) .await?; tracing::debug!( "[RDBI] SOVD response for '{}': {:?}", - sovd_endpoint, resp.data + sovd_endpoint, + resp.data ); resp }; let uds_response = self - .sovd_json_to_uds(did, &sovd_response, ecu_manager, service_name) + .sovd_json_to_uds(did, &sovd_response, resolver, service_name) .await?; tracing::info!( @@ -128,16 +138,13 @@ impl SovdMapper { let sovd_endpoint = service_name.to_lowercase(); - let sovd_write_data = parsed_data; tracing::debug!( "[WDBI] SOVD JSON data: {}", serde_json::to_string_pretty(&parsed_data).unwrap_or_default() ); - let component = &self.config.ecu.default_name; - self.sovd_client - .write_data(component, &sovd_endpoint, parsed_data) + .write_data(&self.ecu_name, &sovd_endpoint, parsed_data) .await?; let uds_response = vec![ @@ -155,26 +162,34 @@ impl SovdMapper { Ok(uds_response) } + /// Bypass the live SOVD gateway and return a synthetic [`DataResponse`]. + /// + /// Builds the response JSON entirely from MDD POS-RESPONSE metadata so + /// the full UDS translation pipeline can be exercised without a running + /// SOVD server. Logs the URL that would have been called so the mock + /// path is easy to spot in traces. + /// + /// # Errors + /// Returns an error if no POS-RESPONSE metadata is available for the + /// requested service. async fn mock_read_response( &self, did: u16, service_name: &str, sovd_endpoint: &str, - ecu_manager: &ServiceResolver, + resolver: &ServiceResolver, ) -> Result { let would_be_url = format!( "{}/vehicle/{}/components/{}/data/{}", - self.config.sovd.gateway_url, - self.config.sovd.api_version, - self.config.ecu.default_name, - sovd_endpoint + self.gateway_url, self.api_version, self.ecu_name, sovd_endpoint ); tracing::info!( "[SOVD MOCK] GET {} (intercepted โ€”> generating synthetic response)", would_be_url ); - let meta = match ecu_manager + let meta = match resolver + .metadata .get_enriched_response_metadata(service_name, did) .await { @@ -183,10 +198,12 @@ impl SovdMapper { tracing::debug!( "[SOVD MOCK] Enriched metadata unavailable for '{}': {}. Falling back to \ basic POS-RESPONSE metadata", - service_name, e + service_name, + e ); - ecu_manager - .get_response_parameter_metadata(service_name) + resolver + .metadata + .get_response_params(service_name) .await .map_err(|inner| { SovdError::SchemaMismatch(format!( @@ -216,11 +233,19 @@ impl SovdMapper { Ok(DataResponse::new(sovd_endpoint.to_string(), data)) } + /// Convert a SOVD JSON response into raw UDS response bytes. + /// + /// Delegates encoding to [`ResponseEncoder`], which uses MDD POS-RESPONSE + /// parameter metadata to place each field at its correct byte offset. + /// + /// # Errors + /// Returns an error if the MDD encoder cannot produce a valid response + /// for the given service name. async fn sovd_json_to_uds( &self, did: u16, sovd_response: &DataResponse, - ecu_manager: &ServiceResolver, + resolver: &ServiceResolver, service_name: &str, ) -> Result> { use cda_interfaces::HashMap as CdaHashMap; @@ -231,7 +256,8 @@ impl SovdMapper { response_data.insert(k.clone(), v.clone()); } - let uds_bytes = ecu_manager + let uds_bytes = resolver + .encoder .build_response( service_name, service_ids::READ_DATA_BY_IDENTIFIER, @@ -247,7 +273,8 @@ impl SovdMapper { tracing::debug!( "[MDD] SOVD JSON -> UDS for '{}': {:02X?}", - service_name, uds_bytes + service_name, + uds_bytes ); Ok(uds_bytes) @@ -262,7 +289,7 @@ mod tests { let config = Config::default(); let sovd_client = SovdClient::new(config.sovd.clone()).expect("failed to create SOVD client"); - SovdMapper::new(config, sovd_client) + SovdMapper::new(&config, sovd_client) } #[test] @@ -274,6 +301,6 @@ mod tests { #[test] fn test_mapper_creation() { let mapper = create_test_mapper(); - assert!(!mapper.config.sovd.gateway_url.is_empty()); + assert!(!mapper.ecu_name.is_empty()); } } From 22e85b8f6ec57a13ebed9eff0280d2e23dceabab Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 7 May 2026 11:57:01 +0200 Subject: [PATCH 22/33] fix: address review comments for proxy-sovd --- proxy-sovd/src/client.rs | 4 +++- proxy-sovd/src/diag_handler.rs | 12 ++++++------ proxy-sovd/src/mapper.rs | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/proxy-sovd/src/client.rs b/proxy-sovd/src/client.rs index e86b7da..f6966f9 100644 --- a/proxy-sovd/src/client.rs +++ b/proxy-sovd/src/client.rs @@ -385,7 +385,9 @@ mod tests { fn create_test_config() -> SovdConfig { SovdConfig { - gateway_url: "http://localhost:20002".to_string(), + gateway_url: "http://localhost:20002" + .parse() + .expect("hard-coded URL is always valid"), client_id: "test-client".to_string(), client_secret: "test-secret".to_string(), timeout_ms: 5000, diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 2e35f9d..0453d8a 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -10,11 +10,12 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ +use std::sync::Arc; + use cda_interfaces::HashMap; use proxy_core::{ Config, ProxyError, ResolvedService, Result, ServiceResolver, ServiceType, error::UdsError, }; -use std::sync::Arc; use tracing::info; use crate::mapper::SovdMapper; @@ -32,10 +33,6 @@ pub struct SovdDiagHandler { /// SOVD gateway mapper for request/response translation. mapper: SovdMapper, /// Per-ECU service resolvers keyed by ECU name. - /// - /// A map is used to support future multi-ECU configurations where a single - /// proxy instance handles requests for more than one ECU. Currently only - /// the ECU named in `config.ecu.default_name` is used. ecu_managers: Arc>, } @@ -55,7 +52,10 @@ impl SovdDiagHandler { } fn ecu_manager(&self) -> Option<&ServiceResolver> { - self.ecu_managers.get(&self.config.ecu.default_name) + let ecu_name = &self.config.ecu.default_name; + self.ecu_managers + .get(ecu_name) + .or_else(|| self.ecu_managers.values().next()) } } diff --git a/proxy-sovd/src/mapper.rs b/proxy-sovd/src/mapper.rs index 416eace..862d67e 100644 --- a/proxy-sovd/src/mapper.rs +++ b/proxy-sovd/src/mapper.rs @@ -61,7 +61,7 @@ impl SovdMapper { Self { ecu_name: config.ecu.default_name.clone(), mock_gateway: config.sovd.mock_gateway, - gateway_url: config.sovd.gateway_url.clone(), + gateway_url: config.sovd.gateway_url.to_string(), api_version: config.sovd.api_version.clone(), sovd_client, } From 23fb2064e35c1996f24e1ebe6bf4abb83087ff56 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 12 May 2026 14:13:37 +0200 Subject: [PATCH 23/33] fix: address review comments for proxy-sovd --- proxy-core/src/config.rs | 757 +++++++++++++++++++++------------ proxy-sovd/src/client.rs | 37 +- proxy-sovd/src/diag_handler.rs | 2 - proxy-sovd/src/mapper.rs | 32 +- 4 files changed, 533 insertions(+), 295 deletions(-) diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index b2cdafd..4d4d6b9 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -12,33 +12,17 @@ use std::{ net::{IpAddr, Ipv4Addr}, - path::Path, + path::PathBuf, }; +use clap::Parser; use serde::{Deserialize, Deserializer, de}; +use url::Url; use crate::error::{ProxyError, Result}; -/// Required byte length for EID and GID fields per ISO 13400-2. -const EID_GID_BYTE_LENGTH: usize = 6; - -// Default values for ServerConfig. -const DEFAULT_DOIP_PORT: u16 = 13400; -const DEFAULT_MAX_CONNECTIONS: usize = 10; -/// DoIP source address (tester logical address used in response messages). -const DEFAULT_SOURCE_ADDRESS: u16 = 0x0E80; - -// Default values for SovdConfig. -const DEFAULT_GATEWAY_URL: &str = "http://localhost:20002"; -const DEFAULT_CLIENT_ID: &str = "uds2sovd_proxy"; -const DEFAULT_CLIENT_SECRET: &str = "test_secret"; -const DEFAULT_TIMEOUT_MS: u64 = 5000; -const DEFAULT_API_VERSION: &str = "v15"; - -// Default values for EcuConfig. -const DEFAULT_ECU_NAME: &str = "ECU"; -/// Top-level proxy configuration loaded from a TOML file. -#[derive(Debug, Clone, Deserialize, Default)] +#[derive(Deserialize, Default)] +#[serde(default)] pub struct Config { /// `DoIP` server settings (port, bind address, source address). pub server: ServerConfig, @@ -50,23 +34,33 @@ pub struct Config { pub logging: LoggingConfig, } -/// `DoIP` server configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Deserialize)] +#[serde(default)] pub struct ServerConfig { - /// TCP port for the `DoIP` server (default: 13400). + /// TCP port for the `DoIP` server (default: 13 400). #[serde(deserialize_with = "deserialize_nonzero_u16")] pub doip_port: u16, - /// IP address to bind the server socket to. - #[serde(deserialize_with = "deserialize_ip_addr")] + /// IP address to bind the server socket to (default: `0.0.0.0`). pub bind_address: IpAddr, - /// Maximum number of concurrent connections. + /// Maximum number of concurrent connections (default: 10). #[serde(deserialize_with = "deserialize_max_connections")] pub max_connections: usize, - /// `DoIP` source address used in response messages. + /// `DoIP` source address used in response messages (default: `0x0E80`). #[serde(deserialize_with = "deserialize_nonzero_u16")] pub source_address: u16, } +impl Default for ServerConfig { + fn default() -> Self { + Self { + doip_port: 13_400, + bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), + max_connections: 10, + source_address: 0x0E80, + } + } +} + fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -77,16 +71,6 @@ fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( Ok(v) } -/// Deserialize IP address string into `std::net::IpAddr`. -fn deserialize_ip_addr<'de, D: Deserializer<'de>>( - deserializer: D, -) -> std::result::Result { - let s = String::deserialize(deserializer)?; - s.parse::() - .map_err(|_| de::Error::custom(format!("invalid IP address: {s}"))) -} - -/// Reject zero during deserialization for `usize` fields. fn deserialize_max_connections<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -97,22 +81,11 @@ fn deserialize_max_connections<'de, D: Deserializer<'de>>( Ok(v) } -/// Reject empty gateway URL strings during deserialization. -fn deserialize_nonempty_gateway_url<'de, D: Deserializer<'de>>( - deserializer: D, -) -> std::result::Result { - let s = String::deserialize(deserializer)?; - if s.is_empty() { - return Err(de::Error::custom("gateway_url must not be empty")); - } - Ok(s) -} -/// SOVD gateway connection configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Clone, Deserialize)] +#[serde(default)] pub struct SovdConfig { /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). - #[serde(deserialize_with = "deserialize_nonempty_gateway_url")] - pub gateway_url: String, + pub gateway_url: Url, /// `OAuth2` client ID for gateway authentication. pub client_id: String, /// `OAuth2` client secret for gateway authentication. @@ -122,291 +95,541 @@ pub struct SovdConfig { /// SOVD API version path segment (e.g. `v15`). pub api_version: String, /// Whether to request inline schema in data responses. - #[serde(default = "SovdConfig::default_include_schema")] pub include_schema: bool, /// When `true`, bypass HTTP calls and generate synthetic responses. - #[serde(default)] pub mock_gateway: bool, } -impl SovdConfig { - fn default_include_schema() -> bool { - true +impl Default for SovdConfig { + fn default() -> Self { + Self { + gateway_url: "http://localhost:20002" + .parse() + .expect("hard-coded URL is always valid"), + client_id: "uds2sovd_proxy".into(), + client_secret: "test_secret".into(), + timeout_ms: 5_000, + api_version: "v15".into(), + include_schema: true, + mock_gateway: true, + } + } +} + +#[derive(Clone, Copy, Deserialize)] +pub struct EidGid([u8; 6]); + +impl EidGid { + fn is_all_zeros(self) -> bool { + self.0 == [0u8; 6] + } +} + +impl Default for EidGid { + fn default() -> Self { + Self([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]) } } -/// ECU identity and addressing configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Deserialize)] +#[serde(default)] pub struct EcuConfig { /// Default ECU name used for SOVD component path. pub default_name: String, /// ISO 13400 logical address of the target ECU. #[serde(deserialize_with = "deserialize_nonzero_u16")] pub logical_address: u16, - /// 6-byte Entity Identification (MAC address). - pub eid: [u8; EID_GID_BYTE_LENGTH], + /// 6-byte Entity Identification + pub eid: EidGid, /// 6-byte Group Identification. - pub gid: [u8; EID_GID_BYTE_LENGTH], + pub gid: EidGid, +} + +impl Default for EcuConfig { + fn default() -> Self { + Self { + default_name: "ECU".into(), + logical_address: 0x0001, + eid: EidGid::default(), + gid: EidGid::default(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum LogLevel { + Error, + Warn, + #[default] + Info, + Debug, + Trace, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum LogFormat { + /// Human-readable coloured output (default). + #[default] + Pretty, + /// Machine-readable JSON (suitable for log aggregators). + Json, } /// Logging output configuration. -#[derive(Debug, Clone, Deserialize)] +#[derive(Deserialize, Default)] +#[serde(default)] pub struct LoggingConfig { - /// Log level filter (e.g. `info`, `debug`, `trace`). - pub level: String, - /// Output format: `pretty` (default) or `json`. - pub format: String, + /// Log level filter. + pub level: LogLevel, + /// Output format. + pub format: LogFormat, +} + +/// Any flag set here overrides the corresponding value from the TOML file. +#[derive(Parser)] +#[command(name = "uds2sovd-proxy", version)] +pub struct Cli { + /// Path to the TOML configuration file. + #[arg( + short, + long, + value_name = "FILE", + env = "PROXY_CONFIG", + default_value = "config/config.toml" + )] + pub config: PathBuf, + + /// Override the IP address to bind to. + #[arg(long, value_name = "ADDR", env = "PROXY_BIND_ADDRESS")] + pub bind_address: Option, + + /// Override the SOVD gateway URL. + #[arg(long, value_name = "URL", env = "PROXY_GATEWAY_URL")] + pub gateway_url: Option, + + /// Enable mock gateway mode (no real HTTP calls). + #[arg(long, env = "PROXY_MOCK_GATEWAY")] + pub mock_gateway: bool, + + /// Override the log level. + #[arg(long, value_enum, value_name = "LEVEL", env = "PROXY_LOG_LEVEL")] + pub log_level: Option, + + /// Override the log output format. + #[arg(long, value_enum, value_name = "FORMAT", env = "PROXY_LOG_FORMAT")] + pub log_format: Option, + + /// MDD file to load (absolute path, or filename resolved under `--mdd-dir`). + #[arg(short, long)] + pub mdd_file: PathBuf, + + /// Directory searched when `--mdd-file` is a relative filename. + #[arg(long, default_value = "testcontainer/mdd")] + pub mdd_dir: PathBuf, } impl Config { - /// Load configuration from TOML file + /// Build a fully-validated [`Config`] by layering defaults, a TOML file, + /// and CLI overrides. + /// + /// # Layer order + /// 1. [`Default`] values + /// 2. TOML file at the path given by `cli.config` + /// 3. CLI flags + /// + /// # Errors + /// Returns [`ProxyError::Config`] if the TOML file cannot be read/parsed + /// or if the merged configuration fails validation. + pub fn load(cli: &Cli) -> Result { + // defaults + TOML file + let mut config = if cli.config.exists() { + Self::from_file(&cli.config)? + } else { + Self::default() + }; + + // CLI overrides + if let Some(addr) = cli.bind_address { + config.server.bind_address = addr; + } + if let Some(ref url) = cli.gateway_url { + config.sovd.gateway_url = url.clone(); + } + if cli.mock_gateway { + config.sovd.mock_gateway = true; + } + if let Some(level) = cli.log_level { + config.logging.level = level; + } + if let Some(format) = cli.log_format { + config.logging.format = format; + } + + config.validate()?; + Ok(config) + } + + /// Load and validate configuration from a TOML file (without CLI overrides). /// /// # Errors - /// Returns an error if the file cannot be read or parsed. - pub fn from_file>(path: P) -> Result { + /// Returns [`ProxyError::Config`] if the file cannot be read, parsed, or + /// if the resulting configuration fails validation. + pub fn from_file>(path: P) -> Result { + let path = path.as_ref(); let content = std::fs::read_to_string(path) - .map_err(|e| ProxyError::Config(format!("Failed to read config file: {e}")))?; + .map_err(|e| ProxyError::Config(format!("cannot read `{}`: {e}", path.display())))?; - toml::from_str(&content) - .map_err(|e| ProxyError::Config(format!("Failed to parse config: {e}"))) + let config: Self = toml::from_str(&content) + .map_err(|e| ProxyError::Config(format!("cannot parse `{}`: {e}", path.display())))?; + + config.validate()?; + Ok(config) } -} -impl Default for ServerConfig { - fn default() -> Self { - Self { - doip_port: DEFAULT_DOIP_PORT, - bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), - max_connections: DEFAULT_MAX_CONNECTIONS, - source_address: DEFAULT_SOURCE_ADDRESS, + /// Validate the fully-merged configuration. + fn validate(&self) -> Result<()> { + let mut errors: Vec = Vec::new(); + + if self.server.max_connections == 0 { + errors.push("[server] max_connections must be greater than zero".into()); + } + if self.sovd.client_id.is_empty() { + errors.push("[sovd] client_id must not be empty".into()); + } + if self.sovd.api_version.is_empty() { + errors.push("[sovd] api_version must not be empty".into()); + } + if self.ecu.default_name.is_empty() { + errors.push("[ecu] default_name must not be empty".into()); + } + if self.ecu.eid.is_all_zeros() { + errors.push("[ecu] eid must not be all zeros".into()); + } + if self.ecu.gid.is_all_zeros() { + errors.push("[ecu] gid must not be all zeros".into()); } - } -} -impl Default for SovdConfig { - fn default() -> Self { - Self { - gateway_url: DEFAULT_GATEWAY_URL.to_string(), - client_id: DEFAULT_CLIENT_ID.to_string(), - client_secret: DEFAULT_CLIENT_SECRET.to_string(), - timeout_ms: DEFAULT_TIMEOUT_MS, - api_version: DEFAULT_API_VERSION.to_string(), - include_schema: true, - mock_gateway: false, + if errors.is_empty() { + Ok(()) + } else { + Err(ProxyError::Config(format!( + "configuration validation failed:\n - {}", + errors.join("\n - ") + ))) } } } -impl Default for EcuConfig { - fn default() -> Self { - Self { - default_name: DEFAULT_ECU_NAME.to_string(), - logical_address: 0x0001, - eid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], - gid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eid_gid_holds_expected_bytes() { + let eid = EidGid([0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); + assert_eq!(eid.0, [0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); + } + + #[test] + fn eid_gid_all_zeros_detected() { + let eid = EidGid([0u8; 6]); + assert!(eid.is_all_zeros()); + + let eid2 = EidGid([0, 1, 2, 3, 4, 5]); + assert!(!eid2.is_all_zeros()); + } + + #[test] + fn log_level_deserializes_all_variants_from_toml() { + #[derive(Deserialize)] + struct Wrapper { + level: LogLevel, + } + + for (raw, expected) in [ + ("error", LogLevel::Error), + ("warn", LogLevel::Warn), + ("info", LogLevel::Info), + ("debug", LogLevel::Debug), + ("trace", LogLevel::Trace), + ] { + let parsed: Wrapper = + toml::from_str(&format!("level = \"{raw}\"")).expect("valid level"); + assert_eq!(parsed.level, expected); } } -} -impl Default for LoggingConfig { - fn default() -> Self { - Self { - level: "info".to_string(), - format: "pretty".to_string(), + #[test] + fn log_format_deserializes_all_variants_from_toml() { + #[derive(Deserialize)] + struct Wrapper { + format: LogFormat, + } + + for (raw, expected) in [("pretty", LogFormat::Pretty), ("json", LogFormat::Json)] { + let parsed: Wrapper = + toml::from_str(&format!("format = \"{raw}\"")).expect("valid format"); + assert_eq!(parsed.format, expected); } } -} -#[cfg(test)] -mod tests { - use super::*; + #[test] + fn server_defaults_are_sane() { + let s = ServerConfig::default(); + assert_eq!(s.doip_port, 13_400); + assert_eq!(s.max_connections, 10); + } #[test] - fn test_default_config() { - let config = Config::default(); - assert_eq!(config.server.doip_port, 13400); - assert_eq!(config.sovd.api_version, "v15"); - assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); + fn sovd_defaults_are_sane() { + let s = SovdConfig::default(); + assert!(s.mock_gateway); + assert!(s.include_schema); + assert_eq!(s.timeout_ms, 5_000); } #[test] - fn test_deserialize_valid_config() { - let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; - let config: Config = toml::from_str(toml_str).expect("valid config should parse"); - assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); - assert_eq!(config.server.doip_port, 13400); + fn validation_rejects_empty_client_id() { + let mut config = Config::default(); + config.sovd.client_id = String::new(); + assert!(config.validate().is_err()); } #[test] - fn test_deserialize_rejects_zero_port() { - let toml_str = r#" - [server] - doip_port = 0 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; - let result = toml::from_str::(toml_str); - assert!(result.is_err(), "doip_port=0 should be rejected"); + fn validation_rejects_all_zero_eid() { + let mut config = Config::default(); + config.ecu.eid = EidGid([0u8; 6]); + assert!(config.validate().is_err()); + } + + #[test] + fn validation_rejects_zero_max_connections() { + let mut config = Config::default(); + config.server.max_connections = 0; + assert!(config.validate().is_err()); + } + + #[test] + fn validation_accumulates_multiple_errors() { + let mut config = Config::default(); + config.sovd.client_id = String::new(); + config.sovd.api_version = String::new(); + config.ecu.eid = EidGid([0u8; 6]); + let err = config.validate().unwrap_err().to_string(); + // Three separate bullets should appear. + assert_eq!(err.matches(" - ").count(), 3); + } + + #[test] + fn toml_parses_complete_config() { + let raw = r#" +[server] +bind_address = "127.0.0.1" +max_connections = 5 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 3000 +api_version = "v15" +include_schema = false +mock_gateway = true + +[ecu] +default_name = "TEST_ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "debug" +format = "json" +"#; + let cfg: Config = toml::from_str(raw).expect("valid TOML"); + assert!(cfg.sovd.mock_gateway); + assert_eq!(cfg.logging.level, LogLevel::Debug); + assert_eq!(cfg.logging.format, LogFormat::Json); } #[test] - fn test_deserialize_rejects_zero_max_connections() { + fn deserialize_rejects_zero_max_connections() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 0 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 0 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "max_connections=0 should be rejected"); } #[test] - fn test_deserialize_rejects_zero_logical_address() { + fn deserialize_rejects_zero_logical_address() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 0 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 0 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "logical_address=0 should be rejected"); } #[test] - fn test_deserialize_rejects_wrong_eid_length() { + fn deserialize_rejects_wrong_eid_length() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "http://localhost:20002" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "eid with wrong length should be rejected"); } #[test] - fn test_deserialize_rejects_empty_gateway_url() { + fn deserialize_rejects_invalid_gateway_url() { + let toml_str = r#" +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "not a valid url" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "info" +format = "pretty" +"#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "invalid gateway_url should be rejected"); + } + + #[test] + fn deserialize_rejects_invalid_log_level() { let toml_str = r#" - [server] - doip_port = 13400 - bind_address = "0.0.0.0" - max_connections = 10 - source_address = 3712 - - [sovd] - gateway_url = "" - client_id = "test" - client_secret = "secret" - timeout_ms = 5000 - api_version = "v15" - - [ecu] - default_name = "ECU" - logical_address = 1 - eid = [0, 1, 2, 3, 4, 5] - gid = [0, 1, 2, 3, 4, 5] - - [logging] - level = "info" - format = "pretty" - "#; +[server] +bind_address = "0.0.0.0" +max_connections = 10 +source_address = 3712 + +[sovd] +gateway_url = "http://localhost:20002" +client_id = "test" +client_secret = "secret" +timeout_ms = 5000 +api_version = "v15" + +[ecu] +default_name = "ECU" +logical_address = 1 +eid = [0, 1, 2, 3, 4, 5] +gid = [0, 1, 2, 3, 4, 5] + +[logging] +level = "verbose" +format = "pretty" +"#; let result = toml::from_str::(toml_str); - assert!(result.is_err(), "empty gateway_url should be rejected"); + assert!(result.is_err(), "invalid log level should be rejected"); + } + + // โ”€โ”€ CLI integration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + #[test] + fn cli_overrides_default_values() { + let cli = Cli::parse_from([ + "uds2sovd-proxy", + "--config", + "/nonexistent/path.toml", + "--log-level", + "debug", + "--mock-gateway", + "--mdd-file", + "test.mdd", + ]); + + let config = Config::load(&cli).expect("should build from defaults + CLI"); + assert_eq!(config.logging.level, LogLevel::Debug); + assert!(config.sovd.mock_gateway); + } + + #[test] + fn toml_with_missing_sections_uses_defaults() { + let raw = r#" +[server] +bind_address = "127.0.0.1" +max_connections = 5 +source_address = 3712 +"#; + let cfg: Config = toml::from_str(raw).expect("partial TOML should parse"); + assert_eq!(cfg.sovd.api_version, "v15"); + assert_eq!(cfg.logging.level, LogLevel::Info); } } diff --git a/proxy-sovd/src/client.rs b/proxy-sovd/src/client.rs index f6966f9..ba75d68 100644 --- a/proxy-sovd/src/client.rs +++ b/proxy-sovd/src/client.rs @@ -16,7 +16,6 @@ use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; use proxy_core::{ config::SovdConfig, error::{Result, SovdError}, - service_resolver::find_mux_case_prefix, }; use reqwest::{Client, StatusCode}; use serde::{Deserialize, Serialize}; @@ -377,6 +376,42 @@ impl SovdClient { } } +fn parse_mux_coded_value(coded_value: &str) -> Option { + let trimmed = coded_value.trim(); + #[allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss + )] + trimmed.parse::().ok().or_else(|| { + let v = trimmed.parse::().ok()?; + (v >= 0.0 && v <= u64::MAX as f64).then_some(v as u64) + }) +} + +fn find_mux_case_prefix(meta: &[ResponseParameterInfo], did: u16) -> Option { + let did_val = u64::from(did); + let mut mux_entries: Vec<(u64, &str)> = meta + .iter() + .filter_map(|p| { + let case_name = p.name.strip_prefix("__mux_case__/")?; + if let cda_interfaces::ParameterTypeMetadata::CodedConst { coded_value } = &p.param_type + { + let lower = parse_mux_coded_value(coded_value)?; + Some((lower, case_name)) + } else { + None + } + }) + .collect(); + if mux_entries.is_empty() { + return None; + } + mux_entries.sort_by_key(|&(lb, _)| lb); + let matched = mux_entries.iter().rev().find(|&&(lb, _)| lb <= did_val)?; + Some(format!("{}/", matched.1)) +} + #[cfg(test)] mod tests { use serde_json::json; diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 0453d8a..65dd783 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -79,7 +79,6 @@ impl SovdDiagHandler { name: service_name, params: parsed_data, } = mgr - .resolver .resolve(ServiceType::Read, did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; @@ -110,7 +109,6 @@ impl SovdDiagHandler { name: service_name, params: parsed_data, } = mgr - .resolver .resolve(ServiceType::Write, did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; diff --git a/proxy-sovd/src/mapper.rs b/proxy-sovd/src/mapper.rs index 862d67e..c466208 100644 --- a/proxy-sovd/src/mapper.rs +++ b/proxy-sovd/src/mapper.rs @@ -188,31 +188,14 @@ impl SovdMapper { would_be_url ); - let meta = match resolver - .metadata - .get_enriched_response_metadata(service_name, did) + let meta = resolver + .get_response_metadata(service_name, did) .await - { - Ok(m) => m, - Err(e) => { - tracing::debug!( - "[SOVD MOCK] Enriched metadata unavailable for '{}': {}. Falling back to \ - basic POS-RESPONSE metadata", - service_name, - e - ); - resolver - .metadata - .get_response_params(service_name) - .await - .map_err(|inner| { - SovdError::SchemaMismatch(format!( - "Failed to load POS-RESPONSE metadata for '{service_name}': {e} \ - (fallback: {inner})" - )) - })? - } - }; + .map_err(|e| { + SovdError::SchemaMismatch(format!( + "Failed to load POS-RESPONSE metadata for '{service_name}': {e}" + )) + })?; if meta.is_empty() { return Err(SovdError::SchemaMismatch(format!( @@ -257,7 +240,6 @@ impl SovdMapper { } let uds_bytes = resolver - .encoder .build_response( service_name, service_ids::READ_DATA_BY_IDENTIFIER, From 2b7d61020c2d589034abf1d1c78d8e2a73c9b8d3 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 30 Apr 2026 11:45:00 +0200 Subject: [PATCH 24/33] refactor: address review comments for service_parsing --- Cargo.lock | 740 ++++++++------------------------------ proxy-core/src/config.rs | 757 ++++++++++++++------------------------- 2 files changed, 409 insertions(+), 1088 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2cc3220..de0fdde 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,6 +46,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + [[package]] name = "anyhow" version = "1.0.102" @@ -63,12 +113,6 @@ dependencies = [ "syn", ] -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - [[package]] name = "autocfg" version = "1.5.0" @@ -305,12 +349,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - [[package]] name = "chrono" version = "0.4.44" @@ -324,6 +362,52 @@ dependencies = [ "windows-link", ] +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "const-oid" version = "0.9.6" @@ -352,7 +436,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", - "rand_core 0.6.4", + "rand_core", "subtle", "zeroize", ] @@ -502,7 +586,7 @@ dependencies = [ "hkdf", "pem-rfc7468", "pkcs8", - "rand_core 0.6.4", + "rand_core", "sec1", "subtle", "zeroize", @@ -521,7 +605,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -536,7 +620,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "rand_core 0.6.4", + "rand_core", "subtle", ] @@ -694,24 +778,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", - "js-sys", "libc", "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 5.3.0", - "wasip2", - "wasm-bindgen", ] [[package]] @@ -722,7 +790,7 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", - "r-efi 6.0.0", + "r-efi", "wasip2", "wasip3", ] @@ -734,7 +802,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", - "rand_core 0.6.4", + "rand_core", "subtle", ] @@ -846,77 +914,12 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "httparse" -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 = "hyper" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "http", - "http-body", - "httparse", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "tokio", - "tokio-rustls", - "tower-service", - "webpki-roots", -] - -[[package]] -name = "hyper-util" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" -dependencies = [ - "base64", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - [[package]] name = "iana-time-zone" version = "0.1.65" @@ -1042,9 +1045,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ "icu_normalizer", "icu_properties", @@ -1063,20 +1066,10 @@ dependencies = [ ] [[package]] -name = "ipnet" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" - -[[package]] -name = "iri-string" -version = "0.7.12" +name = "is_terminal_polyfill" +version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" -dependencies = [ - "memchr", - "serde", -] +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itertools" @@ -1099,8 +1092,6 @@ version = "0.3.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" dependencies = [ - "cfg-if", - "futures-util", "once_cell", "wasm-bindgen", ] @@ -1119,7 +1110,7 @@ dependencies = [ "p256", "p384", "pem", - "rand 0.8.6", + "rand", "rsa", "serde", "serde_json", @@ -1145,9 +1136,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.186" +version = "0.2.185" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" [[package]] name = "libm" @@ -1182,12 +1173,6 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" -[[package]] -name = "lru-slab" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" - [[package]] name = "lzma-sys" version = "0.1.20" @@ -1234,7 +1219,7 @@ checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -1264,7 +1249,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand 0.8.6", + "rand", "smallvec", "zeroize", ] @@ -1311,6 +1296,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "ouroboros" version = "0.18.5" @@ -1575,80 +1566,14 @@ dependencies = [ "cda-database", "cda-interfaces", "cda-plugin-security", + "clap", "serde", "serde_json", "thiserror", "tokio", "toml", "tracing", -] - -[[package]] -name = "proxy-sovd" -version = "0.1.0" -dependencies = [ - "cda-interfaces", - "proxy-core", - "reqwest", - "serde", - "serde_json", - "tokio", - "tracing", -] - -[[package]] -name = "quinn" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" -dependencies = [ - "bytes", - "cfg_aliases", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash", - "rustls", - "socket2", - "thiserror", - "tokio", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-proto" -version = "0.11.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" -dependencies = [ - "bytes", - "getrandom 0.3.4", - "lru-slab", - "rand 0.9.4", - "ring", - "rustc-hash", - "rustls", - "rustls-pki-types", - "slab", - "thiserror", - "tinyvec", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-udp" -version = "0.5.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" -dependencies = [ - "cfg_aliases", - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.60.2", + "url", ] [[package]] @@ -1660,12 +1585,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - [[package]] name = "r-efi" version = "6.0.0" @@ -1679,18 +1598,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", + "rand_chacha", + "rand_core", ] [[package]] @@ -1700,17 +1609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", + "rand_core", ] [[package]] @@ -1722,15 +1621,6 @@ dependencies = [ "getrandom 0.2.17", ] -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - [[package]] name = "redox_syscall" version = "0.5.18" @@ -1789,44 +1679,6 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" -[[package]] -name = "reqwest" -version = "0.12.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" -dependencies = [ - "base64", - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "webpki-roots", -] - [[package]] name = "rfc6979" version = "0.4.0" @@ -1837,20 +1689,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - [[package]] name = "rsa" version = "0.9.10" @@ -1864,19 +1702,13 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core 0.6.4", + "rand_core", "signature", "spki", "subtle", "zeroize", ] -[[package]] -name = "rustc-hash" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" - [[package]] name = "rustc_version" version = "0.4.1" @@ -1896,42 +1728,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c2c118cb077cca2822033836dfb1b975355dfb784b5e8da48f7b6c5db74e60e" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" -dependencies = [ - "web-time", - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", + "windows-sys", ] [[package]] @@ -2087,18 +1884,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - [[package]] name = "sha1" version = "0.10.6" @@ -2144,7 +1929,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core 0.6.4", + "rand_core", ] [[package]] @@ -2178,7 +1963,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2222,6 +2007,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.27.2" @@ -2265,9 +2056,6 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] [[package]] name = "synstructure" @@ -2290,7 +2078,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2354,21 +2142,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "tinyvec" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - [[package]] name = "tokio" version = "1.52.1" @@ -2383,7 +2156,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2397,16 +2170,6 @@ dependencies = [ "syn", ] -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -2456,25 +2219,6 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" -dependencies = [ - "bitflags", - "bytes", - "futures-util", - "http", - "http-body", - "iri-string", - "pin-project-lite", - "tower", "tower-layer", "tower-service", ] @@ -2522,12 +2266,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - [[package]] name = "typenum" version = "1.20.0" @@ -2546,12 +2284,6 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - [[package]] name = "url" version = "2.5.8" @@ -2562,6 +2294,7 @@ dependencies = [ "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] @@ -2570,6 +2303,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.23.1" @@ -2587,15 +2326,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2633,16 +2363,6 @@ dependencies = [ "wasm-bindgen-shared", ] -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.68" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "wasm-bindgen-macro" version = "0.2.118" @@ -2709,35 +2429,6 @@ dependencies = [ "semver", ] -[[package]] -name = "web-sys" -version = "0.3.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "windows-core" version = "0.62.2" @@ -2797,24 +2488,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -2824,135 +2497,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winnow" version = "0.7.15" diff --git a/proxy-core/src/config.rs b/proxy-core/src/config.rs index 4d4d6b9..b2cdafd 100644 --- a/proxy-core/src/config.rs +++ b/proxy-core/src/config.rs @@ -12,17 +12,33 @@ use std::{ net::{IpAddr, Ipv4Addr}, - path::PathBuf, + path::Path, }; -use clap::Parser; use serde::{Deserialize, Deserializer, de}; -use url::Url; use crate::error::{ProxyError, Result}; -#[derive(Deserialize, Default)] -#[serde(default)] +/// Required byte length for EID and GID fields per ISO 13400-2. +const EID_GID_BYTE_LENGTH: usize = 6; + +// Default values for ServerConfig. +const DEFAULT_DOIP_PORT: u16 = 13400; +const DEFAULT_MAX_CONNECTIONS: usize = 10; +/// DoIP source address (tester logical address used in response messages). +const DEFAULT_SOURCE_ADDRESS: u16 = 0x0E80; + +// Default values for SovdConfig. +const DEFAULT_GATEWAY_URL: &str = "http://localhost:20002"; +const DEFAULT_CLIENT_ID: &str = "uds2sovd_proxy"; +const DEFAULT_CLIENT_SECRET: &str = "test_secret"; +const DEFAULT_TIMEOUT_MS: u64 = 5000; +const DEFAULT_API_VERSION: &str = "v15"; + +// Default values for EcuConfig. +const DEFAULT_ECU_NAME: &str = "ECU"; +/// Top-level proxy configuration loaded from a TOML file. +#[derive(Debug, Clone, Deserialize, Default)] pub struct Config { /// `DoIP` server settings (port, bind address, source address). pub server: ServerConfig, @@ -34,33 +50,23 @@ pub struct Config { pub logging: LoggingConfig, } -#[derive(Deserialize)] -#[serde(default)] +/// `DoIP` server configuration. +#[derive(Debug, Clone, Deserialize)] pub struct ServerConfig { - /// TCP port for the `DoIP` server (default: 13 400). + /// TCP port for the `DoIP` server (default: 13400). #[serde(deserialize_with = "deserialize_nonzero_u16")] pub doip_port: u16, - /// IP address to bind the server socket to (default: `0.0.0.0`). + /// IP address to bind the server socket to. + #[serde(deserialize_with = "deserialize_ip_addr")] pub bind_address: IpAddr, - /// Maximum number of concurrent connections (default: 10). + /// Maximum number of concurrent connections. #[serde(deserialize_with = "deserialize_max_connections")] pub max_connections: usize, - /// `DoIP` source address used in response messages (default: `0x0E80`). + /// `DoIP` source address used in response messages. #[serde(deserialize_with = "deserialize_nonzero_u16")] pub source_address: u16, } -impl Default for ServerConfig { - fn default() -> Self { - Self { - doip_port: 13_400, - bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), - max_connections: 10, - source_address: 0x0E80, - } - } -} - fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -71,6 +77,16 @@ fn deserialize_nonzero_u16<'de, D: Deserializer<'de>>( Ok(v) } +/// Deserialize IP address string into `std::net::IpAddr`. +fn deserialize_ip_addr<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let s = String::deserialize(deserializer)?; + s.parse::() + .map_err(|_| de::Error::custom(format!("invalid IP address: {s}"))) +} + +/// Reject zero during deserialization for `usize` fields. fn deserialize_max_connections<'de, D: Deserializer<'de>>( deserializer: D, ) -> std::result::Result { @@ -81,11 +97,22 @@ fn deserialize_max_connections<'de, D: Deserializer<'de>>( Ok(v) } -#[derive(Clone, Deserialize)] -#[serde(default)] +/// Reject empty gateway URL strings during deserialization. +fn deserialize_nonempty_gateway_url<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let s = String::deserialize(deserializer)?; + if s.is_empty() { + return Err(de::Error::custom("gateway_url must not be empty")); + } + Ok(s) +} +/// SOVD gateway connection configuration. +#[derive(Debug, Clone, Deserialize)] pub struct SovdConfig { /// Base URL of the SOVD gateway (e.g. `http://localhost:20002`). - pub gateway_url: Url, + #[serde(deserialize_with = "deserialize_nonempty_gateway_url")] + pub gateway_url: String, /// `OAuth2` client ID for gateway authentication. pub client_id: String, /// `OAuth2` client secret for gateway authentication. @@ -95,541 +122,291 @@ pub struct SovdConfig { /// SOVD API version path segment (e.g. `v15`). pub api_version: String, /// Whether to request inline schema in data responses. + #[serde(default = "SovdConfig::default_include_schema")] pub include_schema: bool, /// When `true`, bypass HTTP calls and generate synthetic responses. + #[serde(default)] pub mock_gateway: bool, } -impl Default for SovdConfig { - fn default() -> Self { - Self { - gateway_url: "http://localhost:20002" - .parse() - .expect("hard-coded URL is always valid"), - client_id: "uds2sovd_proxy".into(), - client_secret: "test_secret".into(), - timeout_ms: 5_000, - api_version: "v15".into(), - include_schema: true, - mock_gateway: true, - } - } -} - -#[derive(Clone, Copy, Deserialize)] -pub struct EidGid([u8; 6]); - -impl EidGid { - fn is_all_zeros(self) -> bool { - self.0 == [0u8; 6] - } -} - -impl Default for EidGid { - fn default() -> Self { - Self([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]) +impl SovdConfig { + fn default_include_schema() -> bool { + true } } -#[derive(Deserialize)] -#[serde(default)] +/// ECU identity and addressing configuration. +#[derive(Debug, Clone, Deserialize)] pub struct EcuConfig { /// Default ECU name used for SOVD component path. pub default_name: String, /// ISO 13400 logical address of the target ECU. #[serde(deserialize_with = "deserialize_nonzero_u16")] pub logical_address: u16, - /// 6-byte Entity Identification - pub eid: EidGid, + /// 6-byte Entity Identification (MAC address). + pub eid: [u8; EID_GID_BYTE_LENGTH], /// 6-byte Group Identification. - pub gid: EidGid, -} - -impl Default for EcuConfig { - fn default() -> Self { - Self { - default_name: "ECU".into(), - logical_address: 0x0001, - eid: EidGid::default(), - gid: EidGid::default(), - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] -#[serde(rename_all = "lowercase")] -pub enum LogLevel { - Error, - Warn, - #[default] - Info, - Debug, - Trace, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, clap::ValueEnum)] -#[serde(rename_all = "lowercase")] -pub enum LogFormat { - /// Human-readable coloured output (default). - #[default] - Pretty, - /// Machine-readable JSON (suitable for log aggregators). - Json, + pub gid: [u8; EID_GID_BYTE_LENGTH], } /// Logging output configuration. -#[derive(Deserialize, Default)] -#[serde(default)] +#[derive(Debug, Clone, Deserialize)] pub struct LoggingConfig { - /// Log level filter. - pub level: LogLevel, - /// Output format. - pub format: LogFormat, -} - -/// Any flag set here overrides the corresponding value from the TOML file. -#[derive(Parser)] -#[command(name = "uds2sovd-proxy", version)] -pub struct Cli { - /// Path to the TOML configuration file. - #[arg( - short, - long, - value_name = "FILE", - env = "PROXY_CONFIG", - default_value = "config/config.toml" - )] - pub config: PathBuf, - - /// Override the IP address to bind to. - #[arg(long, value_name = "ADDR", env = "PROXY_BIND_ADDRESS")] - pub bind_address: Option, - - /// Override the SOVD gateway URL. - #[arg(long, value_name = "URL", env = "PROXY_GATEWAY_URL")] - pub gateway_url: Option, - - /// Enable mock gateway mode (no real HTTP calls). - #[arg(long, env = "PROXY_MOCK_GATEWAY")] - pub mock_gateway: bool, - - /// Override the log level. - #[arg(long, value_enum, value_name = "LEVEL", env = "PROXY_LOG_LEVEL")] - pub log_level: Option, - - /// Override the log output format. - #[arg(long, value_enum, value_name = "FORMAT", env = "PROXY_LOG_FORMAT")] - pub log_format: Option, - - /// MDD file to load (absolute path, or filename resolved under `--mdd-dir`). - #[arg(short, long)] - pub mdd_file: PathBuf, - - /// Directory searched when `--mdd-file` is a relative filename. - #[arg(long, default_value = "testcontainer/mdd")] - pub mdd_dir: PathBuf, + /// Log level filter (e.g. `info`, `debug`, `trace`). + pub level: String, + /// Output format: `pretty` (default) or `json`. + pub format: String, } impl Config { - /// Build a fully-validated [`Config`] by layering defaults, a TOML file, - /// and CLI overrides. - /// - /// # Layer order - /// 1. [`Default`] values - /// 2. TOML file at the path given by `cli.config` - /// 3. CLI flags - /// - /// # Errors - /// Returns [`ProxyError::Config`] if the TOML file cannot be read/parsed - /// or if the merged configuration fails validation. - pub fn load(cli: &Cli) -> Result { - // defaults + TOML file - let mut config = if cli.config.exists() { - Self::from_file(&cli.config)? - } else { - Self::default() - }; - - // CLI overrides - if let Some(addr) = cli.bind_address { - config.server.bind_address = addr; - } - if let Some(ref url) = cli.gateway_url { - config.sovd.gateway_url = url.clone(); - } - if cli.mock_gateway { - config.sovd.mock_gateway = true; - } - if let Some(level) = cli.log_level { - config.logging.level = level; - } - if let Some(format) = cli.log_format { - config.logging.format = format; - } - - config.validate()?; - Ok(config) - } - - /// Load and validate configuration from a TOML file (without CLI overrides). + /// Load configuration from TOML file /// /// # Errors - /// Returns [`ProxyError::Config`] if the file cannot be read, parsed, or - /// if the resulting configuration fails validation. - pub fn from_file>(path: P) -> Result { - let path = path.as_ref(); + /// Returns an error if the file cannot be read or parsed. + pub fn from_file>(path: P) -> Result { let content = std::fs::read_to_string(path) - .map_err(|e| ProxyError::Config(format!("cannot read `{}`: {e}", path.display())))?; + .map_err(|e| ProxyError::Config(format!("Failed to read config file: {e}")))?; - let config: Self = toml::from_str(&content) - .map_err(|e| ProxyError::Config(format!("cannot parse `{}`: {e}", path.display())))?; - - config.validate()?; - Ok(config) + toml::from_str(&content) + .map_err(|e| ProxyError::Config(format!("Failed to parse config: {e}"))) } +} - /// Validate the fully-merged configuration. - fn validate(&self) -> Result<()> { - let mut errors: Vec = Vec::new(); - - if self.server.max_connections == 0 { - errors.push("[server] max_connections must be greater than zero".into()); - } - if self.sovd.client_id.is_empty() { - errors.push("[sovd] client_id must not be empty".into()); - } - if self.sovd.api_version.is_empty() { - errors.push("[sovd] api_version must not be empty".into()); - } - if self.ecu.default_name.is_empty() { - errors.push("[ecu] default_name must not be empty".into()); - } - if self.ecu.eid.is_all_zeros() { - errors.push("[ecu] eid must not be all zeros".into()); - } - if self.ecu.gid.is_all_zeros() { - errors.push("[ecu] gid must not be all zeros".into()); - } - - if errors.is_empty() { - Ok(()) - } else { - Err(ProxyError::Config(format!( - "configuration validation failed:\n - {}", - errors.join("\n - ") - ))) +impl Default for ServerConfig { + fn default() -> Self { + Self { + doip_port: DEFAULT_DOIP_PORT, + bind_address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), + max_connections: DEFAULT_MAX_CONNECTIONS, + source_address: DEFAULT_SOURCE_ADDRESS, } } } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn eid_gid_holds_expected_bytes() { - let eid = EidGid([0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); - assert_eq!(eid.0, [0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]); - } - - #[test] - fn eid_gid_all_zeros_detected() { - let eid = EidGid([0u8; 6]); - assert!(eid.is_all_zeros()); - - let eid2 = EidGid([0, 1, 2, 3, 4, 5]); - assert!(!eid2.is_all_zeros()); - } - - #[test] - fn log_level_deserializes_all_variants_from_toml() { - #[derive(Deserialize)] - struct Wrapper { - level: LogLevel, - } - - for (raw, expected) in [ - ("error", LogLevel::Error), - ("warn", LogLevel::Warn), - ("info", LogLevel::Info), - ("debug", LogLevel::Debug), - ("trace", LogLevel::Trace), - ] { - let parsed: Wrapper = - toml::from_str(&format!("level = \"{raw}\"")).expect("valid level"); - assert_eq!(parsed.level, expected); +impl Default for SovdConfig { + fn default() -> Self { + Self { + gateway_url: DEFAULT_GATEWAY_URL.to_string(), + client_id: DEFAULT_CLIENT_ID.to_string(), + client_secret: DEFAULT_CLIENT_SECRET.to_string(), + timeout_ms: DEFAULT_TIMEOUT_MS, + api_version: DEFAULT_API_VERSION.to_string(), + include_schema: true, + mock_gateway: false, } } +} - #[test] - fn log_format_deserializes_all_variants_from_toml() { - #[derive(Deserialize)] - struct Wrapper { - format: LogFormat, - } - - for (raw, expected) in [("pretty", LogFormat::Pretty), ("json", LogFormat::Json)] { - let parsed: Wrapper = - toml::from_str(&format!("format = \"{raw}\"")).expect("valid format"); - assert_eq!(parsed.format, expected); +impl Default for EcuConfig { + fn default() -> Self { + Self { + default_name: DEFAULT_ECU_NAME.to_string(), + logical_address: 0x0001, + eid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], + gid: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05], } } +} - #[test] - fn server_defaults_are_sane() { - let s = ServerConfig::default(); - assert_eq!(s.doip_port, 13_400); - assert_eq!(s.max_connections, 10); - } - - #[test] - fn sovd_defaults_are_sane() { - let s = SovdConfig::default(); - assert!(s.mock_gateway); - assert!(s.include_schema); - assert_eq!(s.timeout_ms, 5_000); - } - - #[test] - fn validation_rejects_empty_client_id() { - let mut config = Config::default(); - config.sovd.client_id = String::new(); - assert!(config.validate().is_err()); +impl Default for LoggingConfig { + fn default() -> Self { + Self { + level: "info".to_string(), + format: "pretty".to_string(), + } } +} - #[test] - fn validation_rejects_all_zero_eid() { - let mut config = Config::default(); - config.ecu.eid = EidGid([0u8; 6]); - assert!(config.validate().is_err()); - } +#[cfg(test)] +mod tests { + use super::*; #[test] - fn validation_rejects_zero_max_connections() { - let mut config = Config::default(); - config.server.max_connections = 0; - assert!(config.validate().is_err()); + fn test_default_config() { + let config = Config::default(); + assert_eq!(config.server.doip_port, 13400); + assert_eq!(config.sovd.api_version, "v15"); + assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); } #[test] - fn validation_accumulates_multiple_errors() { - let mut config = Config::default(); - config.sovd.client_id = String::new(); - config.sovd.api_version = String::new(); - config.ecu.eid = EidGid([0u8; 6]); - let err = config.validate().unwrap_err().to_string(); - // Three separate bullets should appear. - assert_eq!(err.matches(" - ").count(), 3); + fn test_deserialize_valid_config() { + let toml_str = r#" + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let config: Config = toml::from_str(toml_str).expect("valid config should parse"); + assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); + assert_eq!(config.server.doip_port, 13400); } #[test] - fn toml_parses_complete_config() { - let raw = r#" -[server] -bind_address = "127.0.0.1" -max_connections = 5 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 3000 -api_version = "v15" -include_schema = false -mock_gateway = true - -[ecu] -default_name = "TEST_ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "debug" -format = "json" -"#; - let cfg: Config = toml::from_str(raw).expect("valid TOML"); - assert!(cfg.sovd.mock_gateway); - assert_eq!(cfg.logging.level, LogLevel::Debug); - assert_eq!(cfg.logging.format, LogFormat::Json); + fn test_deserialize_rejects_zero_port() { + let toml_str = r#" + [server] + doip_port = 0 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; + let result = toml::from_str::(toml_str); + assert!(result.is_err(), "doip_port=0 should be rejected"); } #[test] - fn deserialize_rejects_zero_max_connections() { + fn test_deserialize_rejects_zero_max_connections() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 0 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 0 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "max_connections=0 should be rejected"); } #[test] - fn deserialize_rejects_zero_logical_address() { + fn test_deserialize_rejects_zero_logical_address() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 0 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 0 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "logical_address=0 should be rejected"); } #[test] - fn deserialize_rejects_wrong_eid_length() { + fn test_deserialize_rejects_wrong_eid_length() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "http://localhost:20002" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); assert!(result.is_err(), "eid with wrong length should be rejected"); } #[test] - fn deserialize_rejects_invalid_gateway_url() { - let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "not a valid url" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "info" -format = "pretty" -"#; - let result = toml::from_str::(toml_str); - assert!(result.is_err(), "invalid gateway_url should be rejected"); - } - - #[test] - fn deserialize_rejects_invalid_log_level() { + fn test_deserialize_rejects_empty_gateway_url() { let toml_str = r#" -[server] -bind_address = "0.0.0.0" -max_connections = 10 -source_address = 3712 - -[sovd] -gateway_url = "http://localhost:20002" -client_id = "test" -client_secret = "secret" -timeout_ms = 5000 -api_version = "v15" - -[ecu] -default_name = "ECU" -logical_address = 1 -eid = [0, 1, 2, 3, 4, 5] -gid = [0, 1, 2, 3, 4, 5] - -[logging] -level = "verbose" -format = "pretty" -"#; + [server] + doip_port = 13400 + bind_address = "0.0.0.0" + max_connections = 10 + source_address = 3712 + + [sovd] + gateway_url = "" + client_id = "test" + client_secret = "secret" + timeout_ms = 5000 + api_version = "v15" + + [ecu] + default_name = "ECU" + logical_address = 1 + eid = [0, 1, 2, 3, 4, 5] + gid = [0, 1, 2, 3, 4, 5] + + [logging] + level = "info" + format = "pretty" + "#; let result = toml::from_str::(toml_str); - assert!(result.is_err(), "invalid log level should be rejected"); - } - - // โ”€โ”€ CLI integration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - - #[test] - fn cli_overrides_default_values() { - let cli = Cli::parse_from([ - "uds2sovd-proxy", - "--config", - "/nonexistent/path.toml", - "--log-level", - "debug", - "--mock-gateway", - "--mdd-file", - "test.mdd", - ]); - - let config = Config::load(&cli).expect("should build from defaults + CLI"); - assert_eq!(config.logging.level, LogLevel::Debug); - assert!(config.sovd.mock_gateway); - } - - #[test] - fn toml_with_missing_sections_uses_defaults() { - let raw = r#" -[server] -bind_address = "127.0.0.1" -max_connections = 5 -source_address = 3712 -"#; - let cfg: Config = toml::from_str(raw).expect("partial TOML should parse"); - assert_eq!(cfg.sovd.api_version, "v15"); - assert_eq!(cfg.logging.level, LogLevel::Info); + assert!(result.is_err(), "empty gateway_url should be rejected"); } } From f8ca5c76dba46494539be47fb11b158afb589be1 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Wed, 22 Apr 2026 09:57:49 +0200 Subject: [PATCH 25/33] feat: add proxy-sovd crate with SOVD REST client and UDS<->SOVD mapper Signed-off-by: Arvind Rathod --- Cargo.lock | 741 ++++++++++++++++++++++++++------- proxy-sovd/Cargo.toml | 1 + proxy-sovd/src/client.rs | 83 ++-- proxy-sovd/src/diag_handler.rs | 61 +-- proxy-sovd/src/mapper.rs | 135 +++--- proxy-sovd/src/schema.rs | 5 +- 6 files changed, 722 insertions(+), 304 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index de0fdde..b749c0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,56 +46,6 @@ dependencies = [ "libc", ] -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys", -] - [[package]] name = "anyhow" version = "1.0.102" @@ -113,6 +63,12 @@ dependencies = [ "syn", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.0" @@ -349,6 +305,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + [[package]] name = "chrono" version = "0.4.44" @@ -362,52 +324,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - [[package]] name = "const-oid" version = "0.9.6" @@ -436,7 +352,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", - "rand_core", + "rand_core 0.6.4", "subtle", "zeroize", ] @@ -586,7 +502,7 @@ dependencies = [ "hkdf", "pem-rfc7468", "pkcs8", - "rand_core", + "rand_core 0.6.4", "sec1", "subtle", "zeroize", @@ -605,7 +521,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -620,7 +536,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -778,8 +694,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", ] [[package]] @@ -790,7 +722,7 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", "wasip2", "wasip3", ] @@ -802,7 +734,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -914,12 +846,77 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "httparse" +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 = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -1045,9 +1042,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.2" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" dependencies = [ "icu_normalizer", "icu_properties", @@ -1066,10 +1063,20 @@ dependencies = [ ] [[package]] -name = "is_terminal_polyfill" -version = "1.70.2" +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" +dependencies = [ + "memchr", + "serde", +] [[package]] name = "itertools" @@ -1092,6 +1099,8 @@ version = "0.3.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" dependencies = [ + "cfg-if", + "futures-util", "once_cell", "wasm-bindgen", ] @@ -1110,7 +1119,7 @@ dependencies = [ "p256", "p384", "pem", - "rand", + "rand 0.8.6", "rsa", "serde", "serde_json", @@ -1136,9 +1145,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.185" +version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" [[package]] name = "libm" @@ -1173,6 +1182,12 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "lzma-sys" version = "0.1.20" @@ -1219,7 +1234,7 @@ checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1249,7 +1264,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand", + "rand 0.8.6", "smallvec", "zeroize", ] @@ -1296,12 +1311,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - [[package]] name = "ouroboros" version = "0.18.5" @@ -1566,14 +1575,81 @@ dependencies = [ "cda-database", "cda-interfaces", "cda-plugin-security", - "clap", "serde", "serde_json", "thiserror", "tokio", "toml", "tracing", - "url", +] + +[[package]] +name = "proxy-sovd" +version = "0.1.0" +dependencies = [ + "async-trait", + "cda-interfaces", + "proxy-core", + "reqwest", + "serde", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.4", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", ] [[package]] @@ -1585,6 +1661,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -1598,8 +1680,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", ] [[package]] @@ -1609,7 +1701,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -1621,6 +1723,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1679,6 +1790,44 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -1689,6 +1838,20 @@ dependencies = [ "subtle", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rsa" version = "0.9.10" @@ -1702,13 +1865,19 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", "signature", "spki", "subtle", "zeroize", ] +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + [[package]] name = "rustc_version" version = "0.4.1" @@ -1728,7 +1897,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c2c118cb077cca2822033836dfb1b975355dfb784b5e8da48f7b6c5db74e60e" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -1884,6 +2088,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1" version = "0.10.6" @@ -1929,7 +2145,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1963,7 +2179,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2007,12 +2223,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - [[package]] name = "strum" version = "0.27.2" @@ -2056,6 +2266,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -2078,7 +2291,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2142,6 +2355,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" version = "1.52.1" @@ -2156,7 +2384,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2170,6 +2398,16 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -2219,6 +2457,25 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", "tower-layer", "tower-service", ] @@ -2266,6 +2523,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.0" @@ -2284,6 +2547,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -2294,7 +2563,6 @@ dependencies = [ "idna", "percent-encoding", "serde", - "serde_derive", ] [[package]] @@ -2303,12 +2571,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "uuid" version = "1.23.1" @@ -2326,6 +2588,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2363,6 +2634,16 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.118" @@ -2429,6 +2710,35 @@ dependencies = [ "semver", ] +[[package]] +name = "web-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -2488,6 +2798,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -2497,6 +2825,135 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.7.15" diff --git a/proxy-sovd/Cargo.toml b/proxy-sovd/Cargo.toml index 1b9c21d..4962dc1 100644 --- a/proxy-sovd/Cargo.toml +++ b/proxy-sovd/Cargo.toml @@ -19,6 +19,7 @@ license.workspace = true [dependencies] proxy-core = { workspace = true } +async-trait = { workspace = true } cda-interfaces = { workspace = true } reqwest = { workspace = true, features = ["json", "rustls-tls"] } serde = { workspace = true } diff --git a/proxy-sovd/src/client.rs b/proxy-sovd/src/client.rs index ba75d68..5f95781 100644 --- a/proxy-sovd/src/client.rs +++ b/proxy-sovd/src/client.rs @@ -21,6 +21,7 @@ use reqwest::{Client, StatusCode}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use tokio::sync::RwLock; +use tracing::{debug, info}; use crate::schema::DataResponse; @@ -83,11 +84,10 @@ impl SovdClient { if self.config.mock_gateway { let token = "mock-access-token".to_string(); *self.access_token.write().await = Some(token.clone()); - tracing::info!("[SOVD] Mock authentication enabled"); + info!("[SOVD] Mock authentication enabled"); return Ok(token); } - // TODO(sovd-server): OAuth2 token exchange - only reached when mock_gateway = false. let url = format!( "{}/vehicle/{}/authorize", self.config.gateway_url, self.config.api_version @@ -120,16 +120,6 @@ impl SovdClient { Ok(auth_resp.access_token) } - /// Return a cached access token, or fetch a fresh one by calling [`authenticate`]. - /// - /// The token is stored in a shared read-write lock so concurrent requests - /// can read it without blocking each other. A new token is only requested - /// when the cache is empty. - /// - /// # Errors - /// Propagates any error returned by [`authenticate`]. - // TODO(sovd-server): token cache helper - only called from the read_data / write_data - // paths that are bypassed when mock_gateway = true. async fn get_token(&self) -> Result { { let token_guard = self.access_token.read().await; @@ -144,11 +134,6 @@ impl SovdClient { /// /// # Errors /// Returns an error if the read request fails. - /// - /// # Note - /// Not called when `mock_gateway = true` - [`SovdMapper`] intercepts the request - /// in [`SovdMapper::mock_read_response`] before reaching this function. - // TODO(sovd-server): placeholder - wire up once a real SOVD server is available. pub async fn read_data(&self, component: &str, data_id: &str) -> Result { let token = self.get_token().await?; let url = format!( @@ -156,7 +141,7 @@ impl SovdClient { self.config.gateway_url, self.config.api_version, component, data_id ); - tracing::info!("[SOVD] GET {}", url); + info!("[SOVD] GET {}", url); let mut request = self.client.get(&url).bearer_auth(&token); if self.config.include_schema { @@ -170,12 +155,12 @@ impl SovdClient { match response.status() { StatusCode::OK => { - tracing::info!("[SOVD] Response: HTTP 200 OK"); let data: DataResponse = response .json() .await .map_err(|e| SovdError::Http(e.to_string()))?; - tracing::debug!("[SOVD] Data: {} = {:?}", data.id, data.data); + info!("[SOVD] Response: HTTP 200 OK"); + debug!("[SOVD] Data: {} = {:?}", data.id, data.data); Ok(data) } StatusCode::NOT_FOUND => Err(SovdError::DataIdNotFound(data_id.to_string()).into()), @@ -198,15 +183,13 @@ impl SovdClient { ) -> Result<()> { if self.config.mock_gateway { // SID 0x2E (WriteDataByIdentifier) maps to SOVD /configurations/{service} - tracing::info!( + info!( "[SOVD MOCK] PUT /components/{}/configurations/{}", - component, - data_id + component, data_id ); return Ok(()); } - // TODO(sovd-server): real HTTP PUT - only reached when mock_gateway = false. let token = self.get_token().await?; let url = format!( @@ -214,7 +197,7 @@ impl SovdClient { self.config.gateway_url, self.config.api_version, component, data_id ); - tracing::info!("[SOVD] PUT {}", url); + info!("[SOVD] PUT {}", url); let write_req = WriteDataRequest { data: Value::Object(data), @@ -231,7 +214,7 @@ impl SovdClient { match response.status() { StatusCode::NO_CONTENT | StatusCode::OK | StatusCode::ACCEPTED => { - tracing::info!("[SOVD] Write successful: HTTP {}", response.status()); + info!("[SOVD] Write successful: HTTP {}", response.status()); Ok(()) } StatusCode::BAD_REQUEST => { @@ -261,7 +244,6 @@ impl SovdClient { /// /// When the service uses MUX cases, only parameters belonging to the /// case that matches `did` are included. - /// TODO(sovd-server): Remove this function once sovd-server provides real responses. #[must_use] pub fn generate_mock_response_data( &self, @@ -284,9 +266,12 @@ impl SovdClient { return false; } if p.name.contains('/') { - match &mux_case_prefix { - Some(prefix) if p.name.starts_with(prefix.as_str()) => {} - _ => return false, + if let Some(prefix) = &mux_case_prefix { + if !p.name.starts_with(prefix.as_str()) { + return false; + } + } else { + return false; } } matches!( @@ -309,9 +294,12 @@ impl SovdClient { } // Skip params from non-matching MUX cases. if p.name.contains('/') { - match &mux_case_prefix { - Some(prefix) if p.name.starts_with(prefix.as_str()) => {} - _ => continue, + if let Some(prefix) = &mux_case_prefix { + if !p.name.starts_with(prefix.as_str()) { + continue; + } + } else { + continue; } } // Skip coded const and matching request params โ€” encoder fills those. @@ -335,7 +323,7 @@ impl SovdClient { // comes from the ECU / SOVD server in production. Self::mock_opaque_payload(did) } else { - Self::default_value_for_param(p.byte_size) + Self::default_value_for_param(&key, p.byte_size, p.semantic.as_deref()) }; data.insert(key, value); } @@ -349,12 +337,15 @@ impl SovdClient { /// byte size only. /// /// This is MDD-agnostic โ€” no ECU-specific name patterns or DID heuristics. - /// For small fields (1โ€“8 bytes), produces a numeric equal to the byte - /// size as a distinguishable non-zero placeholder. Larger fields are - /// emitted as zero-filled byte arrays. - fn default_value_for_param(byte_size: Option) -> Value { + /// Produces zero-valued numerics or zero-filled byte arrays that satisfy + /// the MDD response encoder without assuming a particular ECU. + fn default_value_for_param( + _name: &str, + byte_size: Option, + _semantic: Option<&str>, + ) -> Value { match byte_size { - Some(sz @ 1..=8) => Value::Number(u64::from(sz).into()), + Some(sz @ 1..=8) => Value::Number(0u64.wrapping_add(u64::from(sz)).into()), Some(sz) => { // Large fields: zero-filled byte array. Value::Array(vec![Value::Number(0.into()); sz as usize]) @@ -368,8 +359,6 @@ impl SovdClient { /// /// Uses a fixed conservative size (4 bytes of zeros) that satisfies the /// MDD response encoder without assuming any ECU-specific layout. - /// Return a fixed-size opaque byte array for services whose response - /// layout cannot be inferred from metadata fn mock_opaque_payload(_did: u16) -> Value { const DEFAULT_OPAQUE_SIZE: usize = 4; Value::Array(vec![Value::Number(0.into()); DEFAULT_OPAQUE_SIZE]) @@ -420,9 +409,7 @@ mod tests { fn create_test_config() -> SovdConfig { SovdConfig { - gateway_url: "http://localhost:20002" - .parse() - .expect("hard-coded URL is always valid"), + gateway_url: "http://localhost:20002".to_string(), client_id: "test-client".to_string(), client_secret: "test-secret".to_string(), timeout_ms: 5000, @@ -730,21 +717,21 @@ mod tests { fn test_default_value_for_param_generic() { // 1-byte VALUE -> numeric 1 assert_eq!( - SovdClient::default_value_for_param(Some(1)), + SovdClient::default_value_for_param("ANY_FIELD", Some(1), None), Value::Number(1.into()), ); // 2-byte VALUE -> numeric 2 assert_eq!( - SovdClient::default_value_for_param(Some(2)), + SovdClient::default_value_for_param("VIN", Some(2), Some("DATA")), Value::Number(2.into()), ); // 17-byte VALUE -> zero-filled array (no VIN heuristic) - let val = SovdClient::default_value_for_param(Some(17)); + let val = SovdClient::default_value_for_param("VIN", Some(17), None); let arr = val.as_array().unwrap(); assert_eq!(arr.len(), 17); // None byte_size -> 0 assert_eq!( - SovdClient::default_value_for_param(None), + SovdClient::default_value_for_param("X", None, None), Value::Number(0.into()), ); } diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 65dd783..3309c07 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -10,23 +10,21 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; -use cda_interfaces::HashMap; -use proxy_core::{ - Config, ProxyError, ResolvedService, Result, ServiceResolver, ServiceType, error::UdsError, -}; +use async_trait::async_trait; +use proxy_core::{Config, DiagHandler, ProxyError, Result, ServiceResolver, error::UdsError}; use tracing::info; use crate::mapper::SovdMapper; -/// SOVD-backed diagnostic handler. +/// SOVD-backed implementation of [`DiagHandler`]. /// /// Combines MDD-based service resolution ([`ServiceResolver`]) with SOVD /// gateway communication ([`SovdMapper`]) to process UDS diagnostic requests. /// /// Constructed in `proxy-main` and injected into the `DoIP` server as -/// `Arc`. +/// `Arc`. pub struct SovdDiagHandler { /// Shared proxy configuration. config: Arc, @@ -59,57 +57,38 @@ impl SovdDiagHandler { } } -impl SovdDiagHandler { - /// Process a `ReadDataByIdentifier` (0x22) request. - /// - /// `did` is the extracted 16-bit Data Identifier. - /// `uds_request` is the full UDS request bytes including the SID byte. - /// - /// Returns the complete UDS response bytes (positive or negative). - /// - /// # Errors - /// Returns an error if no MDD database is loaded, the DID is unknown, - /// or the SOVD gateway request fails. - pub async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result> { +#[async_trait] +impl DiagHandler for SovdDiagHandler { + async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result> { let mgr = self .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let ResolvedService { - name: service_name, - params: parsed_data, - } = mgr - .resolve(ServiceType::Read, did, uds_request) + let (service_name, parsed_data) = mgr + .resolve_read_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; info!("[MDD] READ service found: '{}'", service_name); self.mapper - .process_read_data_request(did, uds_request, mgr, &service_name, Some(parsed_data)) + .process_read_data_request( + did, + uds_request, + Some(mgr), + &service_name, + Some(parsed_data), + ) .await } - /// Process a `WriteDataByIdentifier` (0x2E) request. - /// - /// `did` is the extracted 16-bit Data Identifier. - /// `uds_request` is the full UDS request bytes including the SID byte. - /// - /// Returns the complete UDS response bytes (positive or negative). - /// - /// # Errors - /// Returns an error if no MDD database is loaded, the DID is unknown, - /// or the SOVD gateway request fails. - pub async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result> { + async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result> { let mgr = self .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let ResolvedService { - name: service_name, - params: parsed_data, - } = mgr - .resolve(ServiceType::Write, did, uds_request) + let (service_name, parsed_data) = mgr + .resolve_write_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; diff --git a/proxy-sovd/src/mapper.rs b/proxy-sovd/src/mapper.rs index c466208..5a92e65 100644 --- a/proxy-sovd/src/mapper.rs +++ b/proxy-sovd/src/mapper.rs @@ -16,6 +16,7 @@ use proxy_core::{ error::{Result, SovdError}, }; use serde_json::{Map, Value}; +use tracing::{debug, info, trace}; use crate::{client::SovdClient, schema::DataResponse}; @@ -43,26 +44,18 @@ const MIN_WDBI_REQUEST_HEADER_LENGTH: usize = 3; /// - TODO(sovd): Forward parsed request data to the SOVD gateway for /// write requests that need request-parameter context. pub struct SovdMapper { - /// ECU component name used in SOVD REST paths. - ecu_name: String, - /// When `true`, bypass HTTP and generate synthetic responses. - mock_gateway: bool, - /// Base URL of the SOVD gateway - gateway_url: String, - /// SOVD API version path segment - api_version: String, + /// Proxy configuration (ECU, SOVD endpoint, mock settings). + config: Config, /// HTTP client for the SOVD gateway. sovd_client: SovdClient, } impl SovdMapper { + /// Create a new mapper with the given configuration and SOVD client. #[must_use] - pub fn new(config: &Config, sovd_client: SovdClient) -> Self { + pub fn new(config: Config, sovd_client: SovdClient) -> Self { Self { - ecu_name: config.ecu.default_name.clone(), - mock_gateway: config.sovd.mock_gateway, - gateway_url: config.sovd.gateway_url.to_string(), - api_version: config.sovd.api_version.clone(), + config, sovd_client, } } @@ -73,47 +66,44 @@ impl SovdMapper { &self, did: u16, uds_request: &[u8], - resolver: &ServiceResolver, + ecu_manager: Option<&ServiceResolver>, service_name: &str, parsed_data: Option>, ) -> Result> { - tracing::debug!( + debug!( "[RDBI] DID 0x{:04X} service='{}' request={:02X?}", - did, - service_name, - uds_request + did, service_name, uds_request ); if let Some(ref parsed) = parsed_data { - tracing::trace!( + trace!( "[RDBI] Parsed request: {}", serde_json::to_string_pretty(parsed).unwrap_or_default() ); } let sovd_endpoint = service_name.to_lowercase(); + let component = &self.config.ecu.default_name; - let sovd_response = if self.mock_gateway { - self.mock_read_response(did, service_name, &sovd_endpoint, resolver) + let sovd_response = if self.config.sovd.mock_gateway { + self.mock_read_response(did, service_name, &sovd_endpoint, ecu_manager) .await? } else { - // TODO(sovd-server): read path - not exercised while mock_gateway = true. let resp = self .sovd_client - .read_data(&self.ecu_name, &sovd_endpoint) + .read_data(component, &sovd_endpoint) .await?; - tracing::debug!( + debug!( "[RDBI] SOVD response for '{}': {:?}", - sovd_endpoint, - resp.data + sovd_endpoint, resp.data ); resp }; let uds_response = self - .sovd_json_to_uds(did, &sovd_response, resolver, service_name) + .sovd_json_to_uds(did, &sovd_response, ecu_manager, service_name) .await?; - tracing::info!( + info!( "[RDBI] DID 0x{:04X} '{}' -> {} bytes: {:02X?}", did, service_name, @@ -138,13 +128,16 @@ impl SovdMapper { let sovd_endpoint = service_name.to_lowercase(); - tracing::debug!( + let sovd_write_data = parsed_data; + debug!( "[WDBI] SOVD JSON data: {}", - serde_json::to_string_pretty(&parsed_data).unwrap_or_default() + serde_json::to_string_pretty(&sovd_write_data).unwrap_or_default() ); + let component = &self.config.ecu.default_name; + self.sovd_client - .write_data(&self.ecu_name, &sovd_endpoint, parsed_data) + .write_data(component, &sovd_endpoint, sovd_write_data) .await?; let uds_response = vec![ @@ -153,7 +146,7 @@ impl SovdMapper { (did & 0xFF) as u8, ]; - tracing::info!( + info!( "[WDBI] DID 0x{:04X} '{}' -> {} bytes", did, service_name, @@ -162,40 +155,49 @@ impl SovdMapper { Ok(uds_response) } - /// Bypass the live SOVD gateway and return a synthetic [`DataResponse`]. - /// - /// Builds the response JSON entirely from MDD POS-RESPONSE metadata so - /// the full UDS translation pipeline can be exercised without a running - /// SOVD server. Logs the URL that would have been called so the mock - /// path is easy to spot in traces. - /// - /// # Errors - /// Returns an error if no POS-RESPONSE metadata is available for the - /// requested service. async fn mock_read_response( &self, did: u16, service_name: &str, sovd_endpoint: &str, - resolver: &ServiceResolver, + ecu_manager: Option<&ServiceResolver>, ) -> Result { let would_be_url = format!( "{}/vehicle/{}/components/{}/data/{}", - self.gateway_url, self.api_version, self.ecu_name, sovd_endpoint + self.config.sovd.gateway_url, + self.config.sovd.api_version, + self.config.ecu.default_name, + sovd_endpoint ); - tracing::info!( + info!( "[SOVD MOCK] GET {} (intercepted โ€”> generating synthetic response)", would_be_url ); - let meta = resolver - .get_response_metadata(service_name, did) - .await - .map_err(|e| { - SovdError::SchemaMismatch(format!( - "Failed to load POS-RESPONSE metadata for '{service_name}': {e}" - )) - })?; + let mgr = ecu_manager.ok_or_else(|| { + SovdError::SchemaMismatch( + "ECU manager required for mock response generation".to_string(), + ) + })?; + + let meta = match mgr.get_enriched_response_metadata(service_name, did).await { + Ok(m) => m, + Err(e) => { + debug!( + "[SOVD MOCK] Enriched metadata unavailable for '{}': {}. Falling back to \ + basic POS-RESPONSE metadata", + service_name, e + ); + mgr.get_response_parameter_metadata(service_name) + .await + .map_err(|inner| { + SovdError::SchemaMismatch(format!( + "Failed to load POS-RESPONSE metadata for '{service_name}': {e} \ + (fallback: {inner})" + )) + })? + } + }; if meta.is_empty() { return Err(SovdError::SchemaMismatch(format!( @@ -208,7 +210,7 @@ impl SovdMapper { .sovd_client .generate_mock_response_data(sovd_endpoint, &meta, did); - tracing::debug!( + debug!( "[SOVD MOCK] Generated response SOVD JSON data:\n{}", serde_json::to_string_pretty(&data).unwrap_or_default() ); @@ -216,30 +218,26 @@ impl SovdMapper { Ok(DataResponse::new(sovd_endpoint.to_string(), data)) } - /// Convert a SOVD JSON response into raw UDS response bytes. - /// - /// Delegates encoding to [`ResponseEncoder`], which uses MDD POS-RESPONSE - /// parameter metadata to place each field at its correct byte offset. - /// - /// # Errors - /// Returns an error if the MDD encoder cannot produce a valid response - /// for the given service name. async fn sovd_json_to_uds( &self, did: u16, sovd_response: &DataResponse, - resolver: &ServiceResolver, + ecu_manager: Option<&ServiceResolver>, service_name: &str, ) -> Result> { use cda_interfaces::HashMap as CdaHashMap; + let mgr = ecu_manager.ok_or_else(|| { + SovdError::SchemaMismatch("ECU manager required for MDD encoding".to_string()) + })?; + let mut response_data: CdaHashMap = CdaHashMap::default(); for (k, v) in &sovd_response.data { response_data.insert(k.clone(), v.clone()); } - let uds_bytes = resolver + let uds_bytes = mgr .build_response( service_name, service_ids::READ_DATA_BY_IDENTIFIER, @@ -253,10 +251,9 @@ impl SovdMapper { )) })?; - tracing::debug!( + debug!( "[MDD] SOVD JSON -> UDS for '{}': {:02X?}", - service_name, - uds_bytes + service_name, uds_bytes ); Ok(uds_bytes) @@ -271,7 +268,7 @@ mod tests { let config = Config::default(); let sovd_client = SovdClient::new(config.sovd.clone()).expect("failed to create SOVD client"); - SovdMapper::new(&config, sovd_client) + SovdMapper::new(config, sovd_client) } #[test] @@ -283,6 +280,6 @@ mod tests { #[test] fn test_mapper_creation() { let mapper = create_test_mapper(); - assert!(!mapper.ecu_name.is_empty()); + assert!(!mapper.config.sovd.gateway_url.is_empty()); } } diff --git a/proxy-sovd/src/schema.rs b/proxy-sovd/src/schema.rs index 51b0ec9..98d1e2d 100644 --- a/proxy-sovd/src/schema.rs +++ b/proxy-sovd/src/schema.rs @@ -26,10 +26,7 @@ pub struct DataResponse { pub id: String, /// Response data as JSON object. pub data: serde_json::Map, - /// Field-level errors returned by the sovd-server, if any. - /// - /// Parsed from the response but not yet mapped to UDS negative responses. - // TODO(sovd-server): map sovd-server field errors to NRC codes when live gateway is connected. + /// Field-level errors, if any. #[serde(skip_serializing_if = "Vec::is_empty", default)] pub errors: Vec, /// Optional inline schema From 2d65b435ca11f0e1ea71ce877847d7e85d6eac82 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Mon, 27 Apr 2026 11:37:45 +0200 Subject: [PATCH 26/33] refactor: remove async_trait, convert DiagHandler impl to inherent methods --- Cargo.lock | 123 +++++++++++++++++++++++++++++++++ proxy-sovd/src/diag_handler.rs | 46 +++++++++--- 2 files changed, 159 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b749c0c..e11909e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,6 +46,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.102" @@ -324,6 +374,52 @@ dependencies = [ "windows-link", ] +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "const-oid" version = "0.9.6" @@ -1078,6 +1174,12 @@ dependencies = [ "serde", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.14.0" @@ -1311,6 +1413,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "ouroboros" version = "0.18.5" @@ -1575,12 +1683,14 @@ dependencies = [ "cda-database", "cda-interfaces", "cda-plugin-security", + "clap", "serde", "serde_json", "thiserror", "tokio", "toml", "tracing", + "url", ] [[package]] @@ -2223,6 +2333,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.27.2" @@ -2563,6 +2679,7 @@ dependencies = [ "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] @@ -2571,6 +2688,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.23.1" diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 3309c07..1b1b35c 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -12,19 +12,20 @@ use std::{collections::HashMap, sync::Arc}; -use async_trait::async_trait; -use proxy_core::{Config, DiagHandler, ProxyError, Result, ServiceResolver, error::UdsError}; +use proxy_core::{ + Config, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError, +}; use tracing::info; use crate::mapper::SovdMapper; -/// SOVD-backed implementation of [`DiagHandler`]. +/// SOVD-backed diagnostic handler. /// /// Combines MDD-based service resolution ([`ServiceResolver`]) with SOVD /// gateway communication ([`SovdMapper`]) to process UDS diagnostic requests. /// /// Constructed in `proxy-main` and injected into the `DoIP` server as -/// `Arc`. +/// `Arc`. pub struct SovdDiagHandler { /// Shared proxy configuration. config: Arc, @@ -57,14 +58,26 @@ impl SovdDiagHandler { } } -#[async_trait] -impl DiagHandler for SovdDiagHandler { - async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result> { +impl SovdDiagHandler { + /// Process a `ReadDataByIdentifier` (0x22) request. + /// + /// `did` is the extracted 16-bit Data Identifier. + /// `uds_request` is the full UDS request bytes including the SID byte. + /// + /// Returns the complete UDS response bytes (positive or negative). + /// + /// # Errors + /// Returns an error if no MDD database is loaded, the DID is unknown, + /// or the SOVD gateway request fails. + pub async fn handle_read_did(&self, did: u16, uds_request: &[u8]) -> Result> { let mgr = self .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let (service_name, parsed_data) = mgr + let ResolvedService { + name: service_name, + params: parsed_data, + } = mgr .resolve_read_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; @@ -82,12 +95,25 @@ impl DiagHandler for SovdDiagHandler { .await } - async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result> { + /// Process a `WriteDataByIdentifier` (0x2E) request. + /// + /// `did` is the extracted 16-bit Data Identifier. + /// `uds_request` is the full UDS request bytes including the SID byte. + /// + /// Returns the complete UDS response bytes (positive or negative). + /// + /// # Errors + /// Returns an error if no MDD database is loaded, the DID is unknown, + /// or the SOVD gateway request fails. + pub async fn handle_write_did(&self, did: u16, uds_request: &[u8]) -> Result> { let mgr = self .ecu_manager() .ok_or_else(|| ProxyError::Mdd("No MDD database loaded".to_string()))?; - let (service_name, parsed_data) = mgr + let ResolvedService { + name: service_name, + params: parsed_data, + } = mgr .resolve_write_service(did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; From fec38912bb006bbb93b5b33814235be9ac4e94e6 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Fri, 24 Apr 2026 07:48:57 +0200 Subject: [PATCH 27/33] fix: address remaining PR #11 review comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add UdsResponse<'a> wrapper with sid()/is_negative()/nrc() accessors - is_negative_response/get_nrc delegate to UdsResponse โ€” no more raw byte indexing - Add ResolvedService { name, params } struct; replace (String, Map) tuple in resolve_read_service / resolve_write_service return types - Split resolve_service_did into build_did_candidates + match_candidate_did - or_else + match pattern in activate_base_variant (replaces nested if/else) - Add RwLock doc comment explaining write-reservation intent - Remove redundant HashSet alongside Vec in candidate dedup - Add #[cfg(test)] modules to resolve.rs, metadata.rs, response.rs (6 + 9 + 12 new unit tests; 63 total in proxy-core) --- proxy-core/src/service_resolver/metadata.rs | 193 ++++++++++++++++++++ 1 file changed, 193 insertions(+) diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs index 9aeefdb..2f99179 100644 --- a/proxy-core/src/service_resolver/metadata.rs +++ b/proxy-core/src/service_resolver/metadata.rs @@ -426,3 +426,196 @@ mod tests { assert!(!is_opaque); } } + +#[cfg(test)] +mod tests { + use cda_interfaces::{ParameterTypeMetadata, ResponseParameterInfo}; + + use super::super::uds_helpers::{find_mux_case_prefix, has_mux_case_for_did_exact}; + + /// Build a minimal `ResponseParameterInfo` MUX-case entry for test fixtures. + fn mux_case(name: &str, coded_lower: u64) -> ResponseParameterInfo { + ResponseParameterInfo { + name: format!("__mux_case__/{name}"), + semantic: None, + param_type: ParameterTypeMetadata::CodedConst { + coded_value: coded_lower.to_string(), + }, + byte_position: 0, + bit_position: 0, + byte_size: None, + } + } + + /// Build a plain VALUE parameter at a given byte position. + fn value_param(name: &str, pos: u32, size: u32) -> ResponseParameterInfo { + ResponseParameterInfo { + name: name.to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: pos, + bit_position: 0, + byte_size: Some(size), + } + } + + // โ”€โ”€ has_mux_case_for_did_exact โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + #[test] + fn test_has_mux_exact_match() { + let meta = vec![mux_case("VIN", 0xF190)]; + assert!(has_mux_case_for_did_exact(&meta, 0xF190)); + } + + #[test] + fn test_has_mux_exact_no_match() { + let meta = vec![mux_case("VIN", 0xF190)]; + // 0xF191 is one beyond the only entry โ€” no match. + assert!(!has_mux_case_for_did_exact(&meta, 0xF191)); + } + + #[test] + fn test_has_mux_exact_vs_floor_semantics() { + // Floor matching (find_mux_case_prefix) would return the 0xF100 case for + // 0xF103, but has_mux_case_for_did_exact must NOT. + let meta = vec![mux_case("RANGE", 0xF100)]; + assert!(!has_mux_case_for_did_exact(&meta, 0xF103)); + // Only the exact value matches. + assert!(has_mux_case_for_did_exact(&meta, 0xF100)); + } + + #[test] + fn test_has_mux_exact_empty_meta() { + assert!(!has_mux_case_for_did_exact(&[], 0xF190)); + } + + #[test] + fn test_has_mux_exact_non_mux_params_ignored() { + let meta = vec![value_param("DATA", 3, 17)]; + assert!(!has_mux_case_for_did_exact(&meta, 0x0000)); + } + + // โ”€โ”€ find_mux_case_prefix (floor) vs has_mux_case_for_did_exact โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + #[test] + fn test_floor_vs_exact_differ_for_range_case() { + let meta = vec![mux_case("RANGE", 0xF100), mux_case("OTHER", 0xF200)]; + // Floor: 0xF103 falls in the 0xF100 range โ†’ prefix returned. + assert_eq!( + find_mux_case_prefix(&meta, 0xF103), + Some("RANGE/".to_string()) + ); + // Exact: 0xF103 has no exact entry โ†’ false. + assert!(!has_mux_case_for_did_exact(&meta, 0xF103)); + // But 0xF100 itself is an exact hit. + assert!(has_mux_case_for_did_exact(&meta, 0xF100)); + } + + // โ”€โ”€ opaque-response heuristic โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + // The heuristic inside `get_enriched_response_metadata_with_source` checks: + // is_opaque = data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/') + // We test the data-model conditions that drive it directly. + + #[test] + fn test_opaque_heuristic_single_none_size_param() { + // Only one VALUE param with byte_size = None and no '/' in name โ†’ opaque. + let param = ResponseParameterInfo { + name: "STRUCTURE_DATA".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }; + let data_params: Vec<_> = std::slice::from_ref(¶m) + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(is_opaque); + } + + #[test] + fn test_opaque_heuristic_sized_param_not_opaque() { + // A VALUE param WITH a byte_size is NOT opaque (it has a known layout). + let param = value_param("DATA", 3, 17); + let data_params: Vec<_> = std::slice::from_ref(¶m) + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(!is_opaque); + } + + #[test] + fn test_opaque_heuristic_mux_subparam_not_opaque() { + // A MUX sub-param has '/' in its name โ†’ not opaque even if byte_size is None. + let param = ResponseParameterInfo { + name: "__mux_case__/VIN/DATA".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::Value { + physical_default_value: None, + coded_default_value: None, + compu_scales: vec![], + }, + byte_position: 3, + bit_position: 0, + byte_size: None, + }; + let data_params: Vec<_> = std::slice::from_ref(¶m) + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(!is_opaque); + } + + #[test] + fn test_opaque_heuristic_multiple_params_not_opaque() { + // Multiple VALUE params โ†’ structured layout, NOT opaque. + let params = vec![value_param("FIELD_A", 3, 2), value_param("FIELD_B", 5, 1)]; + let data_params: Vec<_> = params + .iter() + .filter(|p| { + matches!( + p.param_type, + ParameterTypeMetadata::Value { .. } | ParameterTypeMetadata::PhysConst { .. } + ) + }) + .collect(); + let first = data_params.first().unwrap(); + let is_opaque = + data_params.len() == 1 && first.byte_size.is_none() && !first.name.contains('/'); + assert!(!is_opaque); + } +} From 94e1f4f0390da7b65249dd88dedd3472f7e9348d Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Wed, 22 Apr 2026 10:15:11 +0200 Subject: [PATCH 28/33] =?UTF-8?q?feat:=20add=20proxy-doip=20crate=20?= =?UTF-8?q?=E2=80=94=20DoIP=20transport=20layer=20(temporary,=20RDBI/WDBI?= =?UTF-8?q?=20only)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Arvind Rathod --- Cargo.lock | 11 + Cargo.toml | 1 + proxy-doip/Cargo.toml | 28 +++ proxy-doip/src/handler.rs | 511 ++++++++++++++++++++++++++++++++++++++ proxy-doip/src/lib.rs | 26 ++ proxy-doip/src/message.rs | 377 ++++++++++++++++++++++++++++ proxy-doip/src/server.rs | 132 ++++++++++ proxy-doip/src/session.rs | 101 ++++++++ 8 files changed, 1187 insertions(+) create mode 100644 proxy-doip/Cargo.toml create mode 100644 proxy-doip/src/handler.rs create mode 100644 proxy-doip/src/lib.rs create mode 100644 proxy-doip/src/message.rs create mode 100644 proxy-doip/src/server.rs create mode 100644 proxy-doip/src/session.rs diff --git a/Cargo.lock b/Cargo.lock index e11909e..3f29edf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1693,6 +1693,17 @@ dependencies = [ "url", ] +[[package]] +name = "proxy-doip" +version = "0.1.0" +dependencies = [ + "bytes", + "cda-interfaces", + "proxy-core", + "tokio", + "tracing", +] + [[package]] name = "proxy-sovd" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index df5fdcf..a9bea59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ resolver = "3" members = [ "proxy-core", "proxy-sovd", + "proxy-doip", ] [workspace.dependencies] diff --git a/proxy-doip/Cargo.toml b/proxy-doip/Cargo.toml new file mode 100644 index 0000000..6bdf209 --- /dev/null +++ b/proxy-doip/Cargo.toml @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License Version 2.0 which is available at +# https://www.apache.org/licenses/LICENSE-2.0 + +[package] +name = "proxy-doip" +version.workspace = true +edition.workspace = true +publish = false +description = "DoIP transport layer (ISO 13400-2) for the UDS2SOVD proxy" +homepage.workspace = true +license.workspace = true + +[dependencies] +proxy-core = { workspace = true } +cda-interfaces = { workspace = true } +tokio = { workspace = true, features = ["full"] } +tracing = { workspace = true } +bytes = { workspace = true } + +[lints] +workspace = true diff --git a/proxy-doip/src/handler.rs b/proxy-doip/src/handler.rs new file mode 100644 index 0000000..33d9d0d --- /dev/null +++ b/proxy-doip/src/handler.rs @@ -0,0 +1,511 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use std::sync::Arc; + +use cda_interfaces::service_ids; +use proxy_core::{ + Config, DiagHandler, Result, + error::{Nrc, UdsError}, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, +}; +use tracing::{debug, error, info, warn}; + +use crate::{ + message::{ + DOIP_HEADER_SIZE, DOIP_PROTOCOL_VERSION, DiagnosticMessage, DoIpMessage, PayloadType, + RoutingActivationRequest, + }, + session::Session, +}; + +/// ISO 13400 routing activation response code: success. +const ROUTING_ACTIVATION_SUCCESS: u8 = 0x10; + +/// Socket read chunk size used for each `read` call. +const READ_BUFFER_SIZE: usize = 4096; + +/// Maximum buffered bytes retained while waiting for complete `DoIP` frames. +const MAX_STAGED_BUFFER_BYTES: usize = 65_536; + +/// Maximum parsed frames per read cycle to keep scheduling fair. +const MAX_FRAMES_PER_READ: usize = 128; + +/// Read service minimum length: SID (1 byte) + DID (2 bytes) = 3 bytes. +const MIN_READ_SERVICE_LENGTH: usize = 3; + +/// Minimum data bytes for a `WriteDataByIdentifier` request (DID hi + DID lo + 1 data byte). +const MIN_WDBI_DATA_LENGTH: usize = 3; + +/// Minimum data bytes for a `ReadDataByIdentifier` request: DID high byte + DID low byte. +const MIN_RDBI_DATA_LENGTH: usize = 2; + +/// Placeholder service ID used in a negative response when UDS message parsing fails. +const UNKNOWN_SERVICE_ID: u8 = 0x00; + +/// Parsed UDS message consisting of a service identifier and data bytes. +#[derive(Debug, Clone)] +struct UdsMessage { + /// UDS Service Identifier (SID), e.g. 0x22 for `ReadDataByIdentifier`. + service_id: u8, + /// Remaining bytes after the SID (sub-function, DID, data, etc.). + data: Vec, +} + +impl UdsMessage { + /// Parse a UDS message from raw bytes. + /// + /// The first byte is interpreted as the SID; the rest becomes `data`. + /// + /// # Errors + /// Returns an error if the byte slice is empty. + fn from_bytes(bytes: &[u8]) -> Result { + let &first = bytes.first().ok_or(UdsError::InvalidLength { + expected: 1, + actual: 0, + })?; + + Ok(Self { + service_id: first, + data: bytes.get(1..).unwrap_or_default().to_vec(), + }) + } + + /// Build a UDS negative response: `[0x7F, SID, NRC]`. + #[must_use] + fn build_negative_response(&self, nrc: Nrc) -> Vec { + vec![service_ids::NEGATIVE_RESPONSE, self.service_id, nrc as u8] + } + + /// Extract a 16-bit DID from the first two data bytes. + fn extract_did(&self) -> Option { + let &hi = self.data.first()?; + let &lo = self.data.get(1)?; + Some(u16::from_be_bytes([hi, lo])) + } +} + +/// Returns `true` when a full header is present but protocol bytes are invalid. +fn has_invalid_doip_header(buffer: &[u8]) -> bool { + if buffer.len() < DOIP_HEADER_SIZE { + return false; + } + + let Some(&version) = buffer.first() else { + return false; + }; + let Some(&inverse) = buffer.get(1) else { + return false; + }; + + version != DOIP_PROTOCOL_VERSION || inverse != !version +} + +/// Handles a single `DoIP` TCP connection. +/// +/// Reads incoming `DoIP` frames, dispatches UDS requests to the +/// [`DiagHandler`] backend, and sends the encoded response back. +pub struct ConnectionHandler { + /// Shared proxy configuration. + config: Arc, + /// Backend handler for UDS request processing. + diag_handler: Arc, + /// Active TCP stream for this connection. + stream: TcpStream, + /// Routing activation session state. + session: Session, + /// Accumulation buffer for partial `DoIP` frames. + buffer: Vec, +} + +impl ConnectionHandler { + /// Create a new connection handler. + pub fn new(config: Arc, diag_handler: Arc, stream: TcpStream) -> Self { + Self { + config, + diag_handler, + stream, + session: Session::new(), + buffer: Vec::with_capacity(READ_BUFFER_SIZE), + } + } + + /// Run the connection handler loop until the client disconnects or an error occurs. + /// + /// # Errors + /// Returns an error if the connection encounters an I/O error. + pub async fn handle(mut self) -> Result<()> { + let peer_addr = self.stream.peer_addr()?; + info!("New connection from {}", peer_addr); + + let mut read_buf = vec![0u8; READ_BUFFER_SIZE]; + + loop { + match self.stream.read(&mut read_buf).await { + Ok(0) => { + info!("Client {} disconnected", peer_addr); + break; + } + Ok(n) => { + debug!("Received {} bytes from {}", n, peer_addr); + self.buffer + .extend_from_slice(read_buf.get(..n).unwrap_or_default()); + + let mut parsed_frames = 0usize; + while parsed_frames < MAX_FRAMES_PER_READ { + if let Some(msg) = DoIpMessage::from_bytes(&self.buffer) { + let msg_size = DOIP_HEADER_SIZE.saturating_add(msg.payload.len()); + if msg_size > self.buffer.len() { + warn!( + "Parsed message length {} exceeds buffered bytes {}, clearing", + msg_size, + self.buffer.len(), + ); + self.buffer.clear(); + break; + } + + if let Err(e) = self.process_message(&msg).await { + error!("Error processing message from {}: {}", peer_addr, e); + return Err(e); + } + + self.buffer.drain(..msg_size); + parsed_frames = parsed_frames.saturating_add(1); + continue; + } + + if has_invalid_doip_header(&self.buffer) { + warn!( + "Invalid DoIP header from {}, discarding one byte to re-sync", + peer_addr, + ); + self.buffer.drain(..1); + continue; + } + + break; + } + + if parsed_frames == MAX_FRAMES_PER_READ { + warn!( + "Reached frame processing cap ({}) for {}, remaining buffered={} bytes", + MAX_FRAMES_PER_READ, + peer_addr, + self.buffer.len(), + ); + } + + if self.buffer.len() > MAX_STAGED_BUFFER_BYTES { + warn!("Buffer too large ({} bytes), clearing", self.buffer.len()); + self.buffer.clear(); + } + } + Err(e) => { + error!("Error reading from client {}: {}", peer_addr, e); + break; + } + } + } + + Ok(()) + } + + async fn process_message(&mut self, msg: &DoIpMessage) -> Result<()> { + let payload_type = msg.payload_type_enum(); + debug!( + "Received DoIP message: {:?}, payload_len={}", + payload_type, + msg.payload.len(), + ); + + match payload_type { + Some(PayloadType::RoutingActivationRequest) => { + self.handle_routing_activation(msg).await + } + Some(PayloadType::DiagnosticMessage) => self.handle_diagnostic_message(msg).await, + // TODO(doip): Handle VehicleIdentificationRequest (0x0001..0x0003) + // by responding with a VehicleAnnouncementIdentificationResponse + // (0x0004) containing VIN, logical address, EID, and GID from config. + // TODO(doip): Handle AliveCheckRequest (0x0007) by responding with + // AliveCheckResponse (0x0008) containing our source address. + _ => { + debug!("Unsupported payload type: {:?}", payload_type); + Ok(()) + } + } + } + + async fn handle_routing_activation(&mut self, msg: &DoIpMessage) -> Result<()> { + let Some(req) = RoutingActivationRequest::from_payload(&msg.payload) else { + warn!("Invalid routing activation request"); + return Ok(()); + }; + + self.session.activate(req.source_address); + + let mut payload = Vec::new(); + payload.extend_from_slice(&req.source_address.to_be_bytes()); + payload.extend_from_slice(&self.config.ecu.logical_address.to_be_bytes()); + payload.push(ROUTING_ACTIVATION_SUCCESS); + + let response = DoIpMessage::new(PayloadType::RoutingActivationResponse, payload); + self.send_message(&response).await?; + + info!( + "Routing activated for source address 0x{:04X}", + req.source_address + ); + Ok(()) + } + + async fn handle_diagnostic_message(&mut self, msg: &DoIpMessage) -> Result<()> { + if !self.session.is_activated() { + warn!("Received diagnostic message before routing activation"); + return Ok(()); + } + + let Some(diag_msg) = DiagnosticMessage::from_payload(&msg.payload) else { + warn!("Invalid diagnostic message"); + return Ok(()); + }; + + debug!( + "Diagnostic message: SA=0x{:04X}, TA=0x{:04X}, {} bytes", + diag_msg.source_address, + diag_msg.target_address, + diag_msg.user_data.len() + ); + + let expected_target = self.config.ecu.logical_address; + if diag_msg.target_address != expected_target { + warn!( + "Ignoring diagnostic message for unexpected target address 0x{:04X} (expected \ + 0x{:04X})", + diag_msg.target_address, expected_target, + ); + return Ok(()); + } + + if !self.session.is_activated_for(diag_msg.source_address) { + warn!( + "Ignoring diagnostic message from non-activated source 0x{:04X}", + diag_msg.source_address, + ); + return Ok(()); + } + + let uds_response = self.process_uds_request(&diag_msg.user_data).await; + if uds_response.is_empty() { + debug!( + "UDS response suppressed for source 0x{:04X}", + diag_msg.source_address + ); + return Ok(()); + } + + let response_payload = DiagnosticMessage::build_payload( + self.config.server.source_address, + diag_msg.source_address, + &uds_response, + ); + + let response = DoIpMessage::new(PayloadType::DiagnosticMessage, response_payload); + self.send_message(&response).await?; + + Ok(()) + } + + async fn process_uds_request(&self, uds_data: &[u8]) -> Vec { + // All supported services require at least SID (1) + DID high (1) + DID low (1). + if uds_data.len() < MIN_READ_SERVICE_LENGTH { + error!( + "UDS request too short: {} byte(s), minimum is {}", + uds_data.len(), + MIN_READ_SERVICE_LENGTH, + ); + return vec![ + service_ids::NEGATIVE_RESPONSE, + UNKNOWN_SERVICE_ID, + Nrc::IncorrectMessageLengthOrInvalidFormat as u8, + ]; + } + + if let Some(&service_id) = uds_data.first() { + info!( + "UDS request SID=0x{:02X}, payload_len={} bytes", + service_id, + uds_data.len(), + ); + } else { + info!("UDS request with empty payload"); + } + debug!("UDS request payload: {:02X?}", uds_data); + + let uds_msg = match UdsMessage::from_bytes(uds_data) { + Ok(msg) => msg, + Err(e) => { + error!("Failed to parse UDS message: {}", e); + return vec![ + service_ids::NEGATIVE_RESPONSE, + UNKNOWN_SERVICE_ID, + Nrc::IncorrectMessageLengthOrInvalidFormat as u8, + ]; + } + }; + + match uds_msg.service_id { + service_ids::READ_DATA_BY_IDENTIFIER => { + self.process_read_data_by_identifier(&uds_msg).await + } + service_ids::WRITE_DATA_BY_IDENTIFIER => { + self.process_write_data_by_identifier(&uds_msg).await + } + // TODO(uds): Add DiagnosticSessionControl (0x10) and + // TesterPresent (0x3E) handling โ€” both are required for + // compliant UDS communication. TesterPresent should respond + // with a positive response; session control should forward to + // the SOVD gateway modes API. + _ => { + info!("Unsupported service: 0x{:02X}", uds_msg.service_id); + uds_msg.build_negative_response(Nrc::ServiceNotSupported) + } + } + } + + async fn process_write_data_by_identifier(&self, uds_msg: &UdsMessage) -> Vec { + if uds_msg.data.len() < MIN_WDBI_DATA_LENGTH { + error!("Invalid write request - missing DID or data"); + return uds_msg.build_negative_response(Nrc::IncorrectMessageLengthOrInvalidFormat); + } + + let Some(did_value) = uds_msg.extract_did() else { + return uds_msg.build_negative_response(Nrc::IncorrectMessageLengthOrInvalidFormat); + }; + + let uds_request = { + let mut req = vec![service_ids::WRITE_DATA_BY_IDENTIFIER]; + req.extend_from_slice(&uds_msg.data); + req + }; + + match self + .diag_handler + .handle_write_did(did_value, &uds_request) + .await + { + Ok(uds_response) => uds_response, + Err(e) => { + error!("[UDS2SOVD] Write flow failed: {}", e); + uds_msg.build_negative_response(Nrc::GeneralProgrammingFailure) + } + } + } + + async fn process_read_data_by_identifier(&self, uds_msg: &UdsMessage) -> Vec { + if uds_msg.data.len() < MIN_RDBI_DATA_LENGTH { + error!("Invalid read request - missing DID"); + return uds_msg.build_negative_response(Nrc::IncorrectMessageLengthOrInvalidFormat); + } + + let Some(did_value) = uds_msg.extract_did() else { + return uds_msg.build_negative_response(Nrc::IncorrectMessageLengthOrInvalidFormat); + }; + + let uds_request = { + let mut req = vec![service_ids::READ_DATA_BY_IDENTIFIER]; + req.extend_from_slice(uds_msg.data.get(..MIN_RDBI_DATA_LENGTH).unwrap_or_default()); + req + }; + + match self + .diag_handler + .handle_read_did(did_value, &uds_request) + .await + { + Ok(uds_response) => uds_response, + Err(e) => { + error!("[UDS2SOVD] Read flow failed: {}", e); + uds_msg.build_negative_response(Nrc::RequestOutOfRange) + } + } + } + + async fn send_message(&mut self, msg: &DoIpMessage) -> Result<()> { + let bytes = msg.to_bytes(); + self.stream.write_all(&bytes).await?; + self.stream.flush().await?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_uds_message() { + let bytes = vec![service_ids::READ_DATA_BY_IDENTIFIER, 0xF1, 0x90]; + let msg = UdsMessage::from_bytes(&bytes).expect("failed to parse valid UDS message"); + assert_eq!(msg.service_id, service_ids::READ_DATA_BY_IDENTIFIER); + assert_eq!(msg.data, vec![0xF1, 0x90]); + } + + #[test] + fn test_negative_response() { + let msg = UdsMessage { + service_id: service_ids::READ_DATA_BY_IDENTIFIER, + data: vec![], + }; + let response = msg.build_negative_response(Nrc::RequestOutOfRange); + assert_eq!(response, vec![0x7F, 0x22, 0x31]); + } + + #[test] + fn test_parse_empty_message() { + assert!(UdsMessage::from_bytes(&[]).is_err()); + } + + #[test] + fn test_unknown_service_kept_for_dispatch() { + let msg = UdsMessage::from_bytes(&[0xFF]).expect("failed to parse single-byte UDS message"); + assert_eq!(msg.service_id, 0xFF); + assert!(msg.data.is_empty()); + } + + #[test] + fn test_write_service_negative_response() { + let msg = UdsMessage { + service_id: service_ids::WRITE_DATA_BY_IDENTIFIER, + data: vec![], + }; + let response = msg.build_negative_response(Nrc::IncorrectMessageLengthOrInvalidFormat); + assert_eq!(response, vec![0x7F, 0x2E, 0x13]); + } + + #[test] + fn test_invalid_doip_header_detection() { + let mut raw = vec![0x03, 0xFC, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00]; + assert!(has_invalid_doip_header(&raw)); + + if let Some(version) = raw.get_mut(0) { + *version = DOIP_PROTOCOL_VERSION; + } + if let Some(inverse) = raw.get_mut(1) { + *inverse = !DOIP_PROTOCOL_VERSION; + } + assert!(!has_invalid_doip_header(&raw)); + } +} diff --git a/proxy-doip/src/lib.rs b/proxy-doip/src/lib.rs new file mode 100644 index 0000000..a8e4ce8 --- /dev/null +++ b/proxy-doip/src/lib.rs @@ -0,0 +1,26 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +//! `DoIP` transport layer for the UDS-to-SOVD proxy. +//! +//! Provides a TCP server that accepts ISO 13400-2 `DoIP` connections, +//! dispatches UDS diagnostic requests to a backend handler, and returns +//! the encoded response. + +pub mod handler; +pub mod message; +pub mod server; +pub mod session; + +pub use handler::ConnectionHandler; +pub use message::DoIpMessage; +pub use server::DoIpServer; diff --git a/proxy-doip/src/message.rs b/proxy-doip/src/message.rs new file mode 100644 index 0000000..fa9cdcd --- /dev/null +++ b/proxy-doip/src/message.rs @@ -0,0 +1,377 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use bytes::{BufMut, BytesMut}; + +/// `DoIP` protocol version per ISO 13400-2. +pub const DOIP_PROTOCOL_VERSION: u8 = 0x02; + +/// `DoIP` header size in bytes: version (1) + inverse (1) + type (2) + length (4). +pub const DOIP_HEADER_SIZE: usize = 8; + +/// Minimum routing activation request payload: source address (2) + type (1) + reserved (4). +const ROUTING_ACTIVATION_REQUEST_MIN_LEN: usize = 7; + +/// Diagnostic message header size: source address (2) + target address (2). +pub const DIAGNOSTIC_MESSAGE_HEADER_SIZE: usize = 4; + +/// `DoIP` payload types defined in ISO 13400-2. +/// +/// Each variant carries the 16-bit payload type code used on the wire. +#[repr(u16)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PayloadType { + /// Generic `DoIP` header negative acknowledge + GenericHeaderNack = 0x0000, + /// Vehicle identification request + VehicleIdentificationRequest = 0x0001, + /// Vehicle identification request with EID + VehicleIdentificationRequestWithEid = 0x0002, + /// Vehicle identification request with VIN + VehicleIdentificationRequestWithVin = 0x0003, + /// Vehicle announcement/identification response + VehicleAnnouncementIdentificationResponse = 0x0004, + /// Routing activation request + RoutingActivationRequest = 0x0005, + /// Routing activation response + RoutingActivationResponse = 0x0006, + /// Alive check request + AliveCheckRequest = 0x0007, + /// Alive check response + AliveCheckResponse = 0x0008, + /// Diagnostic message + DiagnosticMessage = 0x8001, + /// Diagnostic message positive acknowledgement + DiagnosticMessagePositiveAck = 0x8002, + /// Diagnostic message negative acknowledgement + DiagnosticMessageNegativeAck = 0x8003, +} + +impl PayloadType { + /// Convert a raw `u16` wire value to a [`PayloadType`]. + /// + /// Returns `None` for unknown payload type codes. + #[must_use] + pub fn from_u16(value: u16) -> Option { + match value { + 0x0000 => Some(Self::GenericHeaderNack), + 0x0001 => Some(Self::VehicleIdentificationRequest), + 0x0002 => Some(Self::VehicleIdentificationRequestWithEid), + 0x0003 => Some(Self::VehicleIdentificationRequestWithVin), + 0x0004 => Some(Self::VehicleAnnouncementIdentificationResponse), + 0x0005 => Some(Self::RoutingActivationRequest), + 0x0006 => Some(Self::RoutingActivationResponse), + 0x0007 => Some(Self::AliveCheckRequest), + 0x0008 => Some(Self::AliveCheckResponse), + 0x8001 => Some(Self::DiagnosticMessage), + 0x8002 => Some(Self::DiagnosticMessagePositiveAck), + 0x8003 => Some(Self::DiagnosticMessageNegativeAck), + _ => None, + } + } +} + +/// `DoIP` message consisting of a header and variable-length payload. +/// +/// The header contains the protocol version, inverse version byte, +/// 16-bit payload type, and 32-bit payload length per ISO 13400-2. +#[derive(Debug, Clone)] +pub struct DoIpMessage { + /// Protocol version byte (typically [`DOIP_PROTOCOL_VERSION`]). + pub protocol_version: u8, + /// Raw 16-bit payload type code. + pub payload_type: u16, + /// Variable-length payload bytes. + pub payload: Vec, +} + +impl DoIpMessage { + /// Create a new `DoIP` message with the given payload type and data. + #[must_use] + pub fn new(payload_type: PayloadType, payload: Vec) -> Self { + Self { + protocol_version: DOIP_PROTOCOL_VERSION, + payload_type: payload_type as u16, + payload, + } + } + + /// Parse a `DoIP` message from a byte buffer. + /// + /// Returns `None` if the buffer is too short, the protocol version is invalid, + /// or the declared payload length exceeds the available data. + #[must_use] + pub fn from_bytes(data: &[u8]) -> Option { + if data.len() < DOIP_HEADER_SIZE { + return None; + } + + let protocol_version = *data.first()?; + let inverse_protocol_version = *data.get(1)?; + + // Verify protocol version per ISO 13400-2 + if protocol_version != DOIP_PROTOCOL_VERSION { + return None; + } + if inverse_protocol_version != !protocol_version { + return None; + } + + let pt_bytes: [u8; 2] = data.get(2..4)?.try_into().ok()?; + let payload_type = u16::from_be_bytes(pt_bytes); + + let pl_bytes: [u8; 4] = data.get(4..8)?.try_into().ok()?; + let payload_length = u32::from_be_bytes(pl_bytes) as usize; + + let end = DOIP_HEADER_SIZE.checked_add(payload_length)?; + let payload = data.get(DOIP_HEADER_SIZE..end)?.to_vec(); + + Some(Self { + protocol_version, + payload_type, + payload, + }) + } + + /// Serialize this message to wire-format bytes. + #[must_use] + #[allow(clippy::cast_possible_truncation)] + pub fn to_bytes(&self) -> Vec { + let mut buf = BytesMut::with_capacity(DOIP_HEADER_SIZE.saturating_add(self.payload.len())); + + buf.put_u8(self.protocol_version); + buf.put_u8(!self.protocol_version); + buf.put_u16(self.payload_type); + buf.put_u32(self.payload.len() as u32); + buf.put_slice(&self.payload); + + buf.to_vec() + } + + /// Get the typed [`PayloadType`] enum for this message. + #[must_use] + pub fn payload_type_enum(&self) -> Option { + PayloadType::from_u16(self.payload_type) + } +} + +/// Parsed routing activation request (ISO 13400-2 Table 18). +#[derive(Debug)] +pub struct RoutingActivationRequest { + /// Source address of the external test equipment. + pub source_address: u16, + /// Routing activation type (default / diagnostic / central security). + pub activation_type: u8, + /// Reserved bytes specified by ISO (OEM-specific use). + /// TODO(doip): Use for OEM-specific routing activation handling. + #[allow(dead_code)] + pub reserved: u32, +} + +impl RoutingActivationRequest { + /// Parse a routing activation request from a `DoIP` payload. + /// + /// Returns `None` if the payload is shorter than the minimum 7 bytes. + #[must_use] + pub fn from_payload(payload: &[u8]) -> Option { + if payload.len() < ROUTING_ACTIVATION_REQUEST_MIN_LEN { + return None; + } + + let sa: [u8; 2] = payload.get(0..2)?.try_into().ok()?; + let source_address = u16::from_be_bytes(sa); + let activation_type = *payload.get(2)?; + let res: [u8; 4] = payload.get(3..7)?.try_into().ok()?; + let reserved = u32::from_be_bytes(res); + + Some(Self { + source_address, + activation_type, + reserved, + }) + } +} + +/// Parsed diagnostic message (ISO 13400-2 Table 21). +#[derive(Debug)] +pub struct DiagnosticMessage { + /// Source address of the sending entity. + pub source_address: u16, + /// Target address of the receiving entity. + pub target_address: u16, + /// UDS user data (service bytes). + pub user_data: Vec, +} + +impl DiagnosticMessage { + /// Parse a diagnostic message from a `DoIP` payload. + /// + /// Returns `None` if the payload is shorter than the minimum 4 bytes. + #[must_use] + pub fn from_payload(payload: &[u8]) -> Option { + if payload.len() < DIAGNOSTIC_MESSAGE_HEADER_SIZE { + return None; + } + + let sa: [u8; 2] = payload.get(0..2)?.try_into().ok()?; + let source_address = u16::from_be_bytes(sa); + let ta: [u8; 2] = payload.get(2..4)?.try_into().ok()?; + let target_address = u16::from_be_bytes(ta); + let user_data = payload.get(4..).unwrap_or_default().to_vec(); + + Some(Self { + source_address, + target_address, + user_data, + }) + } + + /// Build a raw diagnostic message payload from addresses and UDS data. + #[must_use] + pub fn build_payload(source_address: u16, target_address: u16, user_data: &[u8]) -> Vec { + let mut payload = + Vec::with_capacity(DIAGNOSTIC_MESSAGE_HEADER_SIZE.saturating_add(user_data.len())); + payload.extend_from_slice(&source_address.to_be_bytes()); + payload.extend_from_slice(&target_address.to_be_bytes()); + payload.extend_from_slice(user_data); + payload + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_doip_message_serialize() { + let msg = DoIpMessage::new(PayloadType::DiagnosticMessage, vec![0x01, 0x02, 0x03]); + let bytes = msg.to_bytes(); + + let (&b0, &b1) = (bytes.first().expect("b0"), bytes.get(1).expect("b1")); + let pt: [u8; 2] = bytes.get(2..4).expect("pt").try_into().expect("2b"); + let len_field: [u8; 4] = bytes.get(4..8).expect("len").try_into().expect("4b"); + let rest = bytes.get(8..).expect("rest"); + assert_eq!(b0, DOIP_PROTOCOL_VERSION); + assert_eq!(b1, !DOIP_PROTOCOL_VERSION); + assert_eq!(u16::from_be_bytes(pt), 0x8001); + assert_eq!(u32::from_be_bytes(len_field), 3); + assert_eq!(rest, &[0x01, 0x02, 0x03]); + } + + #[test] + fn test_doip_message_deserialize() { + let bytes = vec![ + 0x02, 0xFD, // Version and inverse + 0x80, 0x01, // Payload type (DiagnosticMessage) + 0x00, 0x00, 0x00, 0x03, // Payload length + 0x01, 0x02, 0x03, // Payload + ]; + + let msg = DoIpMessage::from_bytes(&bytes).expect("failed to parse valid DoIP message"); + assert_eq!(msg.protocol_version, 0x02); + assert_eq!(msg.payload_type, 0x8001); + assert_eq!(msg.payload, vec![0x01, 0x02, 0x03]); + } + + #[test] + fn test_diagnostic_message_parser() { + let payload = vec![ + 0x0E, 0x80, // Source address + 0x00, 0x01, // Target address + 0x22, 0xF1, 0x90, // UDS data + ]; + + let diag_msg = DiagnosticMessage::from_payload(&payload) + .expect("failed to parse valid diagnostic message"); + assert_eq!(diag_msg.source_address, 0x0E80); + assert_eq!(diag_msg.target_address, 0x0001); + assert_eq!(diag_msg.user_data, vec![0x22, 0xF1, 0x90]); + } + + #[test] + fn test_routing_activation_request() { + let payload = vec![ + 0x0E, 0x80, // Source address + 0x00, // Activation type + 0x00, 0x00, 0x00, 0x00, // Reserved + ]; + + let req = RoutingActivationRequest::from_payload(&payload) + .expect("failed to parse valid routing activation request"); + assert_eq!(req.source_address, 0x0E80); + assert_eq!(req.activation_type, 0x00); + } + + #[test] + fn test_doip_message_roundtrip() { + let original = DoIpMessage::new( + PayloadType::RoutingActivationRequest, + vec![0x0E, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00], + ); + let bytes = original.to_bytes(); + let parsed = + DoIpMessage::from_bytes(&bytes).expect("failed to parse roundtrip DoIP message"); + assert_eq!(parsed.protocol_version, original.protocol_version); + assert_eq!(parsed.payload_type, original.payload_type); + assert_eq!(parsed.payload, original.payload); + } + + #[test] + fn test_doip_message_too_short() { + assert!(DoIpMessage::from_bytes(&[0x02, 0xFD]).is_none()); + assert!(DoIpMessage::from_bytes(&[]).is_none()); + } + + #[test] + fn test_doip_message_invalid_version() { + let bytes = vec![0x03, 0xFC, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00]; + assert!(DoIpMessage::from_bytes(&bytes).is_none()); + } + + #[test] + fn test_doip_message_incomplete_payload() { + let bytes = vec![ + 0x02, 0xFD, 0x80, 0x01, 0x00, 0x00, 0x00, 0x05, // Says 5 bytes but only 2 follow + 0x01, 0x02, + ]; + assert!(DoIpMessage::from_bytes(&bytes).is_none()); + } + + #[test] + fn test_payload_type_from_u16() { + assert_eq!( + PayloadType::from_u16(0x0005), + Some(PayloadType::RoutingActivationRequest) + ); + assert_eq!( + PayloadType::from_u16(0x8001), + Some(PayloadType::DiagnosticMessage) + ); + assert_eq!(PayloadType::from_u16(0xFFFF), None); + } + + #[test] + fn test_diagnostic_message_build_payload() { + let payload = DiagnosticMessage::build_payload(0x0E80, 0x1000, &[0x22, 0xF1, 0x90]); + assert_eq!(payload, vec![0x0E, 0x80, 0x10, 0x00, 0x22, 0xF1, 0x90]); + } + + #[test] + fn test_diagnostic_message_too_short() { + assert!(DiagnosticMessage::from_payload(&[0x0E, 0x80]).is_none()); + } + + #[test] + fn test_routing_activation_too_short() { + assert!(RoutingActivationRequest::from_payload(&[0x0E, 0x80]).is_none()); + } +} diff --git a/proxy-doip/src/server.rs b/proxy-doip/src/server.rs new file mode 100644 index 0000000..8a2b751 --- /dev/null +++ b/proxy-doip/src/server.rs @@ -0,0 +1,132 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +use proxy_core::{Config, DiagHandler, Result}; +use tokio::net::TcpListener; +use tracing::{error, info, warn}; + +use crate::handler::ConnectionHandler; + +/// `DoIP` TCP server that accepts connections and spawns per-connection handlers. +/// +/// Each incoming TCP connection is handled by a [`ConnectionHandler`] that +/// reads `DoIP` frames, dispatches UDS requests to the injected +/// [`DiagHandler`], and returns the encoded response. +/// +/// - TODO(doip): Add UDP announcement/discovery (ISO 13400-2 ยง7.3) so +/// diagnostic tools can discover the proxy via Vehicle Identification. +/// - TODO(doip): Add TLS support for secure `DoIP` connections. +/// - TODO(doip): Add per-connection inactivity timeout (`T_TCP_General_Inactivity`). +pub struct DoIpServer { + /// Shared proxy configuration. + config: Arc, + /// Backend diagnostic handler injected at construction time. + diag_handler: Arc, + /// Number of currently active TCP connections. + active_connections: Arc, +} + +impl DoIpServer { + /// Create a new `DoIP` server with a diagnostic handler. + /// + /// The handler is constructed and wired in `proxy-main`, keeping the + /// `DoIP` layer decoupled from the concrete SOVD backend. + pub fn new(config: Arc, diag_handler: Arc) -> Self { + Self { + config, + diag_handler, + active_connections: Arc::new(AtomicUsize::new(0)), + } + } + + /// Start the `DoIP` TCP server and accept connections in a loop. + /// + /// # Errors + /// Returns an error if the server cannot bind or accept connections. + pub async fn run(&self) -> Result<()> { + let addr = format!( + "{}:{}", + self.config.server.bind_address, self.config.server.doip_port + ); + + info!("Starting DoIP server on {}", addr); + + let listener = TcpListener::bind(&addr).await?; + info!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•"); + info!("DoIP server listening on {}", addr); + info!("UDS2SOVD Proxy ready to accept connections"); + info!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•"); + + loop { + match listener.accept().await { + Ok((stream, peer_addr)) => { + let previous = self.active_connections.fetch_add(1, Ordering::AcqRel); + let limit = self.config.server.max_connections; + if previous >= limit { + self.active_connections.fetch_sub(1, Ordering::AcqRel); + warn!( + "Rejecting connection from {} because active connection limit {}/{} \ + is reached", + peer_addr, previous, limit, + ); + drop(stream); + continue; + } + + let active_now = previous.saturating_add(1); + info!( + "Accepted connection from {} (active connections: {}/{})", + peer_addr, active_now, limit, + ); + + let config = Arc::clone(&self.config); + let diag_handler = Arc::clone(&self.diag_handler); + let active_connections = Arc::clone(&self.active_connections); + + // Spawn handler for this connection + tokio::spawn(async move { + let _connection_slot = ActiveConnectionSlot::new(active_connections); + let handler = ConnectionHandler::new(config, diag_handler, stream); + if let Err(e) = handler.handle().await { + error!("Connection handler error: {}", e); + } + }); + } + Err(e) => { + error!("Failed to accept connection: {}", e); + } + } + } + } +} + +/// Decrements the active connection counter when a connection task ends. +struct ActiveConnectionSlot { + counter: Arc, +} + +impl ActiveConnectionSlot { + fn new(counter: Arc) -> Self { + Self { counter } + } +} + +impl Drop for ActiveConnectionSlot { + fn drop(&mut self) { + self.counter.fetch_sub(1, Ordering::AcqRel); + } +} diff --git a/proxy-doip/src/session.rs b/proxy-doip/src/session.rs new file mode 100644 index 0000000..9091fbe --- /dev/null +++ b/proxy-doip/src/session.rs @@ -0,0 +1,101 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: 2026 The Contributors to Eclipse OpenSOVD (see CONTRIBUTORS) + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +/// `DoIP` routing activation session state. +/// +/// Tracks whether a valid routing activation exchange has occurred +/// and stores the source address of the activated tester. +pub struct Session { + /// `true` after a successful routing activation response. + routing_activated: bool, + /// Source address of the activated tester, if any. + source_address: Option, +} + +impl Session { + /// Create a new inactive session. + #[must_use] + pub fn new() -> Self { + Self { + routing_activated: false, + source_address: None, + } + } + + /// Activate the session with the given tester source address. + pub fn activate(&mut self, source_address: u16) { + self.routing_activated = true; + self.source_address = Some(source_address); + } + + /// Returns `true` if routing activation has been completed. + #[must_use] + pub fn is_activated(&self) -> bool { + self.routing_activated + } + + /// Returns `true` if the session is activated for the given source address. + #[must_use] + pub fn is_activated_for(&self, source_address: u16) -> bool { + self.routing_activated && self.source_address == Some(source_address) + } + + /// Returns the tester source address, if activated. + #[must_use] + pub fn source_address(&self) -> Option { + self.source_address + } + + /// Reset the session to an inactive state. + pub fn clear(&mut self) { + self.routing_activated = false; + self.source_address = None; + } +} + +impl Default for Session { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_new_session_inactive() { + let session = Session::new(); + assert!(!session.is_activated()); + assert_eq!(session.source_address(), None); + } + + #[test] + fn test_session_activation_for_source() { + let mut session = Session::new(); + session.activate(0x0E80); + + assert!(session.is_activated()); + assert!(session.is_activated_for(0x0E80)); + assert!(!session.is_activated_for(0x0E81)); + } + + #[test] + fn test_session_clear() { + let mut session = Session::new(); + session.activate(0x0E80); + session.clear(); + + assert!(!session.is_activated()); + assert_eq!(session.source_address(), None); + } +} From 24cb89b16f60a40eea213a446f804b45d80bf3a1 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Fri, 24 Apr 2026 07:53:56 +0200 Subject: [PATCH 29/33] fix: add Send + Sync bounds to DiagHandler usage in proxy-doip server/handler --- proxy-doip/src/handler.rs | 4 ++-- proxy-doip/src/server.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/proxy-doip/src/handler.rs b/proxy-doip/src/handler.rs index 33d9d0d..7067c20 100644 --- a/proxy-doip/src/handler.rs +++ b/proxy-doip/src/handler.rs @@ -121,7 +121,7 @@ pub struct ConnectionHandler { /// Shared proxy configuration. config: Arc, /// Backend handler for UDS request processing. - diag_handler: Arc, + diag_handler: Arc, /// Active TCP stream for this connection. stream: TcpStream, /// Routing activation session state. @@ -132,7 +132,7 @@ pub struct ConnectionHandler { impl ConnectionHandler { /// Create a new connection handler. - pub fn new(config: Arc, diag_handler: Arc, stream: TcpStream) -> Self { + pub fn new(config: Arc, diag_handler: Arc, stream: TcpStream) -> Self { Self { config, diag_handler, diff --git a/proxy-doip/src/server.rs b/proxy-doip/src/server.rs index 8a2b751..960803c 100644 --- a/proxy-doip/src/server.rs +++ b/proxy-doip/src/server.rs @@ -35,7 +35,7 @@ pub struct DoIpServer { /// Shared proxy configuration. config: Arc, /// Backend diagnostic handler injected at construction time. - diag_handler: Arc, + diag_handler: Arc, /// Number of currently active TCP connections. active_connections: Arc, } @@ -45,7 +45,7 @@ impl DoIpServer { /// /// The handler is constructed and wired in `proxy-main`, keeping the /// `DoIP` layer decoupled from the concrete SOVD backend. - pub fn new(config: Arc, diag_handler: Arc) -> Self { + pub fn new(config: Arc, diag_handler: Arc) -> Self { Self { config, diag_handler, From 9f27397d64c458e22a05a98846edee448b5573ed Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Mon, 27 Apr 2026 11:41:37 +0200 Subject: [PATCH 30/33] refactor: replace Arc with Arc in proxy-doip --- proxy-doip/Cargo.toml | 1 + proxy-doip/src/handler.rs | 7 ++++--- proxy-doip/src/server.rs | 10 ++++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/proxy-doip/Cargo.toml b/proxy-doip/Cargo.toml index 6bdf209..8122732 100644 --- a/proxy-doip/Cargo.toml +++ b/proxy-doip/Cargo.toml @@ -19,6 +19,7 @@ license.workspace = true [dependencies] proxy-core = { workspace = true } +proxy-sovd = { workspace = true } cda-interfaces = { workspace = true } tokio = { workspace = true, features = ["full"] } tracing = { workspace = true } diff --git a/proxy-doip/src/handler.rs b/proxy-doip/src/handler.rs index 7067c20..f323990 100644 --- a/proxy-doip/src/handler.rs +++ b/proxy-doip/src/handler.rs @@ -14,9 +14,10 @@ use std::sync::Arc; use cda_interfaces::service_ids; use proxy_core::{ - Config, DiagHandler, Result, + Config, Result, error::{Nrc, UdsError}, }; +use proxy_sovd::SovdDiagHandler; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::TcpStream, @@ -121,7 +122,7 @@ pub struct ConnectionHandler { /// Shared proxy configuration. config: Arc, /// Backend handler for UDS request processing. - diag_handler: Arc, + diag_handler: Arc, /// Active TCP stream for this connection. stream: TcpStream, /// Routing activation session state. @@ -132,7 +133,7 @@ pub struct ConnectionHandler { impl ConnectionHandler { /// Create a new connection handler. - pub fn new(config: Arc, diag_handler: Arc, stream: TcpStream) -> Self { + pub fn new(config: Arc, diag_handler: Arc, stream: TcpStream) -> Self { Self { config, diag_handler, diff --git a/proxy-doip/src/server.rs b/proxy-doip/src/server.rs index 960803c..aae53df 100644 --- a/proxy-doip/src/server.rs +++ b/proxy-doip/src/server.rs @@ -15,7 +15,8 @@ use std::sync::{ atomic::{AtomicUsize, Ordering}, }; -use proxy_core::{Config, DiagHandler, Result}; +use proxy_core::{Config, Result}; +use proxy_sovd::SovdDiagHandler; use tokio::net::TcpListener; use tracing::{error, info, warn}; @@ -25,7 +26,7 @@ use crate::handler::ConnectionHandler; /// /// Each incoming TCP connection is handled by a [`ConnectionHandler`] that /// reads `DoIP` frames, dispatches UDS requests to the injected -/// [`DiagHandler`], and returns the encoded response. +/// [`SovdDiagHandler`], and returns the encoded response. /// /// - TODO(doip): Add UDP announcement/discovery (ISO 13400-2 ยง7.3) so /// diagnostic tools can discover the proxy via Vehicle Identification. @@ -35,7 +36,7 @@ pub struct DoIpServer { /// Shared proxy configuration. config: Arc, /// Backend diagnostic handler injected at construction time. - diag_handler: Arc, + diag_handler: Arc, /// Number of currently active TCP connections. active_connections: Arc, } @@ -45,7 +46,8 @@ impl DoIpServer { /// /// The handler is constructed and wired in `proxy-main`, keeping the /// `DoIP` layer decoupled from the concrete SOVD backend. - pub fn new(config: Arc, diag_handler: Arc) -> Self { + #[must_use] + pub fn new(config: Arc, diag_handler: Arc) -> Self { Self { config, diag_handler, From 5675d95d7574325640d8ee525a62c17dda4356b4 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 30 Apr 2026 11:46:11 +0200 Subject: [PATCH 31/33] refactor: address review comments for proxy-doip --- proxy-doip/src/handler.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/proxy-doip/src/handler.rs b/proxy-doip/src/handler.rs index f323990..3d6db6c 100644 --- a/proxy-doip/src/handler.rs +++ b/proxy-doip/src/handler.rs @@ -224,6 +224,9 @@ impl ConnectionHandler { Ok(()) } + /// Dispatch an incoming `DoIP` frame to the correct handler based on + /// its payload type. + async fn process_message(&mut self, msg: &DoIpMessage) -> Result<()> { let payload_type = msg.payload_type_enum(); debug!( @@ -249,6 +252,10 @@ impl ConnectionHandler { } } + /// Parses the source address from the request, activates the session, + /// and replies with a `RoutingActivationResponse` (0x0006) signalling + /// success. Any subsequent diagnostic messages are only accepted from + /// the address recorded here. async fn handle_routing_activation(&mut self, msg: &DoIpMessage) -> Result<()> { let Some(req) = RoutingActivationRequest::from_payload(&msg.payload) else { warn!("Invalid routing activation request"); @@ -272,6 +279,12 @@ impl ConnectionHandler { Ok(()) } + /// Handle an ISO 13400 `DiagnosticMessage` (0x8001). + /// The UDS payload is forwarded to [`process_uds_request`] and the resulting + /// response is wrapped backinto a `DiagnosticMessage` and sent to the tester. + /// + /// # Errors + /// Returns an error if sending the diagnostic response fails. async fn handle_diagnostic_message(&mut self, msg: &DoIpMessage) -> Result<()> { if !self.session.is_activated() { warn!("Received diagnostic message before routing activation"); @@ -329,6 +342,14 @@ impl ConnectionHandler { Ok(()) } + /// Route a raw UDS byte slice to the appropriate service handler. + /// + /// Validates the minimum length, parses the SID, and dispatches to + /// `ReadDataByIdentifier` (0x22) or `WriteDataByIdentifier` (0x2E). + /// Unsupported SIDs get a `ServiceNotSupported` negative response. + /// For now - Never returns an error - all failures are encoded as UDS negative + /// responses so the `DoIP` transport always gets a reply. + /// TODO: Handle errors and return the errors caused async fn process_uds_request(&self, uds_data: &[u8]) -> Vec { // All supported services require at least SID (1) + DID high (1) + DID low (1). if uds_data.len() < MIN_READ_SERVICE_LENGTH { @@ -386,6 +407,11 @@ impl ConnectionHandler { } } + /// Execute a `WriteDataByIdentifier` (0x2E) + /// + /// Extracts the DID, rebuilds the full UDS frame with the SID prepended, + /// and delegates to `SovdDiagHandler`. Returns a positive 3-byte response + /// on success or a negative response on any failure. async fn process_write_data_by_identifier(&self, uds_msg: &UdsMessage) -> Vec { if uds_msg.data.len() < MIN_WDBI_DATA_LENGTH { error!("Invalid write request - missing DID or data"); @@ -415,6 +441,11 @@ impl ConnectionHandler { } } + /// Execute a `ReadDataByIdentifier` (0x22) + /// + /// Extracts the DID, rebuilds the full UDS frame with the SID prepended, + /// and delegates to `SovdDiagHandler`. Returns the encoded MDD-driven + /// response bytes on success or a negative response on failure. async fn process_read_data_by_identifier(&self, uds_msg: &UdsMessage) -> Vec { if uds_msg.data.len() < MIN_RDBI_DATA_LENGTH { error!("Invalid read request - missing DID"); @@ -444,6 +475,10 @@ impl ConnectionHandler { } } + /// Serialise a `DoIP` message and write it to the TCP stream. + /// + /// # Errors + /// Returns an error if the write or flush fails. async fn send_message(&mut self, msg: &DoIpMessage) -> Result<()> { let bytes = msg.to_bytes(); self.stream.write_all(&bytes).await?; From 5893b0bdfeb168d04c08dafbc1ef2d797b634b30 Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Thu, 30 Apr 2026 11:47:37 +0200 Subject: [PATCH 32/33] fix: restore correct diag_handler after rebase --- proxy-sovd/src/diag_handler.rs | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/proxy-sovd/src/diag_handler.rs b/proxy-sovd/src/diag_handler.rs index 1b1b35c..2e35f9d 100644 --- a/proxy-sovd/src/diag_handler.rs +++ b/proxy-sovd/src/diag_handler.rs @@ -10,11 +10,11 @@ * https://www.apache.org/licenses/LICENSE-2.0 */ -use std::{collections::HashMap, sync::Arc}; - +use cda_interfaces::HashMap; use proxy_core::{ - Config, ProxyError, ResolvedService, Result, ServiceResolver, error::UdsError, + Config, ProxyError, ResolvedService, Result, ServiceResolver, ServiceType, error::UdsError, }; +use std::sync::Arc; use tracing::info; use crate::mapper::SovdMapper; @@ -32,6 +32,10 @@ pub struct SovdDiagHandler { /// SOVD gateway mapper for request/response translation. mapper: SovdMapper, /// Per-ECU service resolvers keyed by ECU name. + /// + /// A map is used to support future multi-ECU configurations where a single + /// proxy instance handles requests for more than one ECU. Currently only + /// the ECU named in `config.ecu.default_name` is used. ecu_managers: Arc>, } @@ -51,10 +55,7 @@ impl SovdDiagHandler { } fn ecu_manager(&self) -> Option<&ServiceResolver> { - let ecu_name = &self.config.ecu.default_name; - self.ecu_managers - .get(ecu_name) - .or_else(|| self.ecu_managers.values().next()) + self.ecu_managers.get(&self.config.ecu.default_name) } } @@ -78,20 +79,15 @@ impl SovdDiagHandler { name: service_name, params: parsed_data, } = mgr - .resolve_read_service(did, uds_request) + .resolver + .resolve(ServiceType::Read, did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; info!("[MDD] READ service found: '{}'", service_name); self.mapper - .process_read_data_request( - did, - uds_request, - Some(mgr), - &service_name, - Some(parsed_data), - ) + .process_read_data_request(did, uds_request, mgr, &service_name, Some(parsed_data)) .await } @@ -114,7 +110,8 @@ impl SovdDiagHandler { name: service_name, params: parsed_data, } = mgr - .resolve_write_service(did, uds_request) + .resolver + .resolve(ServiceType::Write, did, uds_request) .await .ok_or(ProxyError::Uds(UdsError::InvalidDid(did)))?; From b118a14b4f0b3e2f11f3ea284e3925bf7458d9da Mon Sep 17 00:00:00 2001 From: Arvind Rathod Date: Tue, 12 May 2026 15:05:51 +0200 Subject: [PATCH 33/33] fix: address review comments for proxy-doip --- Cargo.lock | 1 + proxy-doip/src/handler.rs | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 3f29edf..1322201 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1700,6 +1700,7 @@ dependencies = [ "bytes", "cda-interfaces", "proxy-core", + "proxy-sovd", "tokio", "tracing", ] diff --git a/proxy-doip/src/handler.rs b/proxy-doip/src/handler.rs index 3d6db6c..a9cef62 100644 --- a/proxy-doip/src/handler.rs +++ b/proxy-doip/src/handler.rs @@ -226,7 +226,6 @@ impl ConnectionHandler { /// Dispatch an incoming `DoIP` frame to the correct handler based on /// its payload type. - async fn process_message(&mut self, msg: &DoIpMessage) -> Result<()> { let payload_type = msg.payload_type_enum(); debug!(