diff --git a/Cargo.lock b/Cargo.lock index 55e3925..1322201 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,5 +3,3324 @@ 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 = "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" +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 = "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" +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=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cda-core" +version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" +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=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" +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=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" +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=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" +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 = "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" +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 = "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" +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 0.6.4", + "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 = "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" +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 0.6.4", + "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 0.61.2", +] + +[[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 0.6.4", + "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 = "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" +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", + "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]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "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 0.6.4", + "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 = "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" +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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", + "serde", + "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 = "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" +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 = [ + "cfg-if", + "futures-util", + "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 0.8.6", + "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.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[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 = "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" +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 = "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" +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 0.61.2", +] + +[[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 0.8.6", + "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 = "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" +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 = "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" +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 = [ + "cda-core", + "cda-database", + "cda-interfaces", + "cda-plugin-security", + "clap", + "serde", + "serde_json", + "thiserror", + "tokio", + "toml", + "tracing", + "url", +] + +[[package]] +name = "proxy-doip" +version = "0.1.0" +dependencies = [ + "bytes", + "cda-interfaces", + "proxy-core", + "proxy-sovd", + "tokio", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +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" +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 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]] +name = "rand_chacha" +version = "0.3.1" +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", +] + +[[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 = "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" +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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "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" +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 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" +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 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]] +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 = "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" +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 0.6.4", +] + +[[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 0.61.2", +] + +[[package]] +name = "sovd-interfaces" version = "0.1.0" +source = "git+https://github.com/eclipse-opensovd/classic-diagnostic-adapter.git?rev=cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b#cf7fd9c18a7c49467e9e6c9ceae1e771c613e49b" +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 = "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" +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" +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" +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 0.61.2", +] + +[[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 = "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" +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 0.61.2", +] + +[[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 = "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" +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", + "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", +] + +[[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 = "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" +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 = "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", + "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" +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 = "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" +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-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" +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 = "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" +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.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "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 = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[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 = "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" +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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml index 529569d..a9bea59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,15 +8,46 @@ # 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", + "proxy-sovd", + "proxy-doip", +] + +[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 = "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" +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 } +url = { version = "2", features = ["serde"] } + +# ---- 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 @@ -44,3 +75,10 @@ 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..d0d7dd3 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 (`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) +- `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 `examples/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 SOVD Server + ↓ 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 `examples/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/deny.toml b/deny.toml index 10e3516..4c2ae1a 100644 --- a/deny.toml +++ b/deny.toml @@ -16,14 +16,17 @@ 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: @@ -32,15 +35,24 @@ ignore = [] # 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"] - +allow = [ + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "Zlib", + "ISC", + "Unicode-3.0", + "CDLA-Permissive-2.0", +] confidence-threshold = 0.9 exceptions = [] + [licenses.private] 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 @@ -57,6 +69,7 @@ deny = [] 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 @@ -72,6 +85,7 @@ allow-git = [ "https://github.com/alexmohr/flatbuffers.git", ] + [sources.allow-org] github = [] gitlab = [] diff --git a/docs/service_resolver/service_resolver_class_diagram.puml b/docs/service_resolver/service_resolver_class_diagram.puml new file mode 100644 index 0000000..82e3c5f --- /dev/null +++ b/docs/service_resolver/service_resolver_class_diagram.puml @@ -0,0 +1,192 @@ +' 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 +' 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 +' uds_helpers.rs holds pure free functions only. +' ───────────────────────────────────────────────────────────────── +package "proxy-core::service_resolver" { + + class ServiceResolver <> { + - manager : CdaEcuManager + - resolver : DidResolver + - encoder : ResponseEncoder + - metadata : MetadataProvider + == mod.rs -- construction == + + {static} <> new(db, logical, tester) : Result + - {static} <> activate_base_variant(manager) : Result<()> + - {static} default_com_params(logical, tester: u16) : ComParams + == 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 <> { + - manager : CdaEcuManager + == resolve.rs -- DID --> service name == + ~ <> 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 <> { + - 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_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> + } + } + + note right of DidResolver + + 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 + 4. No match --> log error, return None (no fallback) + end note + + 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 + via MetadataProvider.get_enriched_response_metadata_with_source(). + end note + + class uds_helpers <> { + ' -- 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 + == 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 + ~ 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. + end note + + class ResolvedService <> { + + name : String + + params : Map + } + + 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 + DidResolver ..> ResolvedService : returns +} + +' ───────────────────────────────────────────────────────────────── +' 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(plugin) + + get_components_configurations_info(plugin) + + get_mux_cases_for_service(service) + ' — encoding / decoding — + + create_uds_payload(service, plugin, params) + + convert_from_uds(service, payload, true) + + convert_request_from_uds(service, payload, true) + ' — variant selection — + + detect_variant(responses) + } + + 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 { + + 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 + CdaEcuManager = Arc>>. + Each sub-component receives an Arc::clone + to allow concurrent async read access. +end note + +@enduml 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..550c25d --- /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-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_class_diagram.svg.license b/docs/service_resolver/service_resolver_class_diagram.svg.license new file mode 100644 index 0000000..7319749 --- /dev/null +++ b/docs/service_resolver/service_resolver_class_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/service_resolver_sequence_diagram.puml b/docs/service_resolver/service_resolver_sequence_diagram.puml new file mode 100644 index 0000000..d7b3bef --- /dev/null +++ b/docs/service_resolver/service_resolver_sequence_diagram.puml @@ -0,0 +1,185 @@ +' 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)" 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: resolve(ServiceType::Read, did, uds_bytes) +activate Facade + + Facade -> Resolver: resolve(service_type, did, uds_bytes) + activate Resolver + + Resolver -> Resolver: resolve_service_did(sid=0x22, did, label="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, did_prefix, sid, did, label) + 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 + + Resolver --> Facade: Option + deactivate Resolver + +Facade --> Client: Option +deactivate Facade + +== WRITE Service Handling == + +note right of Client + Similar flow for WRITE services + client calls facade.resolve(ServiceType::Write, did, uds_bytes) + which uses sid=0x2E and get_components_configurations_info() +end note + +== Response Building == + +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 + + 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 --> Facade: Result, DiagServiceError> +deactivate Resp + +Facade --> Client: Result, DiagServiceError> +deactivate Facade + +note right of Client + + - **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, + 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 internally + for the cross-module enrichment dependency. +end note + +@enduml 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..2fcfb0e --- /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)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/docs/service_resolver/service_resolver_sequence_diagram.svg.license b/docs/service_resolver/service_resolver_sequence_diagram.svg.license new file mode 100644 index 0000000..7319749 --- /dev/null +++ b/docs/service_resolver/service_resolver_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/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/Cargo.toml b/proxy-core/Cargo.toml new file mode 100644 index 0000000..2f8ed1c --- /dev/null +++ b/proxy-core/Cargo.toml @@ -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 + +[package] +name = "proxy-core" +version.workspace = true +edition.workspace = true +publish = false +description = "Shared types, errors, and MDD engine 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 } +thiserror = { workspace = true } +serde = { workspace = true } +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 new file mode 100644 index 0000000..b2cdafd --- /dev/null +++ b/proxy-core/src/config.rs @@ -0,0 +1,412 @@ +/* + * 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::{ + net::{IpAddr, Ipv4Addr}, + path::Path, +}; + +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; + +// 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, + /// 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, +} + +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) +} + +/// 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 { + let v = usize::deserialize(deserializer)?; + if v == 0 { + return Err(de::Error::custom("value must be greater than zero")); + } + 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)] +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, + /// `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 = "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: [u8; EID_GID_BYTE_LENGTH], + /// 6-byte Group Identification. + pub gid: [u8; EID_GID_BYTE_LENGTH], +} + +/// Logging output configuration. +#[derive(Debug, Clone, 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}"))) + } +} + +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, + } + } +} + +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, + } + } +} + +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], + } + } +} + +impl Default for LoggingConfig { + fn default() -> Self { + Self { + 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"); + assert_eq!(config.ecu.eid, [0, 1, 2, 3, 4, 5]); + } + + #[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); + } + + #[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/error.rs b/proxy-core/src/error.rs new file mode 100644 index 0000000..0bc5530 --- /dev/null +++ b/proxy-core/src/error.rs @@ -0,0 +1,316 @@ +/* + * 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 error: {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, + } + } +} + +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::*; + + #[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')); + + let err = UdsError::NegativeResponse { + nrc: 0x31, + description: "Request out of range".into(), + }; + assert!(err.to_string().contains("0x31")); + } + + #[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..9ef4ff0 --- /dev/null +++ b/proxy-core/src/lib.rs @@ -0,0 +1,19 @@ +/* + * 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 + */ + +pub mod config; +pub mod error; +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}; diff --git a/proxy-core/src/service_resolver/metadata.rs b/proxy-core/src/service_resolver/metadata.rs new file mode 100644 index 0000000..2f99179 --- /dev/null +++ b/proxy-core/src/service_resolver/metadata.rs @@ -0,0 +1,621 @@ +/* + * 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. +//! +//! [`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, ServiceParameterMetadata, +}; + +use super::{ManagerHandle, uds_helpers::has_mux_case_for_did_exact, uds_service_ids}; + +#[derive(Clone)] +pub(crate) struct MetadataProvider { + manager: ManagerHandle, +} + +impl MetadataProvider { + 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. + #[allow(dead_code)] + pub(crate) async fn get_request_params( + &self, + service_name: &str, + ) -> Result, DiagServiceError> { + let manager = self.manager.read().await; + manager.get_request_parameter_metadata(service_name) + } + + /// Return the POS-RESPONSE parameter layout (byte positions, sizes, types). + /// + /// # Errors + /// + /// Returns `DiagServiceError` when the service is unknown or no response + /// metadata exists. + pub(crate) async fn get_response_params( + &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 `DiagServiceError` when the base metadata lookup fails. + pub(crate) 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) + } + + /// 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 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. + #[allow(dead_code)] + pub(crate) 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 = match sid { + uds_service_ids::READ_DATA_BY_IDENTIFIER => manager + .get_components_data_info(&security_plugin) + .into_iter() + .map(|c| c.id) + .collect(), + uds_service_ids::WRITE_DATA_BY_IDENTIFIER => manager + .get_components_configurations_info(&security_plugin) + .unwrap_or_default() + .into_iter() + .map(|c| c.id) + .collect(), + _ => Vec::new(), + }; + Ok(names) + } + + /// Return the best available POS-RESPONSE metadata for `service_name` + `did`. + /// + /// Tries the enriched (MUX-substituted) path first; falls back to the plain + /// POS-RESPONSE layout when the enriched path fails. + /// + /// # Errors + /// + /// Returns `DiagServiceError` when both the enriched and plain paths fail. + pub(crate) async fn get_response_metadata( + &self, + service_name: &str, + 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. + /// + /// 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 + /// that need to validate via `convert_from_uds` must use this name, not + /// the original. + /// + /// # Errors + /// + /// Returns `DiagServiceError` when the base metadata lookup fails. + pub(crate) 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. + 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) { + 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)); + } + } + + // No MUX sibling found -- use original metadata. + Ok((meta, service_name.to_string())) + } +} + +#[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, + }; + 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); + } +} + +#[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); + } +} diff --git a/proxy-core/src/service_resolver/mod.rs b/proxy-core/src/service_resolver/mod.rs new file mode 100644 index 0000000..eaaa23d --- /dev/null +++ b/proxy-core/src/service_resolver/mod.rs @@ -0,0 +1,278 @@ +/* + * 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 + */ + +//! MDD-driven UDS encoding, decoding, and service resolution. +//! +//! `ServiceResolver` is a thin facade that owns the CDA `EcuManager` and +//! exposes three focused sub-components via accessor methods: +//! + +pub(crate) mod metadata; +pub(crate) mod resolve; +pub(crate) mod response; +pub(crate) 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, ResponseParameterInfo, + datatypes::{ComParams, DatabaseNamingConvention, DiagnosticServiceAffixPosition}, + diagservices::DiagServiceResponseType, +}; +use cda_plugin_security::DefaultSecurityPluginData; +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(crate) type ManagerHandle = Arc>>; + +/// Minimum UDS positive response buffer size: response SID (1) + DID high (1) + DID low (1). +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; +} + +pub struct ServiceResolver { + /// DID-to-service resolution. + resolver: DidResolver, + /// UDS response encoding from SOVD JSON data. + encoder: ResponseEncoder, + /// MDD metadata queries (request/response parameter info, MUX cases). + metadata: MetadataProvider, +} + +impl ServiceResolver { + /// 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( + 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?; + + let handle: ManagerHandle = Arc::new(RwLock::new(manager)); + + let metadata = MetadataProvider::new(Arc::clone(&handle)); + Ok(Self { + resolver: DidResolver::new(Arc::clone(&handle)), + encoder: ResponseEncoder::new(Arc::clone(&handle), metadata.clone()), + metadata, + }) + } + + /// 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 `DiagServiceError` when `detect_variant` fails and no + /// variant name was set. + async fn activate_base_variant( + manager: &mut CdaEcuManager, + ) -> Result<(), DiagServiceError> { + // TODO(#16): replace with real variant-identification DID reads. + let dummy_response = DiagServiceResponseStruct { + service: DiagComm { + name: String::new(), + type_: DiagCommType::Data, + lookup_name: None, + }, + data: Vec::new(), + mapped_data: None, + response_type: DiagServiceResponseType::Positive, + }; + + let mut responses: HashMap = HashMap::default(); + responses.insert("__variant_init__".to_string(), dummy_response); + + manager + .detect_variant(responses) + .await + .or_else(|e| match manager.variant().name { + Some(ref name) => { + tracing::info!( + "Base variant '{}' activated (state chart init skipped: {})", + name, + e + ); + Ok(()) + } + None => Err(e), + }) + } + + /// 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 { + 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_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" + ); + } +} diff --git a/proxy-core/src/service_resolver/resolve.rs b/proxy-core/src/service_resolver/resolve.rs new file mode 100644 index 0000000..d660271 --- /dev/null +++ b/proxy-core/src/service_resolver/resolve.rs @@ -0,0 +1,477 @@ +/* + * 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::{ + DynamicPlugin, EcuManager as EcuManagerTrait, HashMap, ServiceParameterMetadata, + diagservices::{DiagServiceResponse, UdsPayloadData}, +}; +use cda_plugin_security::DefaultSecurityPluginData; + +use super::{ + 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"`). + 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. +pub(crate) struct DidResolver { + manager: ManagerHandle, +} + +impl DidResolver { + /// Create a new resolver backed by the given manager handle. + pub(crate) fn new(manager: ManagerHandle) -> Self { + Self { manager } + } + + /// Resolve the best-matching service for a UDS DID request. + pub(crate) async fn resolve( + &self, + service_type: ServiceType, + did: u16, + uds_bytes: &[u8], + ) -> 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, 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 = make_diag_comm(&service_name, sid); + + 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. + /// + /// 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)] + 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. + 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 + } + + /// Build the candidate list from prefix lookup and supplementary sources. + /// + /// 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, + did_prefix: [u8; 3], + sid: u8, + did: u16, + label: &str, + ) -> Option> { + // 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(); + + // 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!( + "[resolve_did] {} DID 0x{:04X} -> '{}' (prefix match)", + label, + did, + name + ); + return Some(vec![name.to_owned()]); + } + + // 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 { + let name = dc.lookup_name.as_deref().unwrap_or(&dc.name).to_owned(); + if !candidates.contains(&name) { + candidates.push(name); + } + } + + let security_plugin: DynamicPlugin = Box::new(()); + 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() + } 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() + } else { + Vec::new() + }; + for name in extra_names { + if !candidates.contains(&name) { + 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} ({} candidates)", + label, + sid, + did, + candidates.len(), + ); + + Some(candidates) + } + + /// Check if `candidate_name` matches `did` via request parameter metadata. + async fn match_candidate_did( + manager: &CdaEcuManager, + candidate_name: &str, + sid: u8, + did: u16, + ) -> bool { + let Ok(meta) = manager.get_request_parameter_metadata(candidate_name) else { + return false; + }; + + let did_param = find_did_param(&meta, sid); + + 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, .. }) => { + // 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), + None => Self::probe_service_did(manager, candidate_name, sid, &meta).await, + }; + resolved == Some(did) + } + + Some(cda_interfaces::ParameterTypeMetadata::Value { + coded_default_value, + compu_scales, + .. + }) => { + // 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) + .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 + } + } + } + + /// 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 = make_diag_comm(service_name, sid); + 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: DID 0x0000 is reserved; treat zero as unresolvable. + if probed_did == 0 { + None + } else { + Some(probed_did) + } + } +} + +#[cfg(test)] +mod tests { + 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)); + 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)); + 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); + } + + #[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)); + } + + #[test] + fn test_find_did_param_skips_sid() { + 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: Some("DATA-IDENTIFIER".to_string()), + param_type: ParameterTypeMetadata::CodedConst { + 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 did_param = find_did_param(&meta, sid); + assert!(did_param.is_some()); + assert_eq!(did_param.unwrap().name, "DID"); + } + + #[test] + fn test_find_did_param_no_sid_match() { + use cda_interfaces::{ParameterTypeMetadata, ServiceParameterMetadata}; + let meta = vec![ServiceParameterMetadata { + name: "ONLY_PARAM".to_string(), + semantic: None, + param_type: ParameterTypeMetadata::PhysConst { + phys_constant_value: "VALUE".to_string(), + coded_value: 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 new file mode 100644 index 0000000..c11729c --- /dev/null +++ b/proxy-core/src/service_resolver/response.rs @@ -0,0 +1,596 @@ +/* + * 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. +//! +//! [`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, + diagservices::DiagServiceResponse, +}; + +use super::{ + 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, + }, +}; + +/// 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 struct ResponseEncoder { + manager: ManagerHandle, + metadata: MetadataProvider, +} + +impl ResponseEncoder { + /// Create a new response encoder. + pub fn new(manager: ManagerHandle, metadata: MetadataProvider) -> Self { + Self { manager, metadata } + } + + /// Build UDS response bytes from SOVD JSON data. + /// + /// Queries the MDD POS-RESPONSE layout and encodes each parameter at its + /// defined byte position: + /// + /// - `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 when no response metadata is available. + /// + /// # Errors + /// + /// 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, + 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 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); + // 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]; + + 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: 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; + } + + Ok(response) + } + + /// Encode a UDS response using POS-RESPONSE parameter metadata. + /// + /// 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, + _sid: u8, + 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()?; + if meta.is_empty() { + return None; + } + + // Find the MUX case matching this DID (floor-based). + let mux_case_prefix = find_mux_case_prefix(&meta, did); + + // 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()) + .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(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?}", + service_name, + response + ); + 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)] +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 new file mode 100644 index 0000000..f96060e --- /dev/null +++ b/proxy-core/src/service_resolver/uds_helpers.rs @@ -0,0 +1,515 @@ +/* + * 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 and types. +//! +//! Pure functions used across the `service_resolver` module: DID extraction, +//! MUX-case matching, value encoding, and payload construction. + +use cda_interfaces::{ + CompuScaleInfo, DiagComm, 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 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. +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 (minimum width). +/// +/// Zero encodes as `[0x00]`. +pub(super) fn encode_unsigned_be(num: u64) -> Vec { + if num == 0 { + return vec![0x00]; + } + 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(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 + // the narrowing cast. DIDs are 16-bit so precision loss from f64 never occurs in practice. + #[allow( + 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 + )] + 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. +/// +/// 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(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. + 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(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__/") + && 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>, +) { + 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 + .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(), + } +} + +/// 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; + + 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_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/proxy-doip/Cargo.toml b/proxy-doip/Cargo.toml new file mode 100644 index 0000000..8122732 --- /dev/null +++ b/proxy-doip/Cargo.toml @@ -0,0 +1,29 @@ +# 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 } +proxy-sovd = { 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..a9cef62 --- /dev/null +++ b/proxy-doip/src/handler.rs @@ -0,0 +1,546 @@ +/* + * 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, Result, + error::{Nrc, UdsError}, +}; +use proxy_sovd::SovdDiagHandler; +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(()) + } + + /// 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!( + "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(()) + } + } + } + + /// 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"); + 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(()) + } + + /// 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"); + 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(()) + } + + /// 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 { + 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) + } + } + } + + /// 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"); + 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) + } + } + } + + /// 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"); + 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) + } + } + } + + /// 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?; + 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..aae53df --- /dev/null +++ b/proxy-doip/src/server.rs @@ -0,0 +1,134 @@ +/* + * 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, Result}; +use proxy_sovd::SovdDiagHandler; +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 +/// [`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. +/// - 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. + #[must_use] + 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); + } +} 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..5f95781 --- /dev/null +++ b/proxy-sovd/src/client.rs @@ -0,0 +1,738 @@ +/* + * 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}, +}; +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]) + } +} + +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; + + 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..2e35f9d --- /dev/null +++ b/proxy-sovd/src/diag_handler.rs @@ -0,0 +1,124 @@ +/* + * 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::HashMap; +use proxy_core::{ + 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>, +} + +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> { + self.ecu_managers.get(&self.config.ecu.default_name) + } +} + +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 + .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, 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> { + 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 + .resolver + .resolve(ServiceType::Write, 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")); + } +} diff --git a/testcontainer/mdd/FLXC1000.mdd b/testcontainer/mdd/FLXC1000.mdd new file mode 100644 index 0000000..cee0703 Binary files /dev/null and b/testcontainer/mdd/FLXC1000.mdd differ 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