From a2ded6506f9c35052669478388a154cb09042f08 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 19:27:42 +0000 Subject: [PATCH 1/6] chore: pin contracts to the LAN transport contract (contracts#52) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- contracts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts b/contracts index d825689..ac2fcad 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit d825689a2436f0f34fdb3b9dfe7b52a0467c3a8e +Subproject commit ac2fcad4982c6d77f49456840f95c2ba729dc6ef From 55f5688e65d0bde0bf847b5b639f0c66b2b43032 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 19:27:42 +0000 Subject: [PATCH 2/6] feat(lan): serve the secure channel over TCP on the LAN, with UDP discovery core-interface gets lan.rs: connection slots, frames in and out per connection (command responses, a system state with the client's command availability and the LAN address, the full vehicle state), the UDP discovery reply and the mDNS TXT records. Sessions now know whether their link is LAN or relay, and handshake inits are rate-limited before any X25519 work. SystemState.lan_address goes out over BLE too. The PC board serves it with [network.lan] (non-blocking sockets polled from one task, mDNS through mdns-sd), and tools/lan_client.py plays the app's part for an end-to-end test. Closes #120 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- .gitignore | 1 + Cargo.lock | 70 ++- README.md | 2 +- boards/esp/xtask_builder.rs | 6 + boards/pc/Cargo.toml | 3 + boards/pc/main.template.rs | 2 +- boards/pc/src/lan.rs | 284 +++++++++++ boards/pc/src/lib.rs | 2 + boards/pc/xtask_builder.rs | 70 ++- config.toml.example | 9 + core-interface/build.rs | 96 +++- core-interface/src/availability.rs | 15 + core-interface/src/can_access.rs | 5 +- core-interface/src/lan.rs | 442 +++++++++++++++++ core-interface/src/lib.rs | 32 +- core-interface/src/routing.rs | 2 + core-interface/src/secure_channel.rs | 124 ++++- core-interface/src/types.rs | 3 +- core-interface/tests/lan.rs | 476 +++++++++++++++++++ core-interface/tests/secure_channel.rs | 16 +- docs/architecture.md | 10 +- docs/lan.md | 45 ++ tools/__pycache__/lan_client.cpython-313.pyc | Bin 0 -> 24952 bytes tools/lan_client.py | 416 ++++++++++++++++ xtask/src/main.rs | 40 ++ 25 files changed, 2115 insertions(+), 56 deletions(-) create mode 100644 boards/pc/src/lan.rs create mode 100644 core-interface/src/lan.rs create mode 100644 core-interface/tests/lan.rs create mode 100644 docs/lan.md create mode 100644 tools/__pycache__/lan_client.cpython-313.pyc create mode 100644 tools/lan_client.py diff --git a/.gitignore b/.gitignore index 949fc3e..c14a32b 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ dist/* # Firmware images (e.g. stock WiCAN firmware kept for restoring a device) *.bin +.lan-client.json diff --git a/Cargo.lock b/Cargo.lock index 9c52b3b..24635cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -272,6 +272,7 @@ dependencies = [ "embedded-can", "embedded-io-async 0.7.0", "log", + "mdns-sd", "prost", "rust-mqtt", "rustls", @@ -1754,9 +1755,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.3.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "ff" @@ -1796,6 +1797,15 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "spin", +] + [[package]] name = "fnv" version = "1.0.7" @@ -2133,6 +2143,16 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "if-addrs" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "ignore" version = "0.4.32" @@ -2413,6 +2433,20 @@ dependencies = [ "void", ] +[[package]] +name = "mdns-sd" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce8fbcff05ecc0559801370d5813fb22a1ea673631c8198b6d9eee45216303d1" +dependencies = [ + "fastrand", + "flume", + "if-addrs", + "mio", + "socket-pktinfo", + "socket2", +] + [[package]] name = "memchr" version = "2.8.0" @@ -2434,6 +2468,18 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "modular-bitfield" version = "0.11.2" @@ -3273,6 +3319,17 @@ dependencies = [ "managed", ] +[[package]] +name = "socket-pktinfo" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebed71a43801aa9e62b6d9a28c5b22802537920532af04b57138973e82961d26" +dependencies = [ + "libc", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "socket2" version = "0.6.5" @@ -3316,6 +3373,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0f368519fc6c85fc1afdb769fb5a51123f6158013e143656e25a3485a0d401c" +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" diff --git a/README.md b/README.md index 1b594bd..a266742 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ The firmware is a Cargo workspace of independently compiled crates that cooperat | `cars/*` | Vehicle logic: CAN decoding, command handling, state encoding | | `xtask` | Build orchestrator: reads `config.toml`, generates `.app_build/`, invokes cargo | -Details: [Architecture](docs/architecture.md) · [BLE](docs/ble.md) · [CAN bus](docs/can.md) · [LTE](docs/lte.md) · [MQTT over TLS](docs/mqtt-tls.md) · [Vehicle commands](docs/commands.md) +Details: [Architecture](docs/architecture.md) · [BLE](docs/ble.md) · [CAN bus](docs/can.md) · [LAN direct](docs/lan.md) · [LTE](docs/lte.md) · [MQTT over TLS](docs/mqtt-tls.md) · [Vehicle commands](docs/commands.md) ## 📂 Project Structure diff --git a/boards/esp/xtask_builder.rs b/boards/esp/xtask_builder.rs index bea8b68..cd30e3d 100644 --- a/boards/esp/xtask_builder.rs +++ b/boards/esp/xtask_builder.rs @@ -615,6 +615,12 @@ impl TargetBuilder for Builder { exit(1); }); let wifi_enabled = uplink == Uplink::Wifi; + if config.network.lan.enabled { + println!( + "\u{26a0}\u{fe0f} [network.lan].enabled is ignored on ESP builds for now: LAN direct \ + is on the PC board only (ESP support is firmware#121)." + ); + } let wifi_ssid = if wifi_enabled { config.network.wifi.ssid.as_deref().unwrap_or_else(|| { eprintln!("\u{274c} [network.wifi].ssid is required for the ESP board when [network.wifi].enabled=true"); diff --git a/boards/pc/Cargo.toml b/boards/pc/Cargo.toml index ad5909c..4efeb8d 100644 --- a/boards/pc/Cargo.toml +++ b/boards/pc/Cargo.toml @@ -16,6 +16,9 @@ log = { workspace = true } # TLS for MQTT (mqtts://). ring instead of aws-lc-rs: it builds without cmake. rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12", "logging"] } +# Announces LAN direct over mDNS (docs/lan.md). +mdns-sd = { version = "0.22", default-features = false } + [target.'cfg(target_os = "linux")'.dependencies] socketcan = { version = "4.0.0", default-features = false } diff --git a/boards/pc/main.template.rs b/boards/pc/main.template.rs index 3ebee86..1c1c0a0 100644 --- a/boards/pc/main.template.rs +++ b/boards/pc/main.template.rs @@ -16,7 +16,7 @@ async fn main(spawner: Spawner) { board_pc::start(&spawner); // After `start`, which sets the random source a new identity is made from. board_pc::restore_secure_keys(DEVICE_IDENTITY_FILE, CLIENT_KEYS_FILE); -{CAN_SPAWNS}{BLE_HTTP_SPAWN}{MQTT_DRIVER_SPAWN}{CAN_LOGGER_SPAWN} spawner.spawn({VEHICLE_CRATE_IDENT}::handle_basic_commands_task().unwrap()); +{CAN_SPAWNS}{BLE_HTTP_SPAWN}{MQTT_DRIVER_SPAWN}{CAN_LOGGER_SPAWN}{LAN_SPAWN} spawner.spawn({VEHICLE_CRATE_IDENT}::handle_basic_commands_task().unwrap()); spawner.spawn({VEHICLE_CRATE_IDENT}::handle_advanced_commands_task().unwrap()); spawner.spawn({VEHICLE_CRATE_IDENT}::state_update_task().unwrap()); spawner.spawn({VEHICLE_CRATE_IDENT}::can_rx_task().unwrap()); diff --git a/boards/pc/src/lan.rs b/boards/pc/src/lan.rs new file mode 100644 index 0000000..d382a16 --- /dev/null +++ b/boards/pc/src/lan.rs @@ -0,0 +1,284 @@ +//! LAN direct on the PC board (docs/lan.md): a TCP listener carrying the secure channel, +//! the UDP discovery responder and an mDNS announcement. The sockets are non-blocking and +//! polled from one Embassy task, so a slow or stuck client never blocks the executor +//! thread (#89). All the protocol and crypto are in `core-interface` (`lan.rs`). + +use std::io::{Read as _, Write as _}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream, UdpSocket}; + +use core_interface::LanConnection; +use embassy_time::{Duration, Instant, Timer}; + +/// How often the device's address is checked for a change. +const ADDRESS_CHECK: Duration = Duration::from_secs(30); +/// Outbound bytes buffered per connection before the device stops taking frames for it. +const MAX_PENDING_TX: usize = 16 * 1024; +/// Bytes read from one connection per pass, so one client can't starve the others. +const READ_CHUNK: usize = 4096; + +struct Client { + conn: LanConnection, + stream: TcpStream, + peer: SocketAddr, + rx: Vec, + tx: Vec, +} + +fn now_ms() -> u64 { + Instant::now().as_millis() +} + +/// Appends `frame` with its 2-byte big-endian length prefix. +fn push_frame(out: &mut Vec, frame: &[u8]) { + out.extend_from_slice(&(frame.len() as u16).to_be_bytes()); + out.extend_from_slice(frame); +} + +/// The IPv4 address the host would use to reach other machines, without sending +/// anything (connecting a UDP socket only picks a route). +fn local_ipv4() -> Option { + let socket = UdpSocket::bind(("0.0.0.0", 0)).ok()?; + socket.connect(("192.0.2.1", 9)).ok()?; + match socket.local_addr().ok()?.ip() { + IpAddr::V4(ip) if !ip.is_unspecified() && !ip.is_loopback() => Some(ip), + _ => None, + } +} + +/// The mDNS announcement, re-registered when the address changes. +struct Mdns { + daemon: Option, + registered: Option, +} + +impl Mdns { + fn new(enabled: bool) -> Self { + let daemon = if enabled { + match mdns_sd::ServiceDaemon::new() { + Ok(daemon) => Some(daemon), + Err(e) => { + log::warn!("LAN: mDNS unavailable ({e}); the UDP probe still works"); + None + } + } + } else { + None + }; + Self { + daemon, + registered: None, + } + } + + /// Announcing failed or had to wait (no identity yet) while there is an address. + fn needs_retry(&self, ip: Option) -> bool { + self.daemon.is_some() && self.registered.is_none() && ip.is_some() + } + + fn announce(&mut self, name: &str, ip: Option, port: u16) { + let Some(daemon) = &self.daemon else { + return; + }; + if let Some(fullname) = self.registered.take() { + let _ = daemon.unregister(&fullname); + } + let (Some(ip), Some(txt)) = (ip, core_interface::lan_mdns_txt()) else { + return; + }; + let service = format!("{}.local.", core_interface::LAN_MDNS_SERVICE); + let host = format!("opencar-{}.local.", txt[0].1); + let info = mdns_sd::ServiceInfo::new(&service, name, &host, IpAddr::V4(ip), port, &txt[..]); + match info.and_then(|info| { + let fullname = info.get_fullname().to_string(); + daemon.register(info).map(|()| fullname) + }) { + Ok(fullname) => { + log::info!("LAN: announced over mDNS as '{name}' ({service})"); + self.registered = Some(fullname); + } + Err(e) => log::warn!("LAN: mDNS announcement failed: {e}"), + } + } +} + +/// Serves LAN direct on TCP `port` (and the UDP probe on the contract's discovery port), +/// announcing `name` over mDNS when `mdns` is set. +#[embassy_executor::task] +pub async fn lan_task(port: u16, name: &'static str, mdns: bool) { + let listener = loop { + match TcpListener::bind(("0.0.0.0", port)) { + Ok(l) => break l, + Err(e) => { + log::warn!("LAN: cannot listen on TCP port {port}: {e}, retrying in 5s"); + Timer::after(Duration::from_secs(5)).await; + } + } + }; + if let Err(e) = listener.set_nonblocking(true) { + log::error!("LAN: set_nonblocking failed: {e}"); + return; + } + let udp_port = core_interface::LAN_UDP_DISCOVERY_PORT; + let udp = match UdpSocket::bind(("0.0.0.0", udp_port)).and_then(|s| { + s.set_nonblocking(true)?; + Ok(s) + }) { + Ok(s) => Some(s), + Err(e) => { + log::warn!("LAN: no UDP discovery on port {udp_port}: {e}"); + None + } + }; + log::info!("LAN: listening on TCP port {port}, UDP discovery on {udp_port}"); + + let mut mdns = Mdns::new(mdns); + let mut address: Option = None; + let mut address_checked: Option = None; + let mut clients: Vec = Vec::new(); + + loop { + // The address: reported in SystemState.lan_address and announced over mDNS. + if address_checked.is_none_or(|at| at.elapsed() >= ADDRESS_CHECK) { + address_checked = Some(Instant::now()); + let ip = local_ipv4(); + if ip != address || mdns.needs_retry(ip) { + address = ip; + let reported = ip.map(|ip| format!("{ip}:{port}")); + log::info!("LAN: address {}", reported.as_deref().unwrap_or("none")); + core_interface::set_lan_address(reported.as_deref()); + mdns.announce(name, ip, port); + } + } + + let mut busy = false; + match listener.accept() { + Ok((stream, peer)) => { + busy = true; + accept(&mut clients, stream, peer); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(e) => log::warn!("LAN: accept failed: {e}"), + } + + let mut i = 0; + while i < clients.len() { + match serve(&mut clients[i]).await { + Ok(moved) => { + busy |= moved; + i += 1; + } + Err(reason) => { + let client = clients.swap_remove(i); + log::info!("LAN: {} disconnected ({reason})", client.peer); + core_interface::lan_close(client.conn); + } + } + } + + if let Some(udp) = &udp { + let mut buf = [0u8; 64]; + while let Ok((n, from)) = udp.recv_from(&mut buf) { + busy = true; + if let Some(reply) = core_interface::lan_discovery_reply(&buf[..n], port, now_ms()) + { + let _ = udp.send_to(&reply, from); + } + } + } + + if !busy { + Timer::after(Duration::from_millis(5)).await; + } + } +} + +fn accept(clients: &mut Vec, stream: TcpStream, peer: SocketAddr) { + let Some(conn) = core_interface::lan_accept(now_ms()) else { + log::info!("LAN: refused {peer}: every connection has a session"); + return; + }; + // A slot taken back from a connection without a session: drop that one. + if let Some(i) = clients.iter().position(|c| c.conn.slot == conn.slot) { + let old = clients.swap_remove(i); + log::info!("LAN: {} replaced before its handshake", old.peer); + } + if stream.set_nonblocking(true).is_err() { + core_interface::lan_close(conn); + return; + } + let _ = stream.set_nodelay(true); + log::info!("LAN: {peer} connected (slot {})", conn.slot); + clients.push(Client { + conn, + stream, + peer, + rx: Vec::new(), + tx: Vec::new(), + }); +} + +/// One pass over a connection: read, hand complete frames to core, queue what core has +/// to send, write. `Ok(true)` if anything moved, `Err` with the reason to close it. +async fn serve(client: &mut Client) -> Result { + let mut moved = false; + if core_interface::lan_should_close(client.conn, now_ms()) { + return Err("no session"); + } + + let mut buf = [0u8; READ_CHUNK]; + match client.stream.read(&mut buf) { + Ok(0) => return Err("closed by the peer"), + Ok(n) => { + moved = true; + client.rx.extend_from_slice(&buf[..n]); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(_) => return Err("read error"), + } + + while client.rx.len() >= 2 { + let len = u16::from_be_bytes([client.rx[0], client.rx[1]]) as usize; + if !core_interface::lan_frame_length_ok(len) { + return Err("bad frame length"); + } + if client.rx.len() < 2 + len { + break; + } + let frame: Vec = client.rx.drain(..2 + len).skip(2).collect(); + if let Some(reply) = core_interface::lan_receive_frame(client.conn, &frame).await { + push_frame(&mut client.tx, &reply); + } + } + + while client.tx.len() < MAX_PENDING_TX { + match core_interface::lan_try_next_frame(client.conn, now_ms()) { + Some(frame) => push_frame(&mut client.tx, &frame), + None => break, + } + } + + while !client.tx.is_empty() { + match client.stream.write(&client.tx) { + Ok(0) => return Err("write closed"), + Ok(n) => { + moved = true; + client.tx.drain(..n); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => return Err("write error"), + } + } + Ok(moved) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frames_get_a_big_endian_length_prefix() { + let mut out = Vec::new(); + push_frame(&mut out, &[1, 2, 3]); + assert_eq!(out, vec![0, 3, 1, 2, 3]); + } +} diff --git a/boards/pc/src/lib.rs b/boards/pc/src/lib.rs index 60859a7..b7bcc88 100644 --- a/boards/pc/src/lib.rs +++ b/boards/pc/src/lib.rs @@ -2,6 +2,7 @@ mod ble; mod can; mod can_approval; mod can_logger; +mod lan; mod network; mod phone_validations; mod restart; @@ -13,6 +14,7 @@ pub use ble::{ble_http_task, set_ble_paired_store_path}; pub use can::socket_can_task; pub use can_approval::{can_rw_approval_store_task, restore_can_rw_approval}; pub use can_logger::can_logger_task; +pub use lan::lan_task; pub use network::mqtt_driver_task; pub use phone_validations::{phone_validations_store_task, restore_phone_validations}; pub use secure_keys::{client_keys_store_task, restore_secure_keys}; diff --git a/boards/pc/xtask_builder.rs b/boards/pc/xtask_builder.rs index 5eb6446..2273405 100644 --- a/boards/pc/xtask_builder.rs +++ b/boards/pc/xtask_builder.rs @@ -95,7 +95,9 @@ pub struct Builder; impl Builder { fn get_pc_hw(config: &Config) -> PcHardwareConfig { - config.hardware.get("pc") + config + .hardware + .get("pc") .expect("\u{274c} Missing [hardware.pc] section in config") .clone() .try_into() @@ -105,7 +107,8 @@ impl Builder { fn execute_cargo_command(&self, cargo_cmd: &str, release: bool) { let mut cmd = Command::new("cargo"); cmd.arg(cargo_cmd) - .arg("--manifest-path").arg(".app_build/Cargo.toml"); + .arg("--manifest-path") + .arg(".app_build/Cargo.toml"); if release { cmd.arg("--release"); } @@ -131,7 +134,9 @@ impl TargetBuilder for Builder { std::process::exit(1); } if cfg!(windows) { - println!("Warning: Running PC simulator on Windows. Native SocketCAN will not be available."); + println!( + "Warning: Running PC simulator on Windows. Native SocketCAN will not be available." + ); } } @@ -162,13 +167,16 @@ impl TargetBuilder for Builder { let vehicle_platform = &config.target.platform; let (platform_id, can_bus_count) = crate::load_platform_meta(vehicle_platform); - let (vehicle_crate_name, vehicle_crate_ident) = crate::load_vehicle_crate_info(vehicle_platform); + let (vehicle_crate_name, vehicle_crate_ident) = + crate::load_vehicle_crate_info(vehicle_platform); // Validate CAN bus count if pc_hw.can_buses.len() < can_bus_count { eprintln!( "Vehicle '{}' requires {} CAN bus(es) but [hardware.pc] only defines {} [[hardware.pc.can_buses]] entries.", - vehicle_platform, can_bus_count, pc_hw.can_buses.len() + vehicle_platform, + can_bus_count, + pc_hw.can_buses.len() ); exit(1); } @@ -188,7 +196,9 @@ impl TargetBuilder for Builder { // Build .app_build/Cargo.toml let mut cargo_toml = String::new(); - cargo_toml.push_str("[package]\nname = \"app-build\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n"); + cargo_toml.push_str( + "[package]\nname = \"app-build\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n", + ); cargo_toml.push_str("[dependencies]\n"); cargo_toml.push_str("core-interface = { path = \"../core-interface\" }\n"); cargo_toml.push_str("board-pc = { path = \"../boards/pc\" }\n"); @@ -198,8 +208,14 @@ impl TargetBuilder for Builder { )); let v = |name: &str| crate::ws_dep_version(&config.workspace_deps, name); cargo_toml.push_str(&format!("embassy-executor = {{ version = \"{}\", features = [\"platform-std\", \"executor-thread\"] }}\n", v("embassy-executor"))); - cargo_toml.push_str(&format!("embassy-time = {{ version = \"{}\", features = [\"std\"] }}\n", v("embassy-time"))); - cargo_toml.push_str(&format!("critical-section = {{ version = \"{}\", features = [\"std\"] }}\n", v("critical-section"))); + cargo_toml.push_str(&format!( + "embassy-time = {{ version = \"{}\", features = [\"std\"] }}\n", + v("embassy-time") + )); + cargo_toml.push_str(&format!( + "critical-section = {{ version = \"{}\", features = [\"std\"] }}\n", + v("critical-section") + )); cargo_toml.push_str("env_logger = \"0.11\"\n"); cargo_toml.push_str(&format!("log = \"{}\"\n", v("log"))); @@ -232,9 +248,7 @@ impl TargetBuilder for Builder { let paired_phones_file = escape_rust_string(&pc_hw.ble.paired_phones_file); if pc_hw.ble.max_bonded_phones == 0 || pc_hw.ble.http_port == 0 { - eprintln!( - "[hardware.pc.ble].max_bonded_phones and http_port must be > 0" - ); + eprintln!("[hardware.pc.ble].max_bonded_phones and http_port must be > 0"); exit(1); } @@ -287,8 +301,7 @@ impl TargetBuilder for Builder { .spawn(board_pc::ble_http_task(BLE_HTTP_BIND, BLE_HTTP_PORT, BLE_DEVICE_NAME_BASE, BLE_PAIRING_WINDOW_S).unwrap());\n" .to_string(); - let mqtt_driver_spawn = - " core_interface::set_mqtt_client_id(MQTT_CLIENT_ID);\n\ + let mqtt_driver_spawn = " core_interface::set_mqtt_client_id(MQTT_CLIENT_ID);\n\ \x20 spawner\n\ .spawn(board_pc::mqtt_driver_task(\n\ MQTT_BROKER_HOST,\n\ @@ -299,7 +312,8 @@ impl TargetBuilder for Builder { MQTT_USERNAME,\n\ MQTT_PASSWORD,\n\ MQTT_TLS,\n\ - ).unwrap());\n".to_string(); + ).unwrap());\n" + .to_string(); let can_logger = &config.network.can_logger; let can_logger_spawn = if can_logger.enabled { @@ -311,6 +325,21 @@ impl TargetBuilder for Builder { String::new() }; + let lan = &config.network.lan; + if lan.port == Some(0) { + eprintln!("[network.lan].port must be > 0"); + exit(1); + } + let lan_spawn = if lan.enabled { + format!( + " spawner.spawn(board_pc::lan_task({port}, BLE_DEVICE_NAME_BASE, {mdns}).unwrap());\n", + port = lan.port_expr(), + mdns = lan.mdns, + ) + } else { + String::new() + }; + let template = fs::read_to_string("boards/pc/main.template.rs") .expect("\u{274c} Could not read boards/pc/main.template.rs"); let main_rs = template @@ -322,15 +351,22 @@ impl TargetBuilder for Builder { .replace("{NETWORK_CONSTANTS}", &network_constants) .replace("{MQTT_DRIVER_SPAWN}", &mqtt_driver_spawn) .replace("{CAN_LOGGER_SPAWN}", &can_logger_spawn) + .replace("{LAN_SPAWN}", &lan_spawn) .replace("{BUILD_KIND_INIT}", &crate::build_kind_init(config)); fs::create_dir_all(".app_build/src").expect("Failed to create .app_build/src"); - fs::write(".app_build/Cargo.toml", cargo_toml).expect("Failed to write .app_build/Cargo.toml"); - fs::write(".app_build/src/main.rs", main_rs).expect("Failed to write .app_build/src/main.rs"); + fs::write(".app_build/Cargo.toml", cargo_toml) + .expect("Failed to write .app_build/Cargo.toml"); + fs::write(".app_build/src/main.rs", main_rs) + .expect("Failed to write .app_build/src/main.rs"); } fn compile(&self, _config: &Config, release: bool) { - let profile = if release { "release" } else { "debug (unoptimized)" }; + let profile = if release { + "release" + } else { + "debug (unoptimized)" + }; println!("Compiling the PC simulator ({profile})..."); self.execute_cargo_command("build", release); } diff --git a/config.toml.example b/config.toml.example index 63e7dc4..3910875 100644 --- a/config.toml.example +++ b/config.toml.example @@ -104,6 +104,15 @@ password = "YourPassword" enabled = false port = 23 +# LAN direct: the app connects to the device over TCP on the local network, with no +# server, through the end-to-end encrypted secure channel (docs/lan.md). The device +# answers the UDP discovery probe and, with `mdns`, announces itself over mDNS. PC board +# only for now (ESP builds ignore it). +[network.lan] +enabled = false +# port = 4734 # the contract's port ([lan] tcp_port in transport.toml) when unset +mdns = true + [network.mqtt] # mqtts:// is MQTT over TLS (port 8883 by default): the broker's certificate is checked # against ca_cert_file and its name. mqtt:// is plain TCP (port 1883): state and the diff --git a/core-interface/build.rs b/core-interface/build.rs index 84e9516..68e0574 100644 --- a/core-interface/build.rs +++ b/core-interface/build.rs @@ -14,6 +14,7 @@ fn main() -> Result<()> { generate_ble_transport_constants()?; generate_phone_validation_constants()?; generate_secure_channel_constants()?; + generate_lan_constants()?; Ok(()) } @@ -265,12 +266,14 @@ fn generate_secure_channel_constants() -> Result<()> { let max_session_messages = int("max_session_messages"); let handshake_timeout_ms = int("handshake_timeout_ms"); let max_client_label_bytes = int("max_client_label_bytes"); + let max_handshake_inits_per_second = int("max_handshake_inits_per_second"); assert!( idle_timeout_seconds > 0 && max_session_seconds > 0 && max_session_messages > 0 && handshake_timeout_ms > 0 - && (0..=255).contains(&max_client_label_bytes), + && (0..=255).contains(&max_client_label_bytes) + && max_handshake_inits_per_second > 0, "secure_channel timeouts and limits out of range" ); let prologue_label = string("prologue_label"); @@ -301,7 +304,96 @@ fn generate_secure_channel_constants() -> Result<()> { /// How long a client waits for the handshake response.\n\ pub const HANDSHAKE_TIMEOUT_MS: u64 = {handshake_timeout_ms};\n\ /// Longest client label, in UTF-8 bytes.\n\ - pub const MAX_CLIENT_LABEL_BYTES: usize = {max_client_label_bytes};\n" + pub const MAX_CLIENT_LABEL_BYTES: usize = {max_client_label_bytes};\n\ + /// Handshake inits processed per second at most, all transports together.\n\ + pub const MAX_HANDSHAKE_INITS_PER_SECOND: u32 = {max_handshake_inits_per_second};\n" + ), + ) +} + +/// LAN direct's constants (`[lan]`, docs/lan.md in the contracts), for `lan.rs`. +fn generate_lan_constants() -> Result<()> { + let toml_str = std::fs::read_to_string("../contracts/opencar/core/v1/transport.toml") + .expect("Failed to read contracts/opencar/core/v1/transport.toml"); + let transport: toml::Value = toml::from_str(&toml_str).expect("Failed to parse transport.toml"); + let lan = transport.get("lan").unwrap_or_else(|| { + panic!("transport.toml is missing [lan]; update the contracts submodule") + }); + let int = |table: &toml::Value, path: &str, key: &str| { + table + .get(key) + .and_then(|v| v.as_integer()) + .unwrap_or_else(|| panic!("transport.toml is missing integer {path}.{key}")) + }; + let string = |table: &toml::Value, path: &str, key: &str| { + table + .get(key) + .and_then(|v| v.as_str()) + .unwrap_or_else(|| panic!("transport.toml is missing string {path}.{key}")) + .to_string() + }; + let mdns = lan + .get("mdns") + .expect("transport.toml is missing [lan.mdns]"); + let udp = lan + .get("udp_discovery") + .expect("transport.toml is missing [lan.udp_discovery]"); + let tcp_port = int(lan, "lan", "tcp_port"); + let max_clients = int(lan, "lan", "max_clients"); + let version = int(lan, "lan", "protocol_version"); + let udp_port = int(udp, "lan.udp_discovery", "port"); + let max_replies = int(udp, "lan.udp_discovery", "max_replies_per_second"); + assert!( + (1..=0xFFFF).contains(&tcp_port) && (1..=0xFFFF).contains(&udp_port), + "transport.toml lan ports out of range" + ); + assert!( + (1..=8).contains(&max_clients), + "transport.toml lan.max_clients out of range" + ); + assert!( + (0..=255).contains(&version) && max_replies > 0, + "transport.toml lan.protocol_version or max_replies_per_second out of range" + ); + // The probe and reply layouts are implemented by hand: a change has to change the code. + let probe_magic = string(udp, "lan.udp_discovery", "probe_magic"); + let reply_magic = string(udp, "lan.udp_discovery", "reply_magic"); + assert!( + probe_magic.len() == 4 + && reply_magic.len() == 4 + && int(udp, "lan.udp_discovery", "probe_bytes") == 15 + && int(udp, "lan.udp_discovery", "reply_bytes") == 17, + "transport.toml lan.udp_discovery layout changed; update core_interface::lan" + ); + let service = string(mdns, "lan.mdns", "service"); + let txt_id = string(mdns, "lan.mdns", "txt_key_device_id"); + let txt_version = string(mdns, "lan.mdns", "txt_key_version"); + + let out_dir = std::env::var("OUT_DIR").unwrap(); + std::fs::write( + std::path::Path::new(&out_dir).join("lan.rs"), + format!( + "// @generated — do not edit. Source: contracts/opencar/core/v1/transport.toml\n\ + /// TCP port the device listens on for LAN connections.\n\ + pub const LAN_TCP_PORT: u16 = {tcp_port};\n\ + /// LAN connections the device accepts at once.\n\ + pub const LAN_MAX_CLIENTS: usize = {max_clients};\n\ + /// Version of the discovery formats (mDNS `v`, the probe's version byte).\n\ + pub const LAN_PROTOCOL_VERSION: u8 = {version};\n\ + /// DNS-SD service type the device announces.\n\ + pub const LAN_MDNS_SERVICE: &str = {service:?};\n\ + /// mDNS TXT key of the device key ID.\n\ + pub const LAN_MDNS_TXT_DEVICE_ID: &str = {txt_id:?};\n\ + /// mDNS TXT key of the protocol version.\n\ + pub const LAN_MDNS_TXT_VERSION: &str = {txt_version:?};\n\ + /// UDP port of the discovery probe.\n\ + pub const LAN_UDP_DISCOVERY_PORT: u16 = {udp_port};\n\ + /// First bytes of a discovery probe.\n\ + pub const LAN_PROBE_MAGIC: &[u8; 4] = b{probe_magic:?};\n\ + /// First bytes of a discovery reply.\n\ + pub const LAN_REPLY_MAGIC: &[u8; 4] = b{reply_magic:?};\n\ + /// Discovery replies sent per second at most.\n\ + pub const LAN_MAX_REPLIES_PER_SECOND: u32 = {max_replies};\n" ), ) } diff --git a/core-interface/src/availability.rs b/core-interface/src/availability.rs index da057ac..9446d0a 100644 --- a/core-interface/src/availability.rs +++ b/core-interface/src/availability.rs @@ -94,6 +94,19 @@ pub fn ble_command_availability_at(now_ms: u64) -> Option Option { + let mut availability = command_availability_at(now_ms)?; + if !crate::phone_trust::is_phone_validated(client_id) { + hold_back(&mut availability); + } + Some(availability) +} + /// The last state queued for the app and when, so unchanged states aren't sent more often /// than every [`COMMAND_AVAILABILITY_REPEAT_MS`]. static LAST_PUBLISHED: Mutex< @@ -283,6 +296,8 @@ pub async fn publish_command_availability_task() { let now_ms = Instant::now().as_millis(); publish_command_availability(now_ms); publish_command_availability_mqtt(now_ms); + // LAN sessions compare with what they were last sent when they next send. + crate::lan::notify_availability(); let _ = embassy_futures::select::select(CHANGED.wait(), Timer::after(Duration::from_secs(1))) .await; diff --git a/core-interface/src/can_access.rs b/core-interface/src/can_access.rs index 389f0b2..af8a976 100644 --- a/core-interface/src/can_access.rs +++ b/core-interface/src/can_access.rs @@ -289,8 +289,8 @@ pub fn can_access_state() -> proto::CanAccessState { } /// A BLE state update carrying only the system state with [`can_access_state`], the -/// connected phone's [`crate::phone_access_state`], the device's MQTT client ID and its -/// identity for the secure channel (`identity.rs`). +/// connected phone's [`crate::phone_access_state`], the device's MQTT client ID, its +/// identity for the secure channel (`identity.rs`) and its LAN address (`lan.rs`). pub fn can_access_state_update(timestamp_ms: u64) -> proto::DeviceToApp { proto::DeviceToApp { timestamp_ms, @@ -302,6 +302,7 @@ pub fn can_access_state_update(timestamp_ms: u64) -> proto::DeviceToApp { phone_access: crate::phone_trust::phone_access_state(timestamp_ms), mqtt_client_id: crate::mqtt_client_id().map(Into::into), device_identity: crate::identity::device_identity(), + lan_address: crate::lan::lan_address(), ..Default::default() }), vehicle_state: None, diff --git a/core-interface/src/lan.rs b/core-interface/src/lan.rs new file mode 100644 index 0000000..ab146b3 --- /dev/null +++ b/core-interface/src/lan.rs @@ -0,0 +1,442 @@ +//! LAN direct (docs/lan.md in the contracts): the app connects to the device over TCP on +//! the local network and runs the secure channel (`secure_channel.rs`) on that connection. +//! +//! The board owns the sockets and stays dumb, like for BLE: it asks for a connection slot +//! with [`lan_accept`], strips the 2-byte length prefix and hands each frame to +//! [`lan_receive_frame`], writes back what that returns and what [`lan_next_frame`] (or +//! [`lan_try_next_frame`]) gives it, and closes the socket when [`lan_should_close`] says +//! so or the peer leaves ([`lan_close`]). All the crypto, and what each session is sent, +//! is here: +//! - command responses for a session, queued per connection (never waited on); +//! - the full vehicle state, like BLE (the newest one, overwritten while unsent); +//! - a system state with the session's client's command availability and the device's +//! LAN address, when the session starts, when either changes, and every +//! [`crate::COMMAND_AVAILABILITY_REPEAT_MS`]. +//! +//! It also answers the UDP discovery probe ([`lan_discovery_reply`]) and keeps the address +//! the board reports ([`set_lan_address`]) for `SystemState.lan_address`. + +use alloc::string::String; +use alloc::vec::Vec; +use core::cell::RefCell; + +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::channel::Channel; +use embassy_sync::signal::Signal; +use embassy_time::{Duration, Instant, Timer}; +use portable_atomic::{AtomicU32, Ordering}; + +use crate::proto; +use crate::secure_channel::{ChannelLink, FRAME_HANDSHAKE_RESPONSE, SessionHandle}; + +include!(concat!(env!("OUT_DIR"), "/lan.rs")); + +/// Length of a discovery probe: magic, version, device key ID. +pub const LAN_PROBE_BYTES: usize = 5 + crate::secure_channel::DEVICE_KEY_ID_BYTES; +/// Length of a discovery reply: magic, version, device key ID, TCP port. +pub const LAN_REPLY_BYTES: usize = LAN_PROBE_BYTES + 2; + +/// A LAN connection slot given to the board by [`lan_accept`]. Stale once the slot is +/// closed or given to another connection, even if the board still holds it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LanConnection { + pub slot: usize, + generation: u32, +} + +impl LanConnection { + /// The secure channel link of this connection. + pub fn link(self) -> ChannelLink { + ChannelLink::lan(self.slot) + } +} + +#[derive(Clone, Default)] +struct Slot { + /// 0 while the slot is free. + generation: u32, + opened_ms: u64, + /// The newest vehicle state hasn't been sent yet. + state_due: bool, + /// The system state (availability, address) has to be sent even if unchanged. + system_due: bool, + /// The availability may have changed: compare it with the last one sent. + availability_check: bool, + /// What the last system state carried, the session it went to and when. + last_system: Option<(SessionHandle, proto::SystemState, u64)>, +} + +static SLOTS: Mutex> = + Mutex::new(RefCell::new( + [const { + Slot { + generation: 0, + opened_ms: 0, + state_due: false, + system_due: false, + availability_check: false, + last_system: None, + } + }; LAN_MAX_CLIENTS], + )); + +static NEXT_GENERATION: AtomicU32 = AtomicU32::new(1); + +/// Command responses for each connection's sessions, for [`lan_next_frame`] to seal. +static LAN_TX: [Channel; + LAN_MAX_CLIENTS] = [const { Channel::new() }; LAN_MAX_CLIENTS]; + +/// Wakes a connection's [`lan_next_frame`]: something may be ready to send. +static LAN_WAKE: [Signal; LAN_MAX_CLIENTS] = + [const { Signal::new() }; LAN_MAX_CLIENTS]; + +static LAN_ADDRESS: Mutex>> = + Mutex::new(RefCell::new(None)); + +fn is_current(conn: LanConnection) -> bool { + conn.slot < LAN_MAX_CLIENTS + && SLOTS.lock(|slots| slots.borrow()[conn.slot].generation == conn.generation) +} + +/// Ends whatever the slot held: its sessions, its queue, and the board's handle to it. +fn free_slot(slot: usize) { + SLOTS.lock(|slots| slots.borrow_mut()[slot] = Slot::default()); + crate::secure_channel::close_link(ChannelLink::lan(slot)); + while LAN_TX[slot].try_receive().is_ok() {} + LAN_WAKE[slot].signal(()); +} + +/// A slot for a new TCP connection at `now_ms`: a free one, else one whose connection has +/// no open session yet (that connection is closed: its [`LanConnection`] goes stale). `None` +/// when every connection has a session: refuse the new one, so nobody on the LAN can push +/// a connected phone off. +pub fn lan_accept(now_ms: u64) -> Option { + let free = SLOTS.lock(|slots| slots.borrow().iter().position(|s| s.generation == 0)); + let slot = match free { + Some(slot) => slot, + None => { + let slot = (0..LAN_MAX_CLIENTS).find(|&slot| { + !crate::secure_channel::has_open_session(ChannelLink::lan(slot), now_ms) + })?; + free_slot(slot); + slot + } + }; + let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed).max(1); + SLOTS.lock(|slots| { + slots.borrow_mut()[slot] = Slot { + generation, + opened_ms: now_ms, + ..Slot::default() + } + }); + Some(LanConnection { slot, generation }) +} + +/// The board closed the connection (the peer left, or [`lan_should_close`]): ends its +/// sessions and frees the slot. Nothing happens if the handle is already stale. +pub fn lan_close(conn: LanConnection) { + if is_current(conn) { + free_slot(conn.slot); + } +} + +/// Whether the board should close the connection at `now_ms`: its slot was taken back, +/// it hasn't completed a handshake within [`crate::HANDSHAKE_TIMEOUT_MS`], or its sessions +/// all ended (idle, expired, revoked). +pub fn lan_should_close(conn: LanConnection, now_ms: u64) -> bool { + let Some(opened_ms) = SLOTS.lock(|slots| { + let slots = slots.borrow(); + (slots[conn.slot].generation == conn.generation).then_some(slots[conn.slot].opened_ms) + }) else { + return true; + }; + now_ms.saturating_sub(opened_ms) >= crate::secure_channel::HANDSHAKE_TIMEOUT_MS + && !crate::secure_channel::has_open_session(conn.link(), now_ms) +} + +/// Whether a frame with this length prefix is acceptable; anything else closes the +/// connection (docs/lan.md). +pub fn lan_frame_length_ok(length: usize) -> bool { + (1..=crate::secure_channel::MAX_FRAME_BYTES).contains(&length) +} + +/// Hands one frame received on `conn` (without its length prefix) to the secure channel +/// and the dispatcher. Returns the frame to send back, if any. A new session is sent the +/// system state and the latest vehicle state next. +pub async fn lan_receive_frame(conn: LanConnection, frame: &[u8]) -> Option> { + if !is_current(conn) { + return None; + } + let reply = crate::secure_channel::process_secure_frame(conn.link(), frame).await?; + if reply.first() == Some(&FRAME_HANDSHAKE_RESPONSE) { + SLOTS.lock(|slots| { + let slot = &mut slots.borrow_mut()[conn.slot]; + slot.system_due = true; + slot.state_due = true; + }); + LAN_WAKE[conn.slot].signal(()); + } + Some(reply) +} + +/// Queues a message for `session` on LAN connection `slot`, from the router. +pub(crate) fn try_queue(slot: usize, session: SessionHandle, msg: proto::DeviceToApp) -> bool { + let Some(channel) = LAN_TX.get(slot) else { + return false; + }; + let queued = channel.try_send((session, msg)).is_ok(); + if queued { + LAN_WAKE[slot].signal(()); + } + queued +} + +/// Marks every open connection, and wakes it. +fn for_each_open(mut mark: impl FnMut(&mut Slot)) { + let open = SLOTS.lock(|slots| { + let mut open = [false; LAN_MAX_CLIENTS]; + for (i, slot) in slots.borrow_mut().iter_mut().enumerate() { + if slot.generation != 0 { + mark(slot); + open[i] = true; + } + } + open + }); + for (i, open) in open.into_iter().enumerate() { + if open { + LAN_WAKE[i].signal(()); + } + } +} + +/// A new vehicle state was published (`routing.rs`). +pub(crate) fn notify_state() { + for_each_open(|slot| slot.state_due = true); +} + +/// The command availability may have changed, or is due again (`availability.rs`). +pub(crate) fn notify_availability() { + for_each_open(|slot| slot.availability_check = true); +} + +/// Sets the address the device accepts LAN connections on (`ip:port`), or `None` while it +/// has none (no listener, no IP). Reported in `SystemState.lan_address` over BLE and to +/// every session whenever it changes. +pub fn set_lan_address(address: Option<&str>) { + let changed = LAN_ADDRESS.lock(|current| { + let mut current = current.borrow_mut(); + if current.as_deref() == address { + return false; + } + *current = address.map(String::from); + true + }); + if changed { + crate::can_access::resend_can_access_state(); + for_each_open(|slot| slot.system_due = true); + } +} + +/// The device's LAN address, as the board reported it. +pub fn lan_address() -> Option { + LAN_ADDRESS.lock(|current| current.borrow().clone()) +} + +/// The system state for a session of `client_id` at `now_ms`, `None` while there is +/// nothing to say (no availability report and no address). +fn system_state_for(client_id: &[u8], now_ms: u64) -> Option { + let state = proto::SystemState { + command_availability: crate::availability::client_command_availability_at( + client_id, now_ms, + ), + lan_address: lan_address(), + ..Default::default() + }; + (state.command_availability.is_some() || state.lan_address.is_some()).then_some(state) +} + +fn system_update(timestamp_ms: u64, state: proto::SystemState) -> proto::DeviceToApp { + proto::DeviceToApp { + timestamp_ms, + platform_id: crate::platform_id(), + payload: Some(proto::device_to_app::Payload::StateUpdate( + proto::StateUpdate { + system_state: Some(state), + vehicle_state: None, + }, + )), + } +} + +/// The system state frame for `session` on `conn`, if one is due: when the session is +/// new or something asked for it, when it changed, and every +/// [`crate::COMMAND_AVAILABILITY_REPEAT_MS`] while it doesn't. +fn next_system_frame( + conn: LanConnection, + session: SessionHandle, + client_id: &[u8], + now_ms: u64, +) -> Option> { + let (forced, check, last) = SLOTS.lock(|slots| { + let slot = &mut slots.borrow_mut()[conn.slot]; + let forced = core::mem::take(&mut slot.system_due); + let check = core::mem::take(&mut slot.availability_check); + (forced, check, slot.last_system.clone()) + }); + let (sent_to, sent, sent_at) = match &last { + Some((sent_to, sent, sent_at)) => (Some(*sent_to), Some(sent), *sent_at), + None => (None, None, 0), + }; + let repeat = sent_to != Some(session) + || now_ms.saturating_sub(sent_at) >= crate::availability::COMMAND_AVAILABILITY_REPEAT_MS; + if !(forced || check || repeat) { + return None; + } + let state = system_state_for(client_id, now_ms)?; + if !(forced || repeat) && sent == Some(&state) { + return None; + } + let (_, frame) = + crate::secure_channel::seal(session, &system_update(now_ms, state.clone()), now_ms)?; + SLOTS.lock(|slots| { + let slot = &mut slots.borrow_mut()[conn.slot]; + if slot.generation == conn.generation { + slot.last_system = Some((session, state, now_ms)); + } + }); + Some(frame) +} + +/// The next frame to send on `conn` at `now_ms`, without waiting: a command response +/// first, then the system state when due, then the newest vehicle state. `None` when there +/// is nothing to send (or the connection is stale). +pub fn lan_try_next_frame(conn: LanConnection, now_ms: u64) -> Option> { + if !is_current(conn) { + return None; + } + while let Ok((session, msg)) = LAN_TX[conn.slot].try_receive() { + if let Some((_, frame)) = crate::secure_channel::seal(session, &msg, now_ms) { + return Some(frame); + } + } + let (session, client_id) = crate::secure_channel::newest_session(conn.link(), now_ms)?; + + if let Some(frame) = next_system_frame(conn, session, &client_id, now_ms) { + return Some(frame); + } + + let state_due = + SLOTS.lock(|slots| core::mem::take(&mut slots.borrow_mut()[conn.slot].state_due)); + if state_due { + let msg = crate::routing::latest_ble_state()?; + return crate::secure_channel::seal(session, &msg, now_ms).map(|(_, frame)| frame); + } + None +} + +/// The next frame to send on `conn`, waiting until there is one. `None` once the +/// connection is stale: the board closes it. +pub async fn lan_next_frame(conn: LanConnection) -> Option> { + loop { + if !is_current(conn) { + return None; + } + if let Some(frame) = lan_try_next_frame(conn, Instant::now().as_millis()) { + return Some(frame); + } + // The timer catches what nothing signals: the availability's repeat, expiry. + let _ = embassy_futures::select::select( + LAN_WAKE[conn.slot].wait(), + Timer::after(Duration::from_secs(1)), + ) + .await; + } +} + +// ── UDP discovery ───────────────────────────────────────────────────────────── + +/// The second (uptime / 1000) of the replies counted, and how many. +static REPLIES: Mutex> = + Mutex::new(RefCell::new((0, 0))); + +fn device_key_id_bytes() -> Option<[u8; crate::secure_channel::DEVICE_KEY_ID_BYTES]> { + let key_id = crate::identity::device_identity()?.key_id; + let hex = key_id.as_bytes(); + let mut out = [0u8; crate::secure_channel::DEVICE_KEY_ID_BYTES]; + if hex.len() != out.len() * 2 { + return None; + } + for (i, byte) in out.iter_mut().enumerate() { + let digit = |c: u8| (c as char).to_digit(16); + *byte = ((digit(hex[2 * i])? << 4) | digit(hex[2 * i + 1])?) as u8; + } + Some(out) +} + +/// The reply to a UDP discovery probe received at `now_ms`, for a device listening on +/// `tcp_port`, or `None` to stay silent: a malformed probe, one for another device, no +/// identity yet, or more than [`LAN_MAX_REPLIES_PER_SECOND`] replies this second. +pub fn lan_discovery_reply( + probe: &[u8], + tcp_port: u16, + now_ms: u64, +) -> Option<[u8; LAN_REPLY_BYTES]> { + if probe.len() != LAN_PROBE_BYTES + || &probe[..4] != LAN_PROBE_MAGIC + || probe[4] != LAN_PROTOCOL_VERSION + { + return None; + } + let key_id = device_key_id_bytes()?; + let wanted = &probe[5..]; + if wanted.iter().any(|&b| b != 0) && wanted != key_id { + return None; + } + let allowed = REPLIES.lock(|replies| { + let mut replies = replies.borrow_mut(); + let second = now_ms / 1_000; + if replies.0 != second { + *replies = (second, 0); + } + if replies.1 >= LAN_MAX_REPLIES_PER_SECOND { + return false; + } + replies.1 += 1; + true + }); + if !allowed { + return None; + } + let mut reply = [0u8; LAN_REPLY_BYTES]; + reply[..4].copy_from_slice(LAN_REPLY_MAGIC); + reply[4] = LAN_PROTOCOL_VERSION; + reply[5..LAN_PROBE_BYTES].copy_from_slice(&key_id); + reply[LAN_PROBE_BYTES..].copy_from_slice(&tcp_port.to_be_bytes()); + Some(reply) +} + +/// The mDNS TXT records the device announces (docs/lan.md): its key ID and the protocol +/// version. `None` while the device has no identity (it isn't reachable over the channel). +pub fn lan_mdns_txt() -> Option<[(&'static str, String); 2]> { + let key_id = crate::identity::device_identity()?.key_id; + Some([ + (LAN_MDNS_TXT_DEVICE_ID, key_id), + ( + LAN_MDNS_TXT_VERSION, + alloc::format!("{LAN_PROTOCOL_VERSION}"), + ), + ]) +} + +/// Frees every slot, forgets the address and the discovery rate. For tests only. +pub fn reset_lan_for_tests() { + for slot in 0..LAN_MAX_CLIENTS { + free_slot(slot); + LAN_WAKE[slot].reset(); + } + LAN_ADDRESS.lock(|current| *current.borrow_mut() = None); + REPLIES.lock(|replies| *replies.borrow_mut() = (0, 0)); +} diff --git a/core-interface/src/lib.rs b/core-interface/src/lib.rs index 403d55f..68d0ec4 100644 --- a/core-interface/src/lib.rs +++ b/core-interface/src/lib.rs @@ -18,6 +18,7 @@ mod dedupe; mod dispatch; mod identity; mod isotp; +mod lan; mod lifecycle; mod mqtt_tls; mod noise; @@ -135,10 +136,11 @@ pub use can_log::{ // Command availability pub use availability::{ COMMAND_AVAILABILITY_REPEAT_MS, CommandKind, REPORT_MAX_AGE_MS, ble_command_availability_at, - command_availability, command_availability_at, command_availability_state_update, - mqtt_command_availability_at, publish_command_availability, publish_command_availability_mqtt, - publish_command_availability_task, report_command_availability, report_command_availability_at, - resend_command_availability, reset_command_availability_for_tests, + client_command_availability_at, command_availability, command_availability_at, + command_availability_state_update, mqtt_command_availability_at, publish_command_availability, + publish_command_availability_mqtt, publish_command_availability_task, + report_command_availability, report_command_availability_at, resend_command_availability, + reset_command_availability_for_tests, }; // Command requirements @@ -166,12 +168,22 @@ pub use noise::initiator::{Initiator, InitiatorSession}; pub use secure_channel::on_handshake_init_for_tests; pub use secure_channel::{ ChannelLink, FRAME_HANDSHAKE_INIT, FRAME_HANDSHAKE_RESPONSE, FRAME_HEADER_BYTES, - FRAME_TRANSPORT, FRAME_UNKNOWN_SESSION, FrameOutcome, HANDSHAKE_TIMEOUT_MS, MAX_FRAME_BYTES, - MAX_PLAINTEXT_BYTES, MAX_SESSION_MESSAGES, MAX_SESSION_MS, MAX_SESSIONS, - MAX_SESSIONS_PER_CLIENT, PROLOGUE_LABEL, REPLAY_WINDOW, SECURE_TX_CHANNEL, SESSION_BYTES, - SESSION_IDLE_TIMEOUT_MS, SessionHandle, TRANSPORT_HEADER_BYTES, close_link, - expire_secure_sessions, is_session_open, on_frame, process_secure_frame, - reset_secure_channel_for_tests, seal, secure_session_count, + FRAME_TRANSPORT, FRAME_UNKNOWN_SESSION, FrameOutcome, HANDSHAKE_TIMEOUT_MS, LinkKind, + MAX_FRAME_BYTES, MAX_HANDSHAKE_INITS_PER_SECOND, MAX_PLAINTEXT_BYTES, MAX_SESSION_MESSAGES, + MAX_SESSION_MS, MAX_SESSIONS, MAX_SESSIONS_PER_CLIENT, PROLOGUE_LABEL, REPLAY_WINDOW, + SECURE_TX_CHANNEL, SESSION_BYTES, SESSION_IDLE_TIMEOUT_MS, SessionHandle, + TRANSPORT_HEADER_BYTES, close_link, expire_secure_sessions, has_open_session, is_session_open, + newest_session, on_frame, process_secure_frame, reset_secure_channel_for_tests, seal, + secure_session_count, +}; + +// LAN direct (the secure channel over TCP on the local network, UDP discovery) +pub use lan::{ + LAN_MAX_CLIENTS, LAN_MAX_REPLIES_PER_SECOND, LAN_MDNS_SERVICE, LAN_MDNS_TXT_DEVICE_ID, + LAN_MDNS_TXT_VERSION, LAN_PROBE_BYTES, LAN_PROBE_MAGIC, LAN_PROTOCOL_VERSION, LAN_REPLY_BYTES, + LAN_REPLY_MAGIC, LAN_TCP_PORT, LAN_UDP_DISCOVERY_PORT, LanConnection, lan_accept, lan_address, + lan_close, lan_discovery_reply, lan_frame_length_ok, lan_mdns_txt, lan_next_frame, + lan_receive_frame, lan_should_close, lan_try_next_frame, reset_lan_for_tests, set_lan_address, }; // Pairing registry diff --git a/core-interface/src/routing.rs b/core-interface/src/routing.rs index 6a41dbc..b2549b1 100644 --- a/core-interface/src/routing.rs +++ b/core-interface/src/routing.rs @@ -264,6 +264,8 @@ pub async fn publish_single_state(payload: VehicleStatePayload, timestamp_ms: u6 let ble_msg = ble_state_update(timestamp_ms, pid, payload); LATEST_BLE_STATE.lock(|latest| *latest.borrow_mut() = Some(ble_msg.clone())); BLE_STATE_TX.signal(ble_msg); + // LAN: the same full state, sealed for each connection's session (`lan.rs`). + crate::lan::notify_state(); // MQTT: basic only (advanced is BLE-exclusive), throttled when no client is active. let now_secs = (timestamp_ms / 1000) as u32; diff --git a/core-interface/src/secure_channel.rs b/core-interface/src/secure_channel.rs index 6262587..f933505 100644 --- a/core-interface/src/secure_channel.rs +++ b/core-interface/src/secure_channel.rs @@ -4,8 +4,11 @@ //! //! Transports stay dumb: they hand every frame they receive to [`process_secure_frame`] //! (or [`on_frame`] and the dispatcher) with the [`ChannelLink`] it came on, send back the -//! reply it returns on that link, report a closed link with [`close_link`], and send what -//! [`SECURE_TX_CHANNEL`] carries after sealing it with [`seal`]. All the crypto is here. +//! reply it returns on that link, and report a closed link with [`close_link`]. Messages for +//! a session go to its LAN connection's queue (`lan.rs`, which seals them), or to +//! [`SECURE_TX_CHANNEL`] for the relay to seal with [`seal`] and send. All the crypto is +//! here. Handshake inits are rate-limited ([`MAX_HANDSHAKE_INITS_PER_SECOND`]) before any +//! X25519 work. //! //! A session is keyed by its session ID and its link. It is RAM-only, ends after //! [`SESSION_IDLE_TIMEOUT_MS`] idle, [`MAX_SESSION_MS`] or [`MAX_SESSION_MESSAGES`] frames, @@ -41,14 +44,44 @@ pub const MAX_FRAME_BYTES: usize = TRANSPORT_HEADER_BYTES + MAX_PLAINTEXT_BYTES /// Handshake inits whose ephemeral key the device remembers, to refuse a replay. const RECENT_EPHEMERALS: usize = 16; +/// The transport carrying a [`ChannelLink`]'s frames, which decides where messages for +/// its sessions go. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LinkKind { + /// A TCP connection on the LAN (`lan.rs`): `connection` is its slot, below + /// [`crate::LAN_MAX_CLIENTS`]. Its messages go to that slot's queue. + Lan, + /// The MQTT relay: its messages go to [`SECURE_TX_CHANNEL`]. + Relay, +} + /// A transport connection carrying frames: a TCP connection on the LAN, the session with /// the broker for the relay. The transport picks the number and reports it closed with /// [`close_link`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ChannelLink { + pub kind: LinkKind, pub connection: u32, } +impl ChannelLink { + /// The LAN connection in `slot`. + pub const fn lan(slot: usize) -> Self { + Self { + kind: LinkKind::Lan, + connection: slot as u32, + } + } + + /// A connection of the relay. + pub const fn relay(connection: u32) -> Self { + Self { + kind: LinkKind::Relay, + connection, + } + } +} + /// An open session, as routing knows it (`Transport::Secure`). Stale once the session /// ends, even if its slot is reused. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -57,9 +90,10 @@ pub struct SessionHandle { generation: u32, } -/// Messages for a session (command responses, for now), for the transport carrying it to -/// [`seal`] and send. Never waited on: a message for a session whose transport doesn't -/// drain it in time is dropped, like on a link that is down. +/// Messages for a relay session (command responses, for now), for the relay to [`seal`] +/// and send. LAN sessions have a queue per connection instead (`lan.rs`). Never waited on: +/// a message for a session whose transport doesn't drain it in time is dropped, like on a +/// link that is down. pub static SECURE_TX_CHANNEL: Channel< CriticalSectionRawMutex, (SessionHandle, proto::DeviceToApp), @@ -139,6 +173,9 @@ struct Sessions { next_generation: u32, recent_ephemerals: [[u8; 32]; RECENT_EPHEMERALS], next_ephemeral: usize, + /// The second (uptime / 1000) of the handshake inits counted in `inits_this_second`. + inits_second: u64, + inits_this_second: u32, } static SESSIONS: Mutex> = @@ -147,6 +184,8 @@ static SESSIONS: Mutex> = next_generation: 1, recent_ephemerals: [[0; 32]; RECENT_EPHEMERALS], next_ephemeral: 0, + inits_second: 0, + inits_this_second: 0, })); impl Sessions { @@ -260,12 +299,34 @@ fn on_handshake_init( message1: &[u8], now_ms: u64, ) -> FrameOutcome { + // Before any X25519 work: anyone who can reach a transport can send inits. + if !take_handshake_budget(now_ms) { + return FrameOutcome::Drop; + } let Some(ephemeral) = fresh_ephemeral() else { return FrameOutcome::Drop; }; on_handshake_init_with(link, session_id, message1, now_ms, ephemeral) } +/// Counts a handshake init against [`MAX_HANDSHAKE_INITS_PER_SECOND`]: whether it may be +/// processed. Over the limit it is dropped unanswered, like one for an unknown key. +fn take_handshake_budget(now_ms: u64) -> bool { + let second = now_ms / 1_000; + SESSIONS.lock(|sessions| { + let mut sessions = sessions.borrow_mut(); + if sessions.inits_second != second { + sessions.inits_second = second; + sessions.inits_this_second = 0; + } + if sessions.inits_this_second >= MAX_HANDSHAKE_INITS_PER_SECOND { + return false; + } + sessions.inits_this_second += 1; + true + }) +} + /// A new ephemeral key from the board's random source. fn fresh_ephemeral() -> Option { let fill = crate::validation::random_source()?; @@ -446,6 +507,41 @@ pub fn expire_secure_sessions(now_ms: u64) { SESSIONS.lock(|sessions| sessions.borrow_mut().prune(now_ms)); } +/// Whether `link` carries a session that is still open. +pub fn has_open_session(link: ChannelLink, now_ms: u64) -> bool { + newest_session(link, now_ms).is_some() +} + +/// The open session on `link` made last, and its client's ID: where a transport sends +/// what isn't an answer (state updates). A client that handshakes again on the same link +/// moves to its new session, and the old one idles out. +pub fn newest_session(link: ChannelLink, now_ms: u64) -> Option<(SessionHandle, Vec)> { + SESSIONS.lock(|sessions| { + let sessions = sessions.borrow(); + sessions + .slots + .iter() + .enumerate() + .filter_map(|(i, s)| s.as_ref().map(|s| (i, s))) + .filter(|(_, s)| s.link == link && !s.expired(now_ms) && s.key_still_enrolled()) + .max_by_key(|(_, s)| (s.created_ms, s.generation)) + .map(|(i, s)| { + ( + SessionHandle { + slot: i as u8, + generation: s.generation, + }, + s.client_id.clone(), + ) + }) + }) +} + +/// The link carrying `session`, while it is open. +fn session_link(session: SessionHandle) -> Option { + SESSIONS.lock(|sessions| sessions.borrow_mut().get(session).map(|s| s.link)) +} + /// Whether `session` is still open, for routing. pub fn is_session_open(session: SessionHandle) -> bool { let now_ms = embassy_time::Instant::now().as_millis(); @@ -476,10 +572,20 @@ pub async fn process_secure_frame(link: ChannelLink, frame: &[u8]) -> Option bool { - is_session_open(session) && SECURE_TX_CHANNEL.try_send((session, msg)).is_ok() + if !is_session_open(session) { + return false; + } + match session_link(session) { + Some(ChannelLink { + kind: LinkKind::Lan, + connection, + }) => crate::lan::try_queue(connection as usize, session, msg), + Some(_) => SECURE_TX_CHANNEL.try_send((session, msg)).is_ok(), + None => false, + } } /// Handles a handshake init with a given device ephemeral key, for the test vectors. For @@ -511,6 +617,8 @@ pub fn reset_secure_channel_for_tests() { sessions.slots = [const { None }; MAX_SESSIONS]; sessions.recent_ephemerals = [[0; 32]; RECENT_EPHEMERALS]; sessions.next_ephemeral = 0; + sessions.inits_second = 0; + sessions.inits_this_second = 0; }); while SECURE_TX_CHANNEL.try_receive().is_ok() {} } diff --git a/core-interface/src/types.rs b/core-interface/src/types.rs index bed243c..286e565 100644 --- a/core-interface/src/types.rs +++ b/core-interface/src/types.rs @@ -9,7 +9,8 @@ pub enum Transport { Ble, Mqtt, /// A session of the secure channel, whichever transport carries its frames (see - /// `secure_channel.rs`). Its messages go to `SECURE_TX_CHANNEL`. + /// `secure_channel.rs`). Its messages go to its LAN connection's queue (`lan.rs`), or to + /// `SECURE_TX_CHANNEL` for the relay. Secure(crate::secure_channel::SessionHandle), } diff --git a/core-interface/tests/lan.rs b/core-interface/tests/lan.rs new file mode 100644 index 0000000..9cee9f2 --- /dev/null +++ b/core-interface/tests/lan.rs @@ -0,0 +1,476 @@ +//! LAN direct (docs/lan.md): connection slots, what a LAN session is sent, the UDP +//! discovery reply and the handshake rate limit. + +use core_interface::{ + BLE_TX_CHANNEL, ChannelLink, CommandKind, FrameOutcome, Initiator, InitiatorSession, + LAN_MAX_CLIENTS, LAN_MAX_REPLIES_PER_SECOND, LAN_PROBE_BYTES, LAN_REPLY_BYTES, LanConnection, + MAX_HANDSHAKE_INITS_PER_SECOND, Transport, VehicleStatePayload, add_paired_phone, + approve_can_read_write, can_access_state_update, clear_paired_phones, confirm_car_fingerprint, + confirm_car_identity, device_identity, handle_ble_message, init, lan_accept, lan_close, + lan_discovery_reply, lan_frame_length_ok, lan_mdns_txt, lan_receive_frame, lan_should_close, + lan_try_next_frame, newest_session, on_frame, proto, publish_single_state, + report_command_availability_at, reset_can_access_for_tests, reset_client_keys_for_tests, + reset_command_availability_for_tests, reset_device_identity_for_tests, reset_lan_for_tests, + reset_latest_ble_state_for_tests, reset_phone_trust_for_tests, + reset_phone_validation_for_tests, reset_secure_channel_for_tests, restore_device_identity, + revoke_car_identity, route_single_response, set_can_dev_write_unlocked, set_can_read_only, + set_lan_address, set_random_source, validate_phone_for_tests, +}; +use embassy_time::Instant; +use prost::Message as _; +use proto::CommandAvailabilityState as State; +use proto::app_to_device::Payload; +use proto::device_to_app::Payload as Out; + +const PLATFORM_ID: u32 = 0xDEAD_BEEF; +const CAR: &[u8] = b"KNAC381AAP5000001"; +const OWNER: &[u8] = b"ble:\x01\x02\x03\x04\x05\x06"; +const SECOND: &[u8] = b"ble:\x0A\x0B\x0C\x0D\x0E\x0F"; +const OWNER_STATIC: [u8; 32] = [0x41; 32]; +const SECOND_STATIC: [u8; 32] = [0x42; 32]; + +fn counting_random(buf: &mut [u8]) { + static NEXT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(1); + for b in buf { + *b = NEXT.fetch_add(7, std::sync::atomic::Ordering::Relaxed); + } +} + +fn next_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +fn now() -> u64 { + Instant::now().as_millis() +} + +fn public(secret: [u8; 32]) -> [u8; 32] { + x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).to_bytes() +} + +fn ephemeral() -> [u8; 32] { + let mut e = [0u8; 32]; + e[1..9].copy_from_slice(&next_id().to_le_bytes()); + e[31] = 0x55; + e +} + +fn enroll(phone: &[u8], client_static: [u8; 32]) { + let msg = proto::AppToDevice { + message_id: next_id(), + platform_id: PLATFORM_ID, + source_device_id: phone.to_vec(), + payload: Some(Payload::SystemCommand(proto::SystemCommand { + action: Some(proto::system_command::Action::EnrollClientKey( + proto::EnrollClientKeyCommand { + public_key: public(client_static).to_vec(), + kind: proto::ClientKind::Phone as i32, + label: "test".into(), + }, + )), + })), + }; + embassy_futures::block_on(handle_ble_message(msg)); + while BLE_TX_CHANNEL.try_receive().is_ok() {} +} + +/// The car identified and read-write, both phones bonded and enrolled, only the owner +/// validated, no LAN connection. +fn boot() { + init(PLATFORM_ID); + revoke_car_identity(); + reset_can_access_for_tests(); + embassy_futures::block_on(clear_paired_phones()); + reset_phone_trust_for_tests(); + reset_phone_validation_for_tests(); + reset_client_keys_for_tests(); + reset_device_identity_for_tests(); + reset_secure_channel_for_tests(); + reset_command_availability_for_tests(); + reset_latest_ble_state_for_tests(); + reset_lan_for_tests(); + set_random_source(counting_random); + assert!(restore_device_identity(&[]).is_some()); + core_interface::set_link_up(Transport::Ble, true); + core_interface::reset_recent_commands_for_tests(); + embassy_futures::block_on(core_interface::reset_ble_controller_lease_for_tests()); + while core_interface::BASIC_CMD_CHANNEL.try_receive().is_ok() {} + for phone in [OWNER, SECOND] { + embassy_futures::block_on(add_paired_phone(phone)); + } + confirm_car_identity(); + assert!(confirm_car_fingerprint(CAR)); + approve_can_read_write().unwrap(); + set_can_dev_write_unlocked(true).unwrap(); + assert!(!set_can_read_only(false)); + assert!(validate_phone_for_tests(OWNER)); + enroll(OWNER, OWNER_STATIC); + enroll(SECOND, SECOND_STATIC); + while BLE_TX_CHANNEL.try_receive().is_ok() {} +} + +struct Client { + conn: LanConnection, + session: InitiatorSession, + session_id: [u8; 4], + counter: u64, +} + +fn prologue() -> Vec { + let mut p = b"opencar/secure/1\0".to_vec(); + p.extend_from_slice(device_identity().unwrap().key_id.as_bytes()); + p +} + +/// Opens a LAN connection and handshakes on it. +fn connect(client_static: [u8; 32]) -> Client { + let conn = lan_accept(now()).expect("no LAN slot"); + handshake(conn, client_static) +} + +fn handshake(conn: LanConnection, client_static: [u8; 32]) -> Client { + let device_key: [u8; 32] = device_identity().unwrap().public_key.try_into().unwrap(); + let (initiator, message1) = + Initiator::start(&prologue(), client_static, ephemeral(), device_key).unwrap(); + let session_id = (next_id() as u32).to_be_bytes(); + let mut frame = vec![1]; + frame.extend_from_slice(&session_id); + frame.extend_from_slice(&message1); + let reply = + embassy_futures::block_on(lan_receive_frame(conn, &frame)).expect("no handshake reply"); + assert_eq!(reply[0], 2); + Client { + conn, + session: initiator.finish(&reply[5..]).unwrap(), + session_id, + counter: 0, + } +} + +impl Client { + fn send(&mut self, msg: &proto::AppToDevice) -> Option> { + let mut frame = vec![3]; + frame.extend_from_slice(&self.session_id); + frame.extend_from_slice(&self.counter.to_be_bytes()); + frame.extend_from_slice(&self.session.encrypt(self.counter, &msg.encode_to_vec())); + self.counter += 1; + embassy_futures::block_on(lan_receive_frame(self.conn, &frame)) + } + + fn open(&self, frame: &[u8]) -> proto::DeviceToApp { + assert_eq!(frame[0], 3); + assert_eq!(frame[1..5], self.session_id); + let counter = u64::from_be_bytes(frame[5..13].try_into().unwrap()); + let plaintext = self.session.decrypt(counter, &frame[13..]).unwrap(); + proto::DeviceToApp::decode(plaintext.as_slice()).unwrap() + } + + /// Everything the device has ready for this connection, opened. + fn receive_all(&self) -> Vec { + let mut out = Vec::new(); + while let Some(frame) = lan_try_next_frame(self.conn, now()) { + out.push(self.open(&frame)); + } + out + } +} + +fn system_states(msgs: &[proto::DeviceToApp]) -> Vec { + msgs.iter() + .filter_map(|m| match &m.payload { + Some(Out::StateUpdate(u)) => u.system_state.clone(), + _ => None, + }) + .collect() +} + +fn vehicle_states(msgs: &[proto::DeviceToApp]) -> Vec { + msgs.iter() + .filter_map(|m| match &m.payload { + Some(Out::StateUpdate(u)) => u.vehicle_state.clone(), + _ => None, + }) + .collect() +} + +fn report_available() { + report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], now()); + report_command_availability_at(CommandKind::Advanced, &[(2, State::Available)], now()); +} + +fn publish_state() { + embassy_futures::block_on(publish_single_state( + VehicleStatePayload { + basic: vec![0x08, 0x01], + advanced: vec![0x10, 0x02], + }, + now(), + )); +} + +// ── Connection slots ────────────────────────────────────────────────────────── + +#[test] +fn a_full_lan_refuses_new_connections_but_replaces_one_without_a_session() { + boot(); + let owner = connect(OWNER_STATIC); + let idle = lan_accept(now()).unwrap(); + assert_eq!(LAN_MAX_CLIENTS, 2, "the test assumes two slots"); + // The idle connection has no session: a new one takes its slot. + let newer = lan_accept(now()).expect("slot of the connection without a session"); + assert_eq!(newer.slot, idle.slot); + assert!( + lan_should_close(idle, now()), + "the replaced connection is closed" + ); + assert!(!lan_should_close(owner.conn, now())); + // Both connections have sessions: the next one is refused. + let _second = handshake(newer, SECOND_STATIC); + assert_eq!(lan_accept(now()), None); + // Once a connection closes, its slot is free again. + lan_close(owner.conn); + assert!(newest_session(owner.conn.link(), now()).is_none()); + assert!(lan_accept(now()).is_some()); +} + +#[test] +fn a_connection_without_a_handshake_is_closed_after_the_handshake_timeout() { + boot(); + let opened = now(); + let conn = lan_accept(opened).unwrap(); + assert!(!lan_should_close(conn, opened + 1)); + assert!(lan_should_close( + conn, + opened + core_interface::HANDSHAKE_TIMEOUT_MS + )); +} + +#[test] +fn frame_lengths_outside_one_frame_close_the_connection() { + assert!(!lan_frame_length_ok(0)); + assert!(lan_frame_length_ok(1)); + assert!(lan_frame_length_ok(core_interface::MAX_FRAME_BYTES)); + assert!(!lan_frame_length_ok(core_interface::MAX_FRAME_BYTES + 1)); +} + +#[test] +fn frames_from_a_link_that_is_not_lan_never_reach_a_lan_connection() { + boot(); + let owner = connect(OWNER_STATIC); + assert!(newest_session(ChannelLink::relay(owner.conn.slot as u32), now()).is_none()); +} + +// ── What a session is sent ──────────────────────────────────────────────────── + +#[test] +fn a_new_session_gets_the_system_state_then_the_full_vehicle_state() { + boot(); + report_available(); + set_lan_address(Some("192.168.1.20:4734")); + publish_state(); + let owner = connect(OWNER_STATIC); + let msgs = owner.receive_all(); + let systems = system_states(&msgs); + assert_eq!(systems.len(), 1, "{msgs:?}"); + assert_eq!(systems[0].lan_address.as_deref(), Some("192.168.1.20:4734")); + let availability = systems[0].command_availability.as_ref().unwrap(); + assert_eq!(availability.basic[&1], State::Available as i32); + assert_eq!(availability.advanced[&2], State::Available as i32); + let vehicle = vehicle_states(&msgs); + assert_eq!(vehicle.len(), 1); + assert_eq!(vehicle[0].basic_state_bytes, vec![0x08, 0x01]); + assert_eq!( + vehicle[0].advanced_state_bytes, + vec![0x10, 0x02], + "the LAN gets the full state, like BLE" + ); + // Nothing more until something changes. + assert!(owner.receive_all().is_empty()); + publish_state(); + assert_eq!(vehicle_states(&owner.receive_all()).len(), 1); +} + +#[test] +fn a_phone_that_is_not_validated_is_told_every_command_is_unavailable() { + boot(); + report_available(); + let second = connect(SECOND_STATIC); + let systems = system_states(&second.receive_all()); + let availability = systems[0].command_availability.as_ref().unwrap(); + assert_eq!(availability.basic[&1], State::Unavailable as i32); + assert_eq!(availability.advanced[&2], State::Unavailable as i32); +} + +#[test] +fn an_address_change_reaches_open_sessions_and_ble() { + boot(); + let owner = connect(OWNER_STATIC); + let _ = owner.receive_all(); + set_lan_address(Some("10.0.0.5:4734")); + let systems = system_states(&owner.receive_all()); + assert_eq!(systems.len(), 1); + assert_eq!(systems[0].lan_address.as_deref(), Some("10.0.0.5:4734")); + let Some(Out::StateUpdate(update)) = can_access_state_update(0).payload else { + panic!("no state update"); + }; + assert_eq!( + update.system_state.unwrap().lan_address.as_deref(), + Some("10.0.0.5:4734") + ); +} + +#[test] +fn a_command_over_the_lan_is_dispatched_and_answered_on_its_connection() { + boot(); + let mut owner = connect(OWNER_STATIC); + let _ = owner.receive_all(); + let message_id = next_id(); + let reply = owner.send(&proto::AppToDevice { + message_id, + platform_id: PLATFORM_ID, + source_device_id: b"forged".to_vec(), + payload: Some(Payload::BasicCommandBytes(vec![0x08, 0x01])), + }); + assert_eq!(reply, None); + let cmd = core_interface::BASIC_CMD_CHANNEL.try_receive().unwrap(); + assert_eq!( + cmd.source_device_id, OWNER, + "stamped with the session's phone" + ); + assert!(cmd.authorization.is_some()); + embassy_futures::block_on(route_single_response( + cmd.transport, + proto::CommandResponse { + message_id, + success: true, + ..Default::default() + }, + now(), + )); + let msgs = owner.receive_all(); + assert!( + msgs.iter().any(|m| matches!( + &m.payload, + Some(Out::CommandResponse(r)) if r.message_id == message_id && r.success + )), + "{msgs:?}" + ); +} + +#[test] +fn a_closed_connection_drops_what_was_queued_for_it() { + boot(); + let mut owner = connect(OWNER_STATIC); + let _ = owner.receive_all(); + owner.send(&proto::AppToDevice { + message_id: next_id(), + platform_id: PLATFORM_ID, + source_device_id: vec![], + payload: Some(Payload::BasicCommandBytes(vec![0x08, 0x01])), + }); + let cmd = core_interface::BASIC_CMD_CHANNEL.try_receive().unwrap(); + lan_close(owner.conn); + embassy_futures::block_on(route_single_response( + cmd.transport, + proto::CommandResponse::default(), + now(), + )); + assert_eq!(lan_try_next_frame(owner.conn, now()), None); +} + +// ── Discovery ───────────────────────────────────────────────────────────────── + +fn key_id_bytes() -> Vec { + let key_id = device_identity().unwrap().key_id; + (0..key_id.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&key_id[i..i + 2], 16).unwrap()) + .collect() +} + +fn probe(key_id: &[u8]) -> Vec { + let mut p = b"OCDQ\x01".to_vec(); + p.extend_from_slice(key_id); + p +} + +#[test] +fn the_device_answers_probes_for_itself_or_any_device() { + boot(); + let key_id = key_id_bytes(); + let reply = lan_discovery_reply(&probe(&key_id), 4734, 0).unwrap(); + assert_eq!(reply.len(), LAN_REPLY_BYTES); + assert_eq!(&reply[..5], b"OCDR\x01"); + assert_eq!(&reply[5..15], key_id.as_slice()); + assert_eq!(&reply[15..], &4734u16.to_be_bytes()); + assert_eq!( + lan_discovery_reply(&probe(&[0; 10]), 4734, 0).map(|r| r[5..15].to_vec()), + Some(key_id) + ); +} + +#[test] +fn the_device_ignores_malformed_probes_and_probes_for_another_device() { + boot(); + assert_eq!(lan_discovery_reply(&probe(&[7; 10]), 4734, 0), None); + let good = probe(&[0; 10]); + assert_eq!(good.len(), LAN_PROBE_BYTES); + assert_eq!(lan_discovery_reply(&good[..14], 4734, 0), None); + let mut long = good.clone(); + long.push(0); + assert_eq!(lan_discovery_reply(&long, 4734, 0), None); + let mut magic = good.clone(); + magic[3] = b'R'; + assert_eq!(lan_discovery_reply(&magic, 4734, 0), None); + let mut version = good; + version[4] = 2; + assert_eq!(lan_discovery_reply(&version, 4734, 0), None); +} + +#[test] +fn discovery_replies_are_rate_limited() { + boot(); + let any = probe(&[0; 10]); + for _ in 0..LAN_MAX_REPLIES_PER_SECOND { + assert!(lan_discovery_reply(&any, 4734, 5_000).is_some()); + } + assert_eq!(lan_discovery_reply(&any, 4734, 5_999), None); + assert!(lan_discovery_reply(&any, 4734, 6_000).is_some()); +} + +#[test] +fn mdns_announces_only_the_key_id_and_the_version() { + boot(); + let txt = lan_mdns_txt().unwrap(); + assert_eq!(txt[0], ("id", device_identity().unwrap().key_id)); + assert_eq!(txt[1], ("v", "1".to_string())); +} + +// ── Handshake rate ──────────────────────────────────────────────────────────── + +#[test] +fn handshake_inits_beyond_the_rate_are_dropped_until_the_next_second() { + boot(); + let device_key: [u8; 32] = device_identity().unwrap().public_key.try_into().unwrap(); + let init = || { + let (_, message1) = + Initiator::start(&prologue(), OWNER_STATIC, ephemeral(), device_key).unwrap(); + let mut frame = vec![1]; + frame.extend_from_slice(&(next_id() as u32).to_be_bytes()); + frame.extend_from_slice(&message1); + frame + }; + let link = ChannelLink::relay(1); + for _ in 0..MAX_HANDSHAKE_INITS_PER_SECOND { + assert!(matches!( + on_frame(link, &init(), 10_000), + FrameOutcome::Reply(_) + )); + } + assert_eq!(on_frame(link, &init(), 10_999), FrameOutcome::Drop); + assert!(matches!( + on_frame(link, &init(), 11_000), + FrameOutcome::Reply(_) + )); +} diff --git a/core-interface/tests/secure_channel.rs b/core-interface/tests/secure_channel.rs index 912bf3f..b56bf2c 100644 --- a/core-interface/tests/secure_channel.rs +++ b/core-interface/tests/secure_channel.rs @@ -24,8 +24,8 @@ const OWNER: &[u8] = b"ble:\x01\x02\x03\x04\x05\x06"; const SECOND: &[u8] = b"ble:\x0A\x0B\x0C\x0D\x0E\x0F"; const OWNER_STATIC: [u8; 32] = [0x41; 32]; const SECOND_STATIC: [u8; 32] = [0x42; 32]; -const LAN: ChannelLink = ChannelLink { connection: 1 }; -const RELAY: ChannelLink = ChannelLink { connection: 2 }; +const LAN: ChannelLink = ChannelLink::relay(1); +const RELAY: ChannelLink = ChannelLink::relay(2); fn counting_random(buf: &mut [u8]) { static NEXT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(1); @@ -593,7 +593,7 @@ fn a_client_at_its_limit_replaces_its_idlest_session() { let mut second = connect_at(OWNER_STATIC, RELAY, 10); let other = connect_at(SECOND_STATIC, LAN, 20); assert_eq!(MAX_SESSIONS_PER_CLIENT, 2); - let mut third = connect_at(OWNER_STATIC, ChannelLink { connection: 3 }, 30); + let mut third = connect_at(OWNER_STATIC, ChannelLink::relay(3), 30); assert_eq!(first.send_at(&basic(OWNER), 31), unknown_session(&first)); assert!(matches!( second.send_at(&basic(OWNER), 31), @@ -612,10 +612,10 @@ fn a_full_table_replaces_the_idlest_session() { boot(); assert_eq!(MAX_SESSIONS, 4); let mut clients = vec![ - connect_at(OWNER_STATIC, ChannelLink { connection: 10 }, 0), - connect_at(SECOND_STATIC, ChannelLink { connection: 11 }, 1), - connect_at(OWNER_STATIC, ChannelLink { connection: 12 }, 2), - connect_at(SECOND_STATIC, ChannelLink { connection: 13 }, 3), + connect_at(OWNER_STATIC, ChannelLink::relay(10), 0), + connect_at(SECOND_STATIC, ChannelLink::relay(11), 1), + connect_at(OWNER_STATIC, ChannelLink::relay(12), 2), + connect_at(SECOND_STATIC, ChannelLink::relay(13), 3), ]; // The first one is the idlest unless used: use it. assert!(matches!( @@ -623,7 +623,7 @@ fn a_full_table_replaces_the_idlest_session() { FrameOutcome::Message(..) )); // The owner is at its limit: its idlest (connection 12) is replaced. - let _new = connect_at(OWNER_STATIC, ChannelLink { connection: 14 }, 5); + let _new = connect_at(OWNER_STATIC, ChannelLink::relay(14), 5); assert_eq!( clients[2].send_at(&basic(OWNER), 6), unknown_session(&clients[2]) diff --git a/docs/architecture.md b/docs/architecture.md index e4f425c..bc537b6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -68,8 +68,8 @@ The actual binary entry point. Generated fresh by `xtask` before every build fro | `BASIC_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel (plain MQTT is rejected) | | `ADVANCED_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel | | `CMD_RESP_CHANNEL` | vehicle → core | `(Transport, CommandResponse)` | Transport tag routes response back | -| `SECURE_TX_CHANNEL` | core → transport | `(SessionHandle, DeviceToApp)` | Responses for a [secure channel](#secure-channel) session, for the transport carrying it to `seal`; never waited on | -| `VEHICLE_STATE_CHANNEL` | vehicle → core | `VehicleStatePayload` | BLE gets full; MQTT gets basic only | +| `SECURE_TX_CHANNEL` | core → transport | `(SessionHandle, DeviceToApp)` | Responses for a [secure channel](#secure-channel) session on the relay, for it to `seal`; never waited on. LAN sessions use a queue per connection inside core ([LAN direct](lan.md)) | +| `VEHICLE_STATE_CHANNEL` | vehicle → core | `VehicleStatePayload` | BLE and LAN get full; MQTT gets basic only | | `CAN_RX_CHANNEL` | board → vehicle | `CanFrame` | Hardware-received CAN frame | | `CAN_TX_CHANNELS[bus_id]` | vehicle → board | `CanTxFrame` | Frame to transmit on that CAN bus, with its TX class (one queue per bus; see [CAN bus](can.md#tx-classes)) | | `CAN_LOG_CHANNEL` | board → logger session | `CanLogFrame` | Raw (pre-filter) frames for the SavvyCAN logger, only filled while a client is connected; see [CAN bus](can.md#savvycan-logging) | @@ -99,11 +99,12 @@ The app may resend a command with the same `message_id` after switching transpor ### Secure channel The device side of the end-to-end encrypted channel ([contracts `docs/secure-channel.md`](https://github.com/OpenCarControls/contracts/blob/main/docs/secure-channel.md)): `Noise_IK_25519_ChaChaPoly_BLAKE2s` between an enrolled client and the device, the same on every transport that carries its frames. `noise.rs` implements the handshake (the device is the responder) and the cipher states from the Noise specification on `x25519-dalek`, `chacha20poly1305` and `blake2`, and its tests pass the contracts' `secure-channel-vectors.json` byte for byte. (`clatter`, a `no_std` Noise crate, was considered; the IK pattern alone is short, and doing it directly gives the explicit nonces and the fixed ephemeral keys the vectors need without its generic layers.) Its constants come from `[secure_channel]` in `transport.toml`, generated by the build script. -* **Transports stay dumb.** A transport hands each received frame to `process_secure_frame(link, bytes)` with the `ChannelLink` (a connection number it picks) it came on, sends back the reply it returns on that link, reports a closed connection with `close_link`, and drains `SECURE_TX_CHANNEL`, sealing each message with `seal(session, msg)` (which also gives the link). All the crypto is in `core-interface`. No transport uses it yet: the LAN (firmware#120) and MQTT (firmware#122) transports plug into it. +* **Transports stay dumb.** A transport hands each received frame to `process_secure_frame(link, bytes)` with the `ChannelLink` it came on (its kind, `Lan` or `Relay`, and a connection number), sends back the reply it returns on that link, and reports a closed connection with `close_link`. All the crypto is in `core-interface`. The LAN goes through `lan.rs`, which wraps these per connection and also decides what each session is sent (see [LAN direct](lan.md)); the relay (firmware#122) will drain `SECURE_TX_CHANNEL`, sealing each message with `seal(session, msg)` (which also gives the link). +* **Handshake rate.** At most `MAX_HANDSHAKE_INITS_PER_SECOND` (8) inits are processed per second, all transports together, checked before any X25519 work; the rest are dropped unanswered. * **Handshake.** A valid handshake init from a key in the registry (`client_for_key`, [BLE](ble.md#client-keys)) creates a session and is answered with the handshake response. An unknown key, or a failed handshake, gets no answer, and an init whose ephemeral key was seen recently is refused (a replay). The ephemeral key comes from the board's random source; without it, or without a device identity, the channel is off. * **Sessions** (`secure_channel.rs`) are RAM-only, keyed by session ID and link, at most `MAX_SESSIONS` (4) and `MAX_SESSIONS_PER_CLIENT` (2); a new one replaces the client's idlest session at its limit, else the idlest one. A session ends after `SESSION_IDLE_TIMEOUT_MS` without a valid frame, `MAX_SESSION_MS` after its handshake, after `MAX_SESSION_MESSAGES` frames one way, when its link closes, and when its client's key leaves the registry (checked on every frame and seal). A transport frame for a session the device doesn't have on that link is answered with an unknown session frame. * **Frames.** Transport frames carry an explicit counter (the nonce); a 64-wide replay window drops duplicates and counters too far behind, and is only updated once a frame decrypts. An empty plaintext is a keepalive. -* **Identity and authorization.** Each `AppToDevice` a session carries is stamped with its client's ID (a phone's `ble:` ID) as `source_device_id`, whatever the client put there, and goes to `handle_secure_message`: basic and advanced vehicle commands get the same checks as that phone over BLE (read-only, validated for this car, controller lease) and a `CommandAuthorization`, and their response comes back through the session (`Transport::Secure(SessionHandle)`, routed to `SECURE_TX_CHANNEL`). System commands are dropped: they stay BLE-only. The `MQTT_COMMANDS_AUTHENTICATED` gate only applies to plain MQTT, until MQTT carries only channel frames (firmware#122). +* **Identity and authorization.** Each `AppToDevice` a session carries is stamped with its client's ID (a phone's `ble:` ID) as `source_device_id`, whatever the client put there, and goes to `handle_secure_message`: basic and advanced vehicle commands get the same checks as that phone over BLE (read-only, validated for this car, controller lease) and a `CommandAuthorization`, and their response comes back through the session (`Transport::Secure(SessionHandle)`, routed to its LAN connection's queue, or to `SECURE_TX_CHANNEL` for the relay). System commands are dropped: they stay BLE-only. The `MQTT_COMMANDS_AUTHENTICATED` gate only applies to plain MQTT, until MQTT carries only channel frames (firmware#122). * **Memory.** A session's table entry is about 200 bytes (`SESSION_BYTES`, in a static, not the heap). A handshake only allocates a few small buffers. `seal` builds a frame in one buffer, encrypted in place, and an inbound frame is decrypted into one buffer, so a message costs about its own size on the heap (up to 4 KB for the largest). ### Channel flow @@ -166,6 +167,7 @@ Embassy is used freely inside `core-interface`. Boards adapt to it — not the o ### PC (`board-pc`) * Compiled as `rlib`. `embassy-executor` with `platform-std` + `executor-thread` features, `embassy-time` with `std` feature, and `critical-section` with `std` feature all live in `.app_build`. No `tokio` — embassy's std driver covers timing and critical sections. * CAN is implemented via SocketCAN (`socketcan` crate) using an `#[embassy_executor::task(pool_size = 4)]` per bus. Frame conversion between `socketcan` and `core-interface` types is extracted into `pub(crate) fn socketcan_to_core_frame` / `core_to_socketcan_frame` helpers for unit testing. +* LAN direct (`lan_task`, with `[network.lan] enabled = true`) polls non-blocking std sockets (TCP, the UDP probe) from one Embassy task, and announces over mDNS with `mdns-sd`, which runs its own thread. See [LAN direct](lan.md). * `board-pc` is always `std`. ## `no_std` / test gating pattern diff --git a/docs/lan.md b/docs/lan.md new file mode 100644 index 0000000..999a665 --- /dev/null +++ b/docs/lan.md @@ -0,0 +1,45 @@ +# LAN direct + +LAN direct lets the app reach the device on the local network with no server: it connects over TCP and runs the [secure channel](architecture.md#secure-channel) on that connection. The wire format (port, framing, discovery) is in the contracts' [`docs/lan.md`](https://github.com/OpenCarControls/contracts/blob/main/docs/lan.md); this page is how the firmware implements it. + +## Configuration + +```toml +[network.lan] +enabled = true +# port = 4734 # the contract's port when unset +mdns = true +``` + +Off by default. It is on the PC board only for now; ESP WiFi builds ignore it until firmware#121. An LTE build will never have it (one uplink per build). + +## How it fits together + +`core-interface/src/lan.rs` holds everything but the sockets, so boards stay dumb: + +* **Connection slots.** The board asks `lan_accept(now)` for a slot when a TCP connection arrives. There are `LAN_MAX_CLIENTS` (2) slots. When all are taken, a connection that hasn't completed a handshake loses its slot to the new one; when every connection has a session, the new one is refused, so someone else on the network can't push the phone off. The board closes a connection when `lan_should_close` says so (no handshake within `HANDSHAKE_TIMEOUT_MS`, all its sessions ended, or its slot was taken back) and reports every close with `lan_close`, which ends its sessions. +* **Frames in.** The board strips the 2-byte length prefix (a length of 0 or above `MAX_FRAME_BYTES` closes the connection, `lan_frame_length_ok`) and hands each frame to `lan_receive_frame`, which runs the secure channel and the dispatcher, and returns the handshake response or unknown-session frame to send back. +* **Frames out.** `lan_next_frame` (or `lan_try_next_frame` for a polling board) gives the next sealed frame for a connection, newest session first: command responses (a queue of 4 per connection, never waited on), then a system state with the session's client's command availability and `lan_address` (when the session starts, when either changes, and every 5 s like BLE's), then the newest vehicle state, the full one like BLE's (overwritten while unsent, so state never queues up). A client that handshakes again on the same connection moves to its new session. +* **Permissions** follow the session's client, as on every secure channel transport: a validated phone may send basic and advanced vehicle commands; system commands stay BLE-only. A phone that isn't validated is told every command is unavailable. +* **Address.** The board reports its `ip:port` with `set_lan_address` (and `None` when it has none). It goes out as `SystemState.lan_address` with the CAN access state over BLE, and to every LAN session, whenever it changes. +* **UDP discovery.** The board hands each datagram on `LAN_UDP_DISCOVERY_PORT` to `lan_discovery_reply`, which checks the probe (length, magic, version, a key ID that is this device's or all zero), limits replies to `LAN_MAX_REPLIES_PER_SECOND`, and builds the reply to send back to the sender. +* **mDNS.** `lan_mdns_txt()` gives the TXT records (`id`, the device key ID, and `v`); the board announces `LAN_MDNS_SERVICE` with the BLE name as the instance name, and again when its address changes. Nothing else is announced. + +Nothing is served before the device has an identity: the handshake needs it, and the probe and mDNS name it. + +## PC board + +`board_pc::lan_task(port, name, mdns)` polls a non-blocking `TcpListener`, its connections and a UDP socket from one Embassy task, sleeping 5 ms when nothing moved, so a slow client never blocks the executor thread. It checks its IPv4 address every 30 s (the address the host would use to reach other machines; loopback isn't reported). mDNS uses the `mdns-sd` crate; if it can't start, the UDP probe and a manual address still work. + +## Trying it + +`tools/lan_client.py` plays the app's part. With the PC firmware running the virtual car and `[network.lan] enabled = true`: + +```sh +python3 -m venv .venv && .venv/bin/pip install noiseprotocol==0.3.1 +.venv/bin/python -I tools/lan_client.py setup # pair, approve, validate, enroll (BLE mock) +.venv/bin/python -I tools/lan_client.py discover # the UDP probe +.venv/bin/python -I tools/lan_client.py run --lock # handshake, state, a door lock command +``` + +`setup` asks for the validation code the firmware logs (`the cluster shows the validation code ...`). The client's key and the device's public key are saved in `.lan-client.json` (gitignored). `run` without `--host` finds the device with the probe; it prints the handshake time, what the device sends, and the command's response. diff --git a/tools/__pycache__/lan_client.cpython-313.pyc b/tools/__pycache__/lan_client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..278a991da1a189f44a9b4ae835d4983b6dcab2a3 GIT binary patch literal 24952 zcmd6PdvqJudFKo;Al~5nB~s+@C6bm%iV|f@v?ZAqskcaxL&%hA8HPwmf<*$<0MrAH zYdYQ5q-9r7ZC6n26GM$oOf~L?&gL}q#-~wQ?^Zd@ZUKW1nF%+Ww%+Y(U&of*ZR+jW zv%l{S1^_9@cH2L8uf&Tx_x=99`}@9o@7nDa4(7b4==48q$aj$a{ zCvy@n=??HR&wh2Xj{WLoJ^K}8f&Cg}1N+U9bJ(v@HnLxnY+}D=*@9pF0qcI7Y};>_ z?II@$vO_Y+xl)dtCmH2@$s`v@X1P$Z$VHM>E|zR-IJrc!!!DH^u*;-e*yU0l>@`w8 z>cIA_6Yq=*)19@5_(!aIbmgI+2*ka(gEoc>)GgVR%QdUdFutjN|RI-M9hL>xk zMyZ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 z`UCF|yzl1U>`&C}NfhjzHZGZRFWF{nuN{j*raXTxfkv73QY(yfU;pjqt2uLJvC_`@ z+Ic7*-{NDA{R^f8>G}z8S+82-mb!mVofjw( zl_BTV(QA^~F5i+Sm?Uh|i4;zP{#8aYuori50|zo-`>H^EN+t<xW)$haAVy*y-0 zzT6thTm7;tUX?Lwulbc>LmNb10`dxy{>zz3Jl;3T?wf>KNqsisW#APL`KBKv)?Oh- zzQQTb*hDC&rG@VLgdC~YYCAhNb!-Y%5PYGq)I}CyQAQ^wA-*KR zf2e@ui;PsIUUv?eT3S>Mo6mFcploZ#AKR-#jmg6^-h9SEn4+QJLJ3KDv|9Eg-siL|PUZ=)HeN=*{Sk-7Ja0}Ce zHl^ZGl~qE;6r@79u!%a-GuD34aLbtszTWZQ_i@zKglp%>RwL!+f%n6h>;%$MQq4nm5X% z%ptEM>s^|}?~%m-wLc*j!_63<_6$B1hx!UkYw{5onFyeg$F$~KGr&S3rYd4cV4-ZF z+}p_dbNakV*1sd`$7GSnkG*}HzNaUzr+`|rh_O>|@wHMs0&i6Y@Cdn1kmV!m8ddB5PSzu?Tj;2gi;?CigV`4s;Rx8+yXwkgw6e*KgK%KdOL%TYXK1&amC zVx2NBm6XM}!aEi-Uv;O9=QrFj@%+v^rUJg;&I2aC@J@+=&$*MQ;~(cgwQy$JboZrw zFYUW{AW|Qo z_zizovX-y0>z2ROkt9ZKlS Se=eAQYxgI5PFTZw=l=o;x0$;D literal 0 HcmV?d00001 diff --git a/tools/lan_client.py b/tools/lan_client.py new file mode 100644 index 0000000..7a2b26d --- /dev/null +++ b/tools/lan_client.py @@ -0,0 +1,416 @@ +#!/usr/bin/env python3 +"""A LAN direct test client for the PC firmware (docs/lan.md). + +It plays the app's part on the LAN: finds the device with the UDP probe, connects over +TCP, runs the secure channel handshake (Noise IK) with an enrolled client key, prints +what the device sends, and sends a virtual-car door lock command. + +Setup, once per device identity, goes through the PC board's BLE mock (HTTP): pair, +approve the car, unlock the dev lock (debug builds), validate the phone with the +virtual car's cluster code (read it from the firmware's log), and enroll the key. The +mock identifies the "phone" by the client's IP address. + + python3 -m venv .venv && .venv/bin/pip install noiseprotocol==0.3.1 + .venv/bin/python -I tools/lan_client.py setup # once + .venv/bin/python -I tools/lan_client.py discover + .venv/bin/python -I tools/lan_client.py run [--host 127.0.0.1] [--lock | --unlock] + +The client's key and the device's public key are kept in `.lan-client.json` (or +`--state`), which is gitignored. +""" + +import argparse +import json +import os +import secrets +import socket +import struct +import sys +import time +import urllib.request + +from noise.connection import Keypair, NoiseConnection + +PROTOCOL = b"Noise_IK_25519_ChaChaPoly_BLAKE2s" +PROLOGUE_LABEL = b"opencar/secure/1" +TCP_PORT = 4734 +UDP_PORT = 4735 +PROBE_MAGIC = b"OCDQ" +REPLY_MAGIC = b"OCDR" +VERSION = 1 +HANDSHAKE_TIMEOUT_S = 10 + +# ── Protobuf, by hand (only the fields this client needs) ─────────────────── + + +def varint(n): + out = bytearray() + while True: + b = n & 0x7F + n >>= 7 + if n: + out.append(b | 0x80) + else: + out.append(b) + return bytes(out) + + +def field_varint(num, value): + return varint(num << 3) + varint(value) + + +def field_bytes(num, value): + return varint((num << 3) | 2) + varint(len(value)) + value + + +def parse(data): + """Decodes one message into {field number: [values]} (bytes for length-delimited).""" + fields, i = {}, 0 + while i < len(data): + key, i = read_varint(data, i) + num, wire = key >> 3, key & 7 + if wire == 0: + value, i = read_varint(data, i) + elif wire == 2: + length, i = read_varint(data, i) + value, i = data[i : i + length], i + length + elif wire == 1: + value, i = data[i : i + 8], i + 8 + elif wire == 5: + value, i = data[i : i + 4], i + 4 + else: + raise ValueError(f"wire type {wire}") + fields.setdefault(num, []).append(value) + return fields + + +def read_varint(data, i): + shift = value = 0 + while True: + b = data[i] + i += 1 + value |= (b & 0x7F) << shift + if not b & 0x80: + return value, i + shift += 7 + + +def app_to_device(message_id, platform_id, payload_field, payload): + return ( + field_varint(1, message_id) + + field_varint(2, platform_id) + + field_bytes(payload_field, payload) + ) + + +def system_command(platform_id, action_field, action): + """AppToDevice.system_command (3) with SystemCommand..""" + return app_to_device(next_id(), platform_id, 3, field_bytes(action_field, action)) + + +_next = int(time.time() * 1000) + + +def next_id(): + global _next + _next += 1 + return _next + + +def describe(msg): + """A one-line summary of a DeviceToApp.""" + d = parse(msg) + if 4 in d: + r = parse(d[4][0]) + ok = bool(r.get(2, [0])[0]) + err = r.get(3, [b""])[0].decode(errors="replace") + return f"command response {r.get(1, [0])[0]}: {'ok' if ok else 'failed'} {err}".strip() + if 3 in d: + u = parse(d[3][0]) + parts = [] + if 1 in u: + s = parse(u[1][0]) + if 6 in s: + a = parse(s[6][0]) + parts.append(f"availability basic={len(a.get(1, []))} advanced={len(a.get(2, []))}") + if 11 in s: + parts.append(f"lan_address={s[11][0].decode()}") + if 10 in s: + parts.append("device_identity") + if 2 in u: + v = parse(u[2][0]) + parts.append( + f"vehicle state basic={len(v.get(1, [b''])[0])}B advanced={len(v.get(2, [b''])[0])}B" + ) + return "state update: " + ", ".join(parts) + return f"message {sorted(d)}" + + +# ── Setup through the BLE mock ────────────────────────────────────────────── + + +def http(base, method, path, body=None): + req = urllib.request.Request(base + path, data=body, method=method) + with urllib.request.urlopen(req, timeout=5) as resp: + return resp.status, resp.read() + + +def drain_mock(base, seconds=1.0): + """Everything the mock's BLE side has queued, as DeviceToApp bytes.""" + out, end = [], time.time() + seconds + while time.time() < end: + status, body = http(base, "GET", "/state") + if status == 200: + out.append(body) + else: + time.sleep(0.1) + return out + + +def setup(args): + base = f"http://{args.mock}" + state = load_state(args.state) + private = bytes.fromhex(state["client_private"]) if "client_private" in state else secrets.token_bytes(32) + public = public_key(private) + + msgs = drain_mock(base, 0.5) + platform_id = next((parse(m)[2][0] for m in msgs if 2 in parse(m)), None) + print("Opening the pairing window and pairing…") + http(base, "POST", "/pairing") + http(base, "POST", "/pair") + if platform_id is None: + msgs = drain_mock(base, 2) + platform_id = next((parse(m)[2][0] for m in msgs if 2 in parse(m)), None) + if platform_id is None: + sys.exit("No message from the device: is the PC firmware running with the virtual car?") + + def send(cmd): + http(base, "POST", "/cmd", cmd) + return [describe(m) for m in drain_mock(base, 1)] + + print("Approving the car:", send(system_command(platform_id, 8, field_varint(1, 1)))) + print("Unlocking the dev lock:", send(system_command(platform_id, 9, field_varint(1, 1)))) + print("Starting validation:", send(system_command(platform_id, 11, field_bytes(1, b"virtual_car.cluster_code")))) + code = input("Validation code from the firmware's log ('the cluster shows the validation code …'): ").strip() + print("Submitting it:", send(system_command(platform_id, 12, field_bytes(1, code.encode())))) + + enroll = field_bytes(1, public) + field_varint(2, 1) + field_bytes(3, b"lan_client.py") + http(base, "POST", "/cmd", system_command(platform_id, 14, enroll)) + identity = None + for m in drain_mock(base, 2): + d = parse(m) + print(" ", describe(m)) + for found in find_identities(d): + identity = found + if identity is None: + sys.exit("The device didn't report its identity: was the phone validated?") + state.update( + client_private=private.hex(), + device_public=identity[0].hex(), + device_key_id=identity[1], + platform_id=platform_id, + ) + save_state(args.state, state) + print(f"Enrolled. Device key ID {identity[1]}; saved to {args.state}") + + +def find_identities(d): + """DeviceIdentity (public key, key ID) in a DeviceToApp: in a system state or in a + SystemCommandResult.""" + found = [] + if 3 in d: + u = parse(d[3][0]) + if 1 in u: + s = parse(u[1][0]) + if 10 in s: + found.append(s[10][0]) + if 4 in d: + r = parse(d[4][0]) + if 8 in r: + result = parse(r[8][0]) + if 5 in result: + found.append(result[5][0]) + out = [] + for raw in found: + i = parse(raw) + out.append((i[1][0], i[2][0].decode())) + return out + + +def public_key(private): + conn = NoiseConnection.from_name(PROTOCOL) + conn.set_keypair_from_private_bytes(Keypair.STATIC, private) + return conn.noise_protocol.keypairs["s"].public_bytes + + +def load_state(path): + try: + with open(path) as f: + return json.load(f) + except FileNotFoundError: + return {} + + +def save_state(path, state): + with open(path, "w") as f: + json.dump(state, f, indent=2) + os.chmod(path, 0o600) + + +# ── Discovery ─────────────────────────────────────────────────────────────── + + +def probe(key_id_hex=None, target="255.255.255.255", timeout=1.0): + key_id = bytes.fromhex(key_id_hex) if key_id_hex else bytes(10) + packet = PROBE_MAGIC + bytes([VERSION]) + key_id + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + sock.settimeout(0.2) + found = {} + for _ in range(3): + sock.sendto(packet, (target, UDP_PORT)) + end = time.time() + 0.5 + while time.time() < end: + try: + data, (host, _) = sock.recvfrom(64) + except socket.timeout: + continue + if len(data) == 17 and data[:4] == REPLY_MAGIC and data[4] == VERSION: + found[data[5:15].hex()] = (host, struct.unpack(">H", data[15:17])[0]) + time.sleep(timeout) + return found + + +def discover(args): + found = probe(target=args.target) + if not found: + print("No device answered (client isolation, or the firmware isn't running with LAN).") + for key_id, (host, port) in found.items(): + print(f"{key_id} at {host}:{port}") + + +# ── The channel ───────────────────────────────────────────────────────────── + + +class Channel: + def __init__(self, sock, conn, session_id): + self.sock, self.conn, self.session_id = sock, conn, session_id + self.counter = 0 + self.buf = b"" + + def send(self, plaintext): + ct = self.conn.encrypt(plaintext) + frame = b"\x03" + self.session_id + struct.pack(">Q", self.counter) + ct + self.counter += 1 + self.sock.sendall(struct.pack(">H", len(frame)) + frame) + + def receive(self, timeout): + """The next frame's plaintext, or None after `timeout` seconds.""" + self.sock.settimeout(timeout) + while True: + if len(self.buf) >= 2: + length = struct.unpack(">H", self.buf[:2])[0] + if len(self.buf) >= 2 + length: + frame, self.buf = self.buf[2 : 2 + length], self.buf[2 + length :] + if frame[0] == 5: + raise RuntimeError("unknown session: the device restarted") + return self.conn.decrypt(frame[13:]) + try: + chunk = self.sock.recv(4096) + except socket.timeout: + return None + if not chunk: + raise RuntimeError("the device closed the connection") + self.buf += chunk + + +def connect(host, port, state): + sock = socket.create_connection((host, port), timeout=3) + conn = NoiseConnection.from_name(PROTOCOL) + conn.set_as_initiator() + conn.set_keypair_from_private_bytes(Keypair.STATIC, bytes.fromhex(state["client_private"])) + conn.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC, bytes.fromhex(state["device_public"])) + conn.set_prologue(PROLOGUE_LABEL + b"\x00" + state["device_key_id"].encode()) + conn.start_handshake() + session_id = secrets.token_bytes(4) + frame = b"\x01" + session_id + conn.write_message() + started = time.time() + sock.sendall(struct.pack(">H", len(frame)) + frame) + sock.settimeout(HANDSHAKE_TIMEOUT_S) + try: + header = recv_exact(sock, 2) + reply = recv_exact(sock, struct.unpack(">H", header)[0]) + except (socket.timeout, RuntimeError): + sys.exit("No handshake response: the key isn't enrolled, or this isn't the device.") + if reply[0] != 2 or reply[1:5] != session_id: + sys.exit(f"Unexpected handshake reply {reply[:5].hex()}") + conn.read_message(reply[5:]) + print(f"Handshake done in {(time.time() - started) * 1000:.0f} ms") + return Channel(sock, conn, session_id) + + +def recv_exact(sock, n): + data = b"" + while len(data) < n: + chunk = sock.recv(n - len(data)) + if not chunk: + raise RuntimeError("closed") + data += chunk + return data + + +def run(args): + state = load_state(args.state) + if "client_private" not in state: + sys.exit(f"No enrolled key in {args.state}: run `setup` first.") + host, port = args.host, args.port + if host is None: + found = probe(state["device_key_id"]) + if state["device_key_id"] not in found: + sys.exit("The device didn't answer the probe; pass --host.") + host, port = found[state["device_key_id"]] + print(f"Found {state['device_key_id']} at {host}:{port}") + channel = connect(host, port, state) + platform_id = state["platform_id"] + + end = time.time() + 2 + while time.time() < end: + msg = channel.receive(0.5) + if msg: + print("<", describe(msg)) + if args.lock is not None: + message_id = next_id() + # virtual-car BasicCommand.door_lock (1) = DoorLockCommand { lock (1) }. + command = field_bytes(1, field_varint(1, 1 if args.lock else 0)) + channel.send(app_to_device(message_id, platform_id, 4, command)) + print(f"> door {'lock' if args.lock else 'unlock'} ({message_id})") + end = time.time() + args.listen + while time.time() < end: + msg = channel.receive(0.5) + if msg: + print("<", describe(msg)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--state", default=".lan-client.json") + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("setup", help="pair, validate and enroll through the BLE mock") + p.add_argument("--mock", default="127.0.0.1:4242", help="the BLE mock's HTTP address") + p.set_defaults(func=setup) + p = sub.add_parser("discover", help="send the UDP probe") + p.add_argument("--target", default="255.255.255.255") + p.set_defaults(func=discover) + p = sub.add_parser("run", help="connect, read the state, send a command") + p.add_argument("--host") + p.add_argument("--port", type=int, default=TCP_PORT) + p.add_argument("--lock", dest="lock", action="store_true", default=None) + p.add_argument("--unlock", dest="lock", action="store_false") + p.add_argument("--listen", type=float, default=3, help="seconds to keep printing") + p.set_defaults(func=run) + args = parser.parse_args() + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3d6f1dc..25dbe98 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -118,9 +118,49 @@ pub struct NetworkConfig { #[serde(default)] pub can_logger: CanLoggerConfig, #[serde(default)] + pub lan: LanConfig, + #[serde(default)] pub lte: LteConfig, } +/// LAN direct: the app connects to the device over TCP on the local network, through the +/// secure channel (docs/lan.md). Off by default. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LanConfig { + #[serde(default)] + pub enabled: bool, + /// The TCP port; the contract's (`[lan] tcp_port`) when unset. + pub port: Option, + /// Announce the device over mDNS. The UDP probe and a manual address work without it. + #[serde(default = "lan_mdns_default")] + pub mdns: bool, +} + +impl Default for LanConfig { + fn default() -> Self { + Self { + enabled: false, + port: None, + mdns: lan_mdns_default(), + } + } +} + +fn lan_mdns_default() -> bool { + true +} + +impl LanConfig { + /// The port as a Rust expression for a generated `main.rs`. + pub fn port_expr(&self) -> String { + match self.port { + Some(port) => port.to_string(), + None => "core_interface::LAN_TCP_PORT".into(), + } + } +} + /// LTE uplink settings: the SIM's, not the board's (the modem's wiring is in the /// board's `[hardware..modem]`). Off by default. #[derive(Deserialize, Default)] From 3b7bc4aa429baa5b556739c238755c5aa8c482d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 19:42:48 +0000 Subject: [PATCH 3/6] test(lan): enroll the second phone while it is validated Enrolling a client key needs a validated phone, so the LAN tests validate both phones, enroll them, then end the validations by approving another car, like the secure channel tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- core-interface/tests/lan.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/core-interface/tests/lan.rs b/core-interface/tests/lan.rs index 9cee9f2..151f613 100644 --- a/core-interface/tests/lan.rs +++ b/core-interface/tests/lan.rs @@ -24,6 +24,7 @@ use proto::device_to_app::Payload as Out; const PLATFORM_ID: u32 = 0xDEAD_BEEF; const CAR: &[u8] = b"KNAC381AAP5000001"; +const OTHER_CAR: &[u8] = b"KNAC381AAP5000002"; const OWNER: &[u8] = b"ble:\x01\x02\x03\x04\x05\x06"; const SECOND: &[u8] = b"ble:\x0A\x0B\x0C\x0D\x0E\x0F"; const OWNER_STATIC: [u8; 32] = [0x41; 32]; @@ -104,9 +105,18 @@ fn boot() { approve_can_read_write().unwrap(); set_can_dev_write_unlocked(true).unwrap(); assert!(!set_can_read_only(false)); + // Enrolling needs a validated phone. Approving another car ends every validation but + // keeps the keys; back in this car only the owner validates again. assert!(validate_phone_for_tests(OWNER)); + assert!(validate_phone_for_tests(SECOND)); enroll(OWNER, OWNER_STATIC); enroll(SECOND, SECOND_STATIC); + assert!(confirm_car_fingerprint(OTHER_CAR)); + approve_can_read_write().unwrap(); + assert!(confirm_car_fingerprint(CAR)); + approve_can_read_write().unwrap(); + assert!(!set_can_read_only(false)); + assert!(validate_phone_for_tests(OWNER)); while BLE_TX_CHANNEL.try_receive().is_ok() {} } From 1289f3cd6d220fa4e116f9dc26065a9105f5cad3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 01:54:29 +0000 Subject: [PATCH 4/6] chore: pin contracts to the LAN remote tier and receive timeout (contracts#52) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- contracts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts b/contracts index ac2fcad..b101725 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit ac2fcad4982c6d77f49456840f95c2ba729dc6ef +Subproject commit b101725f088938055630975be8e1858ac3d998e2 From a7bb7fe7958b7a77f4940047bdd096c1958876c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 01:56:07 +0000 Subject: [PATCH 5/6] feat(lan): make the LAN the remote tier - A secure channel session gets the basic vehicle state only, and its client's advanced commands are reported unavailable and refused with REJECTED_UNAVAILABLE: reaching the device over a network is no proof of being at the car. - The system state repeats every LAN_SYSTEM_STATE_REPEAT_MS (from the contract), which the app's receive timeout relies on. - lan_mdns_instance_name: the BLE name and the key ID's first four characters, so the PC board announces the same name as the ESP. - lan_is_open, for the boards' logs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- boards/pc/src/lan.rs | 11 +++- core-interface/build.rs | 7 +++ core-interface/src/availability.rs | 11 +++- core-interface/src/dispatch.rs | 43 ++++++++++++--- core-interface/src/lan.rs | 46 ++++++++++++++-- core-interface/src/lib.rs | 7 ++- core-interface/tests/lan.rs | 76 +++++++++++++++++++++----- core-interface/tests/secure_channel.rs | 13 ++++- docs/architecture.md | 4 +- docs/commands.md | 2 +- docs/lan.md | 6 +- 11 files changed, 182 insertions(+), 44 deletions(-) diff --git a/boards/pc/src/lan.rs b/boards/pc/src/lan.rs index d382a16..d5b4a70 100644 --- a/boards/pc/src/lan.rs +++ b/boards/pc/src/lan.rs @@ -82,18 +82,23 @@ impl Mdns { if let Some(fullname) = self.registered.take() { let _ = daemon.unregister(&fullname); } - let (Some(ip), Some(txt)) = (ip, core_interface::lan_mdns_txt()) else { + let (Some(ip), Some(txt), Some(instance)) = ( + ip, + core_interface::lan_mdns_txt(), + core_interface::lan_mdns_instance_name(name), + ) else { return; }; let service = format!("{}.local.", core_interface::LAN_MDNS_SERVICE); let host = format!("opencar-{}.local.", txt[0].1); - let info = mdns_sd::ServiceInfo::new(&service, name, &host, IpAddr::V4(ip), port, &txt[..]); + let info = + mdns_sd::ServiceInfo::new(&service, &instance, &host, IpAddr::V4(ip), port, &txt[..]); match info.and_then(|info| { let fullname = info.get_fullname().to_string(); daemon.register(info).map(|()| fullname) }) { Ok(fullname) => { - log::info!("LAN: announced over mDNS as '{name}' ({service})"); + log::info!("LAN: announced over mDNS as '{instance}' ({service})"); self.registered = Some(fullname); } Err(e) => log::warn!("LAN: mDNS announcement failed: {e}"), diff --git a/core-interface/build.rs b/core-interface/build.rs index 68e0574..7f43659 100644 --- a/core-interface/build.rs +++ b/core-interface/build.rs @@ -341,6 +341,11 @@ fn generate_lan_constants() -> Result<()> { let tcp_port = int(lan, "lan", "tcp_port"); let max_clients = int(lan, "lan", "max_clients"); let version = int(lan, "lan", "protocol_version"); + let system_repeat = int(lan, "lan", "system_state_repeat_ms"); + assert!( + system_repeat > 0, + "transport.toml lan.system_state_repeat_ms out of range" + ); let udp_port = int(udp, "lan.udp_discovery", "port"); let max_replies = int(udp, "lan.udp_discovery", "max_replies_per_second"); assert!( @@ -378,6 +383,8 @@ fn generate_lan_constants() -> Result<()> { pub const LAN_TCP_PORT: u16 = {tcp_port};\n\ /// LAN connections the device accepts at once.\n\ pub const LAN_MAX_CLIENTS: usize = {max_clients};\n\ + /// A LAN session gets a system state at least this often (ms), even unchanged.\n\ + pub const LAN_SYSTEM_STATE_REPEAT_MS: u64 = {system_repeat};\n\ /// Version of the discovery formats (mDNS `v`, the probe's version byte).\n\ pub const LAN_PROTOCOL_VERSION: u8 = {version};\n\ /// DNS-SD service type the device announces.\n\ diff --git a/core-interface/src/availability.rs b/core-interface/src/availability.rs index 9446d0a..e118c42 100644 --- a/core-interface/src/availability.rs +++ b/core-interface/src/availability.rs @@ -94,8 +94,10 @@ pub fn ble_command_availability_at(now_ms: u64) -> Option Option { }) } +/// Advanced vehicle commands need Bluetooth: through the secure channel (the LAN, the +/// relay) the client could be anywhere, so only basic commands are accepted there. +fn needs_bluetooth_rejection(message_id: u64) -> proto::DeviceToApp { + proto::DeviceToApp { + timestamp_ms: embassy_time::Instant::now().as_millis(), + platform_id: crate::PLATFORM_ID.load(Ordering::Relaxed), + payload: Some(proto::device_to_app::Payload::CommandResponse( + proto::CommandResponse { + message_id, + success: false, + error_message: String::from( + "command rejected: advanced commands need a Bluetooth connection", + ), + response_data: None, + status_code: proto::CommandStatusCode::RejectedUnavailable as i32, + }, + )), + } +} + /// Vehicle commands also need the sending phone to be validated for this car (see /// `phone_trust.rs`): a phone that only bonded during a pairing window can't act on the car. fn not_validated_rejection(message_id: u64) -> proto::DeviceToApp { @@ -661,11 +681,13 @@ pub async fn process_mqtt_commands_task() { /// Processes a single `AppToDevice` that a secure channel session carried /// (`secure_channel.rs`), already stamped with its client's ID as `source_device_id`. -/// Permissions follow the authenticated client, not the transport: -/// - `basic_command_bytes` / `advanced_command_bytes` → the same checks as the same phone -/// over BLE (read-only, validated for this car, controller lease), then -/// `BASIC_CMD_CHANNEL` / `ADVANCED_CMD_CHANNEL` with the command's authorization. The -/// response goes back through the session (`Transport::Secure`). +/// Every transport that carries the channel is the remote tier: reaching the device over a +/// network is no proof of being at the car. +/// - `basic_command_bytes` → the same checks as the same phone over BLE (read-only, +/// validated for this car, controller lease), then `BASIC_CMD_CHANNEL` with the +/// command's authorization. The response goes back through the session +/// (`Transport::Secure`). +/// - `advanced_command_bytes` → refused with `REJECTED_UNAVAILABLE`: they need Bluetooth. /// - `system_command` → dropped: system commands need physical presence, so BLE only. /// - `heartbeat` → nothing (any frame already keeps the session alive). /// @@ -690,9 +712,14 @@ pub async fn handle_secure_message( if is_duplicate_command(&msg.source_device_id, msg.message_id) { return; } - let bytes = match msg.payload { - Some(proto::app_to_device::Payload::BasicCommandBytes(bytes)) - | Some(proto::app_to_device::Payload::AdvancedCommandBytes(bytes)) => bytes, + let bytes = match (kind, msg.payload) { + (VehicleCommand::Basic, Some(proto::app_to_device::Payload::BasicCommandBytes(bytes))) => { + bytes + } + (VehicleCommand::Advanced, _) => { + send_to(transport, needs_bluetooth_rejection(msg.message_id)).await; + return; + } _ => return, }; dispatch_vehicle_command(transport, kind, msg.message_id, msg.source_device_id, bytes).await; diff --git a/core-interface/src/lan.rs b/core-interface/src/lan.rs index ab146b3..a027bd3 100644 --- a/core-interface/src/lan.rs +++ b/core-interface/src/lan.rs @@ -8,10 +8,11 @@ //! so or the peer leaves ([`lan_close`]). All the crypto, and what each session is sent, //! is here: //! - command responses for a session, queued per connection (never waited on); -//! - the full vehicle state, like BLE (the newest one, overwritten while unsent); +//! - the basic vehicle state only, like MQTT (the newest one, overwritten while unsent): the +//! LAN is the remote tier, being on the network is no proof of being at the car; //! - a system state with the session's client's command availability and the device's //! LAN address, when the session starts, when either changes, and every -//! [`crate::COMMAND_AVAILABILITY_REPEAT_MS`]. +//! [`LAN_SYSTEM_STATE_REPEAT_MS`] (the app's receive timeout relies on it). //! //! It also answers the UDP discovery probe ([`lan_discovery_reply`]) and keeps the address //! the board reports ([`set_lan_address`]) for `SystemState.lan_address`. @@ -99,6 +100,12 @@ fn is_current(conn: LanConnection) -> bool { && SLOTS.lock(|slots| slots.borrow()[conn.slot].generation == conn.generation) } +/// Whether `conn` still holds its slot: `false` once it was closed or taken back for a new +/// connection. For the board's logs; [`lan_should_close`] is what decides. +pub fn lan_is_open(conn: LanConnection) -> bool { + is_current(conn) +} + /// Ends whatever the slot held: its sessions, its queue, and the board's handle to it. fn free_slot(slot: usize) { SLOTS.lock(|slots| slots.borrow_mut()[slot] = Slot::default()); @@ -258,6 +265,16 @@ fn system_state_for(client_id: &[u8], now_ms: u64) -> Option (state.command_availability.is_some() || state.lan_address.is_some()).then_some(state) } +/// `msg` without its advanced state: the LAN gets the basic state only, like MQTT. +fn basic_only(mut msg: proto::DeviceToApp) -> proto::DeviceToApp { + if let Some(proto::device_to_app::Payload::StateUpdate(update)) = &mut msg.payload + && let Some(vehicle) = &mut update.vehicle_state + { + vehicle.advanced_state_bytes.clear(); + } + msg +} + fn system_update(timestamp_ms: u64, state: proto::SystemState) -> proto::DeviceToApp { proto::DeviceToApp { timestamp_ms, @@ -273,7 +290,7 @@ fn system_update(timestamp_ms: u64, state: proto::SystemState) -> proto::DeviceT /// The system state frame for `session` on `conn`, if one is due: when the session is /// new or something asked for it, when it changed, and every -/// [`crate::COMMAND_AVAILABILITY_REPEAT_MS`] while it doesn't. +/// [`LAN_SYSTEM_STATE_REPEAT_MS`] while it doesn't. fn next_system_frame( conn: LanConnection, session: SessionHandle, @@ -290,8 +307,8 @@ fn next_system_frame( Some((sent_to, sent, sent_at)) => (Some(*sent_to), Some(sent), *sent_at), None => (None, None, 0), }; - let repeat = sent_to != Some(session) - || now_ms.saturating_sub(sent_at) >= crate::availability::COMMAND_AVAILABILITY_REPEAT_MS; + let repeat = + sent_to != Some(session) || now_ms.saturating_sub(sent_at) >= LAN_SYSTEM_STATE_REPEAT_MS; if !(forced || check || repeat) { return None; } @@ -331,7 +348,7 @@ pub fn lan_try_next_frame(conn: LanConnection, now_ms: u64) -> Option> { let state_due = SLOTS.lock(|slots| core::mem::take(&mut slots.borrow_mut()[conn.slot].state_due)); if state_due { - let msg = crate::routing::latest_ble_state()?; + let msg = basic_only(crate::routing::latest_ble_state()?); return crate::secure_channel::seal(session, &msg, now_ms).map(|(_, frame)| frame); } None @@ -431,6 +448,23 @@ pub fn lan_mdns_txt() -> Option<[(&'static str, String); 2]> { ]) } +/// The mDNS instance label every board announces for a device named `name` (its BLE name): +/// the name and the key ID's first four characters, so two devices with the same name stay +/// apart, with dots made dashes and cut to one DNS label (63 bytes). `None` without an +/// identity. +pub fn lan_mdns_instance_name(name: &str) -> Option { + let key_id = crate::identity::device_identity()?.key_id; + let short_id: String = key_id.chars().take(4).collect(); + let mut label: String = alloc::format!("{name}-{short_id}") + .chars() + .map(|c| if c == '.' { '-' } else { c }) + .collect(); + while label.len() > 63 { + label.pop(); + } + Some(label) +} + /// Frees every slot, forgets the address and the discovery rate. For tests only. pub fn reset_lan_for_tests() { for slot in 0..LAN_MAX_CLIENTS { diff --git a/core-interface/src/lib.rs b/core-interface/src/lib.rs index 68d0ec4..cf503b9 100644 --- a/core-interface/src/lib.rs +++ b/core-interface/src/lib.rs @@ -181,9 +181,10 @@ pub use secure_channel::{ pub use lan::{ LAN_MAX_CLIENTS, LAN_MAX_REPLIES_PER_SECOND, LAN_MDNS_SERVICE, LAN_MDNS_TXT_DEVICE_ID, LAN_MDNS_TXT_VERSION, LAN_PROBE_BYTES, LAN_PROBE_MAGIC, LAN_PROTOCOL_VERSION, LAN_REPLY_BYTES, - LAN_REPLY_MAGIC, LAN_TCP_PORT, LAN_UDP_DISCOVERY_PORT, LanConnection, lan_accept, lan_address, - lan_close, lan_discovery_reply, lan_frame_length_ok, lan_mdns_txt, lan_next_frame, - lan_receive_frame, lan_should_close, lan_try_next_frame, reset_lan_for_tests, set_lan_address, + LAN_REPLY_MAGIC, LAN_SYSTEM_STATE_REPEAT_MS, LAN_TCP_PORT, LAN_UDP_DISCOVERY_PORT, + LanConnection, lan_accept, lan_address, lan_close, lan_discovery_reply, lan_frame_length_ok, + lan_is_open, lan_mdns_instance_name, lan_mdns_txt, lan_next_frame, lan_receive_frame, + lan_should_close, lan_try_next_frame, reset_lan_for_tests, set_lan_address, }; // Pairing registry diff --git a/core-interface/tests/lan.rs b/core-interface/tests/lan.rs index 151f613..8ae6b9c 100644 --- a/core-interface/tests/lan.rs +++ b/core-interface/tests/lan.rs @@ -7,14 +7,15 @@ use core_interface::{ MAX_HANDSHAKE_INITS_PER_SECOND, Transport, VehicleStatePayload, add_paired_phone, approve_can_read_write, can_access_state_update, clear_paired_phones, confirm_car_fingerprint, confirm_car_identity, device_identity, handle_ble_message, init, lan_accept, lan_close, - lan_discovery_reply, lan_frame_length_ok, lan_mdns_txt, lan_receive_frame, lan_should_close, - lan_try_next_frame, newest_session, on_frame, proto, publish_single_state, - report_command_availability_at, reset_can_access_for_tests, reset_client_keys_for_tests, - reset_command_availability_for_tests, reset_device_identity_for_tests, reset_lan_for_tests, - reset_latest_ble_state_for_tests, reset_phone_trust_for_tests, - reset_phone_validation_for_tests, reset_secure_channel_for_tests, restore_device_identity, - revoke_car_identity, route_single_response, set_can_dev_write_unlocked, set_can_read_only, - set_lan_address, set_random_source, validate_phone_for_tests, + lan_discovery_reply, lan_frame_length_ok, lan_mdns_instance_name, lan_mdns_txt, + lan_receive_frame, lan_should_close, lan_try_next_frame, newest_session, on_frame, proto, + publish_single_state, report_command_availability_at, reset_can_access_for_tests, + reset_client_keys_for_tests, reset_command_availability_for_tests, + reset_device_identity_for_tests, reset_lan_for_tests, reset_latest_ble_state_for_tests, + reset_phone_trust_for_tests, reset_phone_validation_for_tests, reset_secure_channel_for_tests, + restore_device_identity, revoke_car_identity, route_single_response, + set_can_dev_write_unlocked, set_can_read_only, set_lan_address, set_random_source, + validate_phone_for_tests, }; use embassy_time::Instant; use prost::Message as _; @@ -274,7 +275,7 @@ fn frames_from_a_link_that_is_not_lan_never_reach_a_lan_connection() { // ── What a session is sent ──────────────────────────────────────────────────── #[test] -fn a_new_session_gets_the_system_state_then_the_full_vehicle_state() { +fn a_new_session_gets_the_system_state_then_the_basic_vehicle_state() { boot(); report_available(); set_lan_address(Some("192.168.1.20:4734")); @@ -286,14 +287,17 @@ fn a_new_session_gets_the_system_state_then_the_full_vehicle_state() { assert_eq!(systems[0].lan_address.as_deref(), Some("192.168.1.20:4734")); let availability = systems[0].command_availability.as_ref().unwrap(); assert_eq!(availability.basic[&1], State::Available as i32); - assert_eq!(availability.advanced[&2], State::Available as i32); + assert_eq!( + availability.advanced[&2], + State::Unavailable as i32, + "advanced commands need Bluetooth" + ); let vehicle = vehicle_states(&msgs); assert_eq!(vehicle.len(), 1); assert_eq!(vehicle[0].basic_state_bytes, vec![0x08, 0x01]); - assert_eq!( - vehicle[0].advanced_state_bytes, - vec![0x10, 0x02], - "the LAN gets the full state, like BLE" + assert!( + vehicle[0].advanced_state_bytes.is_empty(), + "the LAN is the remote tier: basic state only" ); // Nothing more until something changes. assert!(owner.receive_all().is_empty()); @@ -368,6 +372,33 @@ fn a_command_over_the_lan_is_dispatched_and_answered_on_its_connection() { ); } +#[test] +fn an_advanced_command_over_the_lan_is_refused() { + boot(); + report_available(); + let mut owner = connect(OWNER_STATIC); + let _ = owner.receive_all(); + let message_id = next_id(); + let reply = owner.send(&proto::AppToDevice { + message_id, + platform_id: PLATFORM_ID, + source_device_id: OWNER.to_vec(), + payload: Some(Payload::AdvancedCommandBytes(vec![0x08, 0x02])), + }); + assert_eq!(reply, None); + assert!(core_interface::ADVANCED_CMD_CHANNEL.try_receive().is_err()); + let msgs = owner.receive_all(); + assert!( + msgs.iter().any(|m| matches!( + &m.payload, + Some(Out::CommandResponse(r)) if r.message_id == message_id + && !r.success + && r.status_code == proto::CommandStatusCode::RejectedUnavailable as i32 + )), + "{msgs:?}" + ); +} + #[test] fn a_closed_connection_drops_what_was_queued_for_it() { boot(); @@ -457,6 +488,23 @@ fn mdns_announces_only_the_key_id_and_the_version() { assert_eq!(txt[1], ("v", "1".to_string())); } +#[test] +fn the_mdns_instance_name_tells_devices_with_the_same_name_apart() { + boot(); + let key_id = device_identity().unwrap().key_id; + assert_eq!( + lan_mdns_instance_name("OpenCar").unwrap(), + format!("OpenCar-{}", &key_id[..4]) + ); + assert_eq!( + lan_mdns_instance_name("my.car").unwrap(), + format!("my-car-{}", &key_id[..4]) + ); + assert_eq!(lan_mdns_instance_name(&"x".repeat(80)).unwrap().len(), 63); + reset_device_identity_for_tests(); + assert!(lan_mdns_instance_name("OpenCar").is_none()); +} + // ── Handshake rate ──────────────────────────────────────────────────────────── #[test] diff --git a/core-interface/tests/secure_channel.rs b/core-interface/tests/secure_channel.rs index b56bf2c..a0a812f 100644 --- a/core-interface/tests/secure_channel.rs +++ b/core-interface/tests/secure_channel.rs @@ -326,14 +326,23 @@ fn a_validated_phone_command_reaches_the_vehicle_stamped_and_authorized() { } #[test] -fn advanced_commands_are_allowed_through_a_session() { +fn advanced_commands_are_refused_through_a_session() { boot(); let mut client = connect(OWNER_STATIC, RELAY); let mut msg = basic(OWNER); msg.payload = Some(Payload::AdvancedCommandBytes(vec![0x08, 0x02])); let (session, stamped) = message(client.send(&msg)); embassy_futures::block_on(handle_secure_message(session, stamped)); - assert!(ADVANCED_CMD_CHANNEL.try_receive().is_ok()); + assert!( + ADVANCED_CMD_CHANNEL.try_receive().is_err(), + "advanced commands need Bluetooth" + ); + let resp = secure_response(&client); + assert_eq!(resp.message_id, msg.message_id); + assert_eq!( + resp.status_code, + proto::CommandStatusCode::RejectedUnavailable as i32 + ); } #[test] diff --git a/docs/architecture.md b/docs/architecture.md index bc537b6..61643cb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,7 +69,7 @@ The actual binary entry point. Generated fresh by `xtask` before every build fro | `ADVANCED_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel | | `CMD_RESP_CHANNEL` | vehicle → core | `(Transport, CommandResponse)` | Transport tag routes response back | | `SECURE_TX_CHANNEL` | core → transport | `(SessionHandle, DeviceToApp)` | Responses for a [secure channel](#secure-channel) session on the relay, for it to `seal`; never waited on. LAN sessions use a queue per connection inside core ([LAN direct](lan.md)) | -| `VEHICLE_STATE_CHANNEL` | vehicle → core | `VehicleStatePayload` | BLE and LAN get full; MQTT gets basic only | +| `VEHICLE_STATE_CHANNEL` | vehicle → core | `VehicleStatePayload` | BLE gets full; MQTT and the secure channel (LAN) get basic only | | `CAN_RX_CHANNEL` | board → vehicle | `CanFrame` | Hardware-received CAN frame | | `CAN_TX_CHANNELS[bus_id]` | vehicle → board | `CanTxFrame` | Frame to transmit on that CAN bus, with its TX class (one queue per bus; see [CAN bus](can.md#tx-classes)) | | `CAN_LOG_CHANNEL` | board → logger session | `CanLogFrame` | Raw (pre-filter) frames for the SavvyCAN logger, only filled while a client is connected; see [CAN bus](can.md#savvycan-logging) | @@ -104,7 +104,7 @@ The device side of the end-to-end encrypted channel ([contracts `docs/secure-cha * **Handshake.** A valid handshake init from a key in the registry (`client_for_key`, [BLE](ble.md#client-keys)) creates a session and is answered with the handshake response. An unknown key, or a failed handshake, gets no answer, and an init whose ephemeral key was seen recently is refused (a replay). The ephemeral key comes from the board's random source; without it, or without a device identity, the channel is off. * **Sessions** (`secure_channel.rs`) are RAM-only, keyed by session ID and link, at most `MAX_SESSIONS` (4) and `MAX_SESSIONS_PER_CLIENT` (2); a new one replaces the client's idlest session at its limit, else the idlest one. A session ends after `SESSION_IDLE_TIMEOUT_MS` without a valid frame, `MAX_SESSION_MS` after its handshake, after `MAX_SESSION_MESSAGES` frames one way, when its link closes, and when its client's key leaves the registry (checked on every frame and seal). A transport frame for a session the device doesn't have on that link is answered with an unknown session frame. * **Frames.** Transport frames carry an explicit counter (the nonce); a 64-wide replay window drops duplicates and counters too far behind, and is only updated once a frame decrypts. An empty plaintext is a keepalive. -* **Identity and authorization.** Each `AppToDevice` a session carries is stamped with its client's ID (a phone's `ble:` ID) as `source_device_id`, whatever the client put there, and goes to `handle_secure_message`: basic and advanced vehicle commands get the same checks as that phone over BLE (read-only, validated for this car, controller lease) and a `CommandAuthorization`, and their response comes back through the session (`Transport::Secure(SessionHandle)`, routed to its LAN connection's queue, or to `SECURE_TX_CHANNEL` for the relay). System commands are dropped: they stay BLE-only. The `MQTT_COMMANDS_AUTHENTICATED` gate only applies to plain MQTT, until MQTT carries only channel frames (firmware#122). +* **Identity and authorization.** Each `AppToDevice` a session carries is stamped with its client's ID (a phone's `ble:` ID) as `source_device_id`, whatever the client put there, and goes to `handle_secure_message`: every channel transport is the remote tier, so basic vehicle commands get the same checks as that phone over BLE (read-only, validated for this car, controller lease) and a `CommandAuthorization`, and advanced commands are refused with `REJECTED_UNAVAILABLE` (they need Bluetooth). Responses come back through the session (`Transport::Secure(SessionHandle)`, routed to its LAN connection's queue, or to `SECURE_TX_CHANNEL` for the relay). System commands are dropped: they stay BLE-only. The `MQTT_COMMANDS_AUTHENTICATED` gate only applies to plain MQTT, until MQTT carries only channel frames (firmware#122). * **Memory.** A session's table entry is about 200 bytes (`SESSION_BYTES`, in a static, not the heap). A handshake only allocates a few small buffers. `seal` builds a frame in one buffer, encrypted in place, and an inbound frame is decrypted into one buffer, so a message costs about its own size on the heap (up to 4 KB for the largest). ### Channel flow diff --git a/docs/commands.md b/docs/commands.md index d26da7c..e1ec776 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -43,7 +43,7 @@ The app greys out the commands the device would reject, so the requirements are * while the device is read-only every command is unavailable, whatever was reported (a flip is published within a second); * a report older than `REPORT_MAX_AGE_MS` (5 s) counts as unavailable, so a vehicle that stopped reporting can't leave a command shown as available; * over BLE, every command is unavailable while the connected phone isn't validated for this car (see [Phone trust](ble.md#phone-trust)), since the device would refuse its commands (`ble_command_availability_at`). The app offers to validate the phone instead. -* **BLE and MQTT:** BLE gets both command sets. MQTT clients get the basic commands only (advanced commands are BLE only), at the MQTT state's rate: every 5 s while a client is active, once per MQTT idle period otherwise (`publish_command_availability_mqtt`). MQTT commands are not authenticated yet (`MQTT_COMMANDS_AUTHENTICATED`) and the device rejects all of them, so over MQTT every command is reported unavailable until that changes. +* **BLE and MQTT:** BLE gets both command sets. MQTT clients get the basic commands only (advanced commands are BLE only), at the MQTT state's rate: every 5 s while a client is active, once per MQTT idle period otherwise (`publish_command_availability_mqtt`). MQTT commands are not authenticated yet (`MQTT_COMMANDS_AUTHENTICATED`) and the device rejects all of them, so over MQTT every command is reported unavailable until that changes. A secure channel session (the LAN) is the remote tier too: it gets the basic commands as its phone would over BLE, and every advanced command reported unavailable, since they need Bluetooth (`client_command_availability_at`). * **States:** `AVAILABLE`, `UNAVAILABLE` (not right now: read-only, state out of date, the car is driving, ...) and `UNSUPPORTED` (not on this car). Nothing sends `UNSUPPORTED` yet; how a car declares it is still to be decided. * **The app** must trust an availability only if it was received on the current connection and treat a command with no entry as unavailable. It never caches or persists it. * **Virtual car:** reports its commands from its simulated state, so the app's grey-out and rejection messages can be tried without a car (see below). Like any other platform they are unavailable until the device is read-write. diff --git a/docs/lan.md b/docs/lan.md index 999a665..dead975 100644 --- a/docs/lan.md +++ b/docs/lan.md @@ -19,11 +19,11 @@ Off by default. It is on the PC board only for now; ESP WiFi builds ignore it un * **Connection slots.** The board asks `lan_accept(now)` for a slot when a TCP connection arrives. There are `LAN_MAX_CLIENTS` (2) slots. When all are taken, a connection that hasn't completed a handshake loses its slot to the new one; when every connection has a session, the new one is refused, so someone else on the network can't push the phone off. The board closes a connection when `lan_should_close` says so (no handshake within `HANDSHAKE_TIMEOUT_MS`, all its sessions ended, or its slot was taken back) and reports every close with `lan_close`, which ends its sessions. * **Frames in.** The board strips the 2-byte length prefix (a length of 0 or above `MAX_FRAME_BYTES` closes the connection, `lan_frame_length_ok`) and hands each frame to `lan_receive_frame`, which runs the secure channel and the dispatcher, and returns the handshake response or unknown-session frame to send back. -* **Frames out.** `lan_next_frame` (or `lan_try_next_frame` for a polling board) gives the next sealed frame for a connection, newest session first: command responses (a queue of 4 per connection, never waited on), then a system state with the session's client's command availability and `lan_address` (when the session starts, when either changes, and every 5 s like BLE's), then the newest vehicle state, the full one like BLE's (overwritten while unsent, so state never queues up). A client that handshakes again on the same connection moves to its new session. -* **Permissions** follow the session's client, as on every secure channel transport: a validated phone may send basic and advanced vehicle commands; system commands stay BLE-only. A phone that isn't validated is told every command is unavailable. +* **Frames out.** `lan_next_frame` (or `lan_try_next_frame` for a polling board) gives the next sealed frame for a connection, newest session first: command responses (a queue of 4 per connection, never waited on), then a system state with the session's client's command availability and `lan_address` (when the session starts, when either changes, and every `LAN_SYSTEM_STATE_REPEAT_MS` (5 s) even unchanged, which the app's receive timeout relies on), then the newest vehicle state, basic only like MQTT's (overwritten while unsent, so state never queues up; not throttled, the LAN is cheap). A client that handshakes again on the same connection moves to its new session. +* **Permissions:** the LAN is the remote tier, like MQTT and the relay: being on the same network is no proof of being at the car. A validated phone may send basic vehicle commands; advanced commands are refused with `REJECTED_UNAVAILABLE` and always reported unavailable to the session; system commands stay BLE-only. A phone that isn't validated is told every command is unavailable. * **Address.** The board reports its `ip:port` with `set_lan_address` (and `None` when it has none). It goes out as `SystemState.lan_address` with the CAN access state over BLE, and to every LAN session, whenever it changes. * **UDP discovery.** The board hands each datagram on `LAN_UDP_DISCOVERY_PORT` to `lan_discovery_reply`, which checks the probe (length, magic, version, a key ID that is this device's or all zero), limits replies to `LAN_MAX_REPLIES_PER_SECOND`, and builds the reply to send back to the sender. -* **mDNS.** `lan_mdns_txt()` gives the TXT records (`id`, the device key ID, and `v`); the board announces `LAN_MDNS_SERVICE` with the BLE name as the instance name, and again when its address changes. Nothing else is announced. +* **mDNS.** `lan_mdns_txt()` gives the TXT records (`id`, the device key ID, and `v`); the board announces `LAN_MDNS_SERVICE` under `lan_mdns_instance_name` (the BLE name and the key ID's first four characters, so two devices with the same name stay apart), and again when its address changes. Nothing else is announced. Nothing is served before the device has an identity: the handshake needs it, and the probe and mDNS name it. From 159dfd9cf49fc0676c3c344016aee6496b57c7d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 04:59:41 +0000 Subject: [PATCH 6/6] chore: pin contracts to main after contracts#52 merged Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- contracts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts b/contracts index b101725..3998261 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit b101725f088938055630975be8e1858ac3d998e2 +Subproject commit 39982611fec37f98f5221341ef3b77b313445c2a