From a2ded6506f9c35052669478388a154cb09042f08 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 19:27:42 +0000 Subject: [PATCH 1/8] 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/8] 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 zMyZs!YNaxS)Jf&A>!mfY8>9-@>!eE9jZ%}emc?t5s_@-h#?^9C^%_nRx9HRoY2xF=iFH59p%x|6!*X7~Tlb6l5ru&Y-b^~#=+ zpcwQ7g5t=S*W(L{C;YM)JmnD&?-EaV!P z1Xx7(#6)92oN&uQ(eGnE$hi}VeWPlGQO{ZLh(|o<4W44b&hEqFgzP`=*&vSieLhqm zAo|aGWXs^L!y80-(x)a1ct$2s_Q)wW;*5#-84a9rpGIwZ{oa5_+;^Z^&C~4@JwDk# zHs%@C8gbflVFSwW`ho$=xl?Ym5G_j9Bj74%l^reY8%me$Ng@36g~6U z!5(p(@@v{VIC!|Z6J6z%H(1bZGFr`QhH^KElRj2zvZiVknnpdxCr^sUC%t2%f#wb3 zS@)QC)E!h)O`P)k(%ouFHbO*ZD0O6PG7v;nNBpDcG1=oD6}=c-*+0%o)P@!@$NVRe zGj)gBi!2-+*eVX5@>p2S)rOw%vPOEuT2^wcc>ID|dp2>9)4s!^dvsLx1On(Y5oY2- z5Ov%vwv3BsJ-)MIE3?kw{L9S+}h6a zVd>Q9EJv|rpBVJ}$Jm^7sS~$#;sVAK<3t6gO&uGxe^f4`-oOZ(kCe+-EgI8S9Byej z<;O~D-}F%HM*M3(MqX@Gzb3Y{r~`b=VnM$qCn`D(J{6dbYRf)G{*7VDeuTB(Hjs?dV}7RKELe21inpM zMsKrDF&^+-py{XNvNg0zU4CA_FHl1{Q!yd%l zjlz1J8%~93o2iel;+!B1EeP@H;L^2}zy-f1q#)xi<~S!mK)I|kPMxH0F{Za-k?X6x zUrcSg7P(<;-l}o(nr}UKsGH-Oh2GoGBj`5r5_sfTt z3(F#fuXe_4Yd_89thslQ9XFCBA>>Yv#e?|B91GU}Xn@um=}}7ePz%!3bIrQm+tku# zp4Iz?PSN`&#}xy1t4U9Q3KK;+A3ur>d&t`@m$AtBAA%a)bIR_q8;N3x3+3Jk>k}(6)H6Nx_%%t0(wU653sY|!RnHrT&%oO)`I4<3? zA)Uq|OrrJ^o1A*|h8bi9sh=DaIf;z98N4zCOegSiI6Nh$j!}h8n5Y1Wx^( zSl71+DGe;8jpK%NSdlqu49$f&BH|cV#4)AfFc;!D(yLN3I}HwQvrZc=505oXD{_@_ z3T>R${sFXlwQ=TXIf&dB^eB4n5PH?gV|H6Yecc|SqhM1&aK}O4+$TNQkAr^kSvLA2 zru%V^+$j#LQ~ualJos-j#$7HvSc!Lo6; znTzH?$Z`%0ni#w=;Srk+awWVJE79`g3Q{abXo>a6vR_s#pnjvC6Yj~epp0(knoWuT zUcs&8usQ}5-mBT)%JtHYMH9s!TxFR%=2iu+Yw zLAYzWYsq4Lc_dta(R;CFIlnS8n8rMuE}dU0EDLX)?xW!R8OyZcQ#)vf+B-BaHA987-Z=wUpRtEN8q7-a%Z59+uasj%$qly*B zkRVPhrNaio*R7 zOTtvQY$*XfU7xV5`&7@H8$Y%bhsP6^mQM{jbL%I1!H}bN2Q^BeTv%^Mf-~#yhaaZzCA~tPKo_-|ezbkoGdBi;u z1Usj8!H!n8$299%D;1;9b3TZUQae&Fx1*MdEi(al8J1k*ThtzNtSnl_k)C@7e@U|a zv9;{Y(l^SZ2j=p>f8eGq(cw&3kHmx{tbcC*7j(!7BBuI8KjH1mqVMb(#Sm{`uNZZa_~ss#sQPcepqdAk3F{Zl>5*1V~M>M&(eS1Y2j8vGh| z<}jtHst;gx&aDWWhBtxw$$8Tm0EwFG=gMU zohBQ_lX4{EHr^*lru*b$zPD@#Cs~|&ZC`R@OeAX`FWKO4cM71hIoW8ZHhJp-t*E`T zhj(M?r&l=oN1*1fYN4Tx^W_i)XFd8yD^eIFbCwiF$>B7z*iWp84gV~$P0pMF8r4-s z${ogxQjOD;bzID8Zb2JO^g-U2rqgFjw^`8g0Qi)jtUo&WKD8@w8m0VnYqE{4*5jF+ z5ArTd<_(_uK6w{q)I^``cPzt`Uo%`lxhm`U^d)R)*wB`T&;85)m z85IlZIz>h2KMhXI?FCAu@ZxPc!h{OlXW`*K?i~Y)Bp!DMyd&E~7Jw*c-GG`#x8J5o z9kSuj?@9tI+ht0qnG~ zgBUVt{A{zCF?xz{9LS2IKj{f7Iirm41=kUjy%UV9RGCoW8Nb)3_=2u&ye7vAG zVXvFkEje;8d1gG}u82N7dC?zn#~tFLqcQGioV^fpG{zj;z^UffM%&-sa&60O{%rs3 zu5WFh%a7M>j@5R|J@&`)yTP01V-FsV9qx|}IAi@sV!4km<{pdZ9!uo9VkQ@>(!aR3 zN=tbKV4|$HFn{sE<-FpsJHlTc1wVZ9RR=g`Fjrj{&n_30M`|KnSL-8Zt~S2f8|Iht zim%u%+hWz5zQ1|y%nv5tot*E#sry%7OKk3rZR)xC#KK`IHt1X&JQ^Q78hc_mcFdI+ zd^&O19qT(DTRXClH@cKd{PekGK9R4@cFi8Y(KA%zq5nH=+A@9+Z zF=K067xLQfTU}fJrGqmEmkQQh56rfIcgu|}bNO@9T+erQ&bP|LjjU z-#YUblRue^IgiASJ{cQ2_UF&XTu;aQ+=&CnWBW&9BcriA&u4m_-SJ5dmnTN+-)_Fv zJlm6~-4xH=6f>3za*I&QY~Sx=P`P^E1;9p^JR4FklYuQKq>LV>jXyF(YyNf35ODXv(= z{#3(lNS_TbZmN@;|8x7gWhouP^RV_ zC1+9|8}lBg4e1QRRMxDG27+rnf(5$N!UBm(vtk4$G8MVN30Ptl?uy`bok z1H}nU1gOi^m8z~%;Z!g=TyVN?fdIyBhRAZm@K1Hm-nuh+ctZYG zQsDUeFnru)m{+Os&&FsItU!}pOWRjGOq7$E0m61x8O$8L78i$+6l>&6!DT*uniU$f zW1b~9K5T}Bt}-JT)^JXtFfGwcZB{nHQkb)m*)5=Kyf({X|v&v}W z;xtRuw6lCkoIHwy)gW#Y(2~tsX4nU_>~LvNZ^de;L0K#x9RF&wr^F7LLGey<&2_yY zBQYACZEcD}m2=PdWS0po=EK;v{$_mKVse?zZ=_Oy-m-r(8E334x8 z>qdniUm+hdKXTFol=~5(oPA!gl^@Svx;TGqn$Fo<{9S!b|RR zP{Ht@W76fM*I!M2TM-WTNrNF%Thc3JU@q32|JS`L2hkFFlB~0^GW$`!K)xYZKcJ9Q zXI1R~Uia*o`K}L&Z=U(nviAPtF99yqn5vh(mxm4M#e`O z=m6B0mIGs|*vT4_X*~s=Cto+LB+5ILWbjEDMk!o1MalDr6!$?`zXr!|vP}<$AB;R0 z-MnCGTyAKa6Xx6t4OT3*& zK$C!`KuIScYN$@9cn-`t)k#(LN!G(Nx|0D?&4N6E3>AA43{sUwQlAj@5!g?}AXL_q zRFG;-^7>4*WM8)!vOX*Z+-IRV1z~3M8bu&RT(K}Q3gi6=`@!xjQ;QTM_1r1XdB)<) z9w0l`p#QYT=VFHj#iG{0MM6g63w9KP*Eca4 zlu2X-Jk3Xg$97dVca>aHC)40A=po_I%RnqePt~zd6I`sK%??Fy%O?Z!ORU04;-Tau zJ4XOe6<~cLzrbopv!1FU2sN@K53d!xjvUpL!@x+K;Mh$G}#Nd=0^W zfWN>gkOeH3C3{hL@XFE4N5cnVR&lC(*;Wz`UI|?eC2X}2$8Ftvt0%Fw|7Fjm@tN^R zPYi%a<>m!P$HL=JEk6FthmSuKJ3XFw+&8sn*I5c%&Sun>eTNZ=|mj%;w(e&AHXhEpe+~*dA>Lp`A+_+{rw>(lGd#=z1zq<4ROMy&$+hwwFcnBfEhCULTul zpK~YHZH?QvzW?yeGqL?oBpx1)+lQxiYh7~o&EJ?kJ-=!GY@&Mig0Kh3#MEBuYa!zP znOy|FNPy!-=-Mm;i5z`xFF>jT3np>7xIWtdv*O0-o~6>tm-gP(b0tlm8aYSJCl=0> z7dMtJYn?Z+V3L*u^NR;xIJi_=b>-R1&%XNHQb`rGK~7)sU-l#YpFlO2Jk&xv8OZ14S z%-#2S6((WQERG#LdseVJNd{--Vbce?vC#JM-62w2INwjT-CiBY9J{cA7GK$Z3*H>HM>yk{VOqkvgV>&D@?m4&(sHF^5LGne=yG66Y72 z(wc!Al6!bFX$GzkT7aJ+A60Cdln6knl{_s{rnq>(6M(jeDkWBB98_T@Vo>ECj5>?t zR{;ww1s!=*Ilw;hFw3+@%2BfV$&$$GgQesEMkG}f6$Fyq=a>RRfQWf&3uU{f{5qu} z>*x3j{AXBG9H3%*F80X#ApiG;tXBfz{So=9GunQ2Xd!Rimt|GFCej}1zuFPyuRiqZ zQ&30&Sik$?vl^y;1nMkDqi3!@xsdn3lEpT)>le92(|Xz=>MrglMGEUB%Zw%56?R|l zh7Q}FNI%g1!D!9Z$KQJD>QjleEwRGZpPAY|HE?;wXk2#aiMT|XS9jls^<_9WfQuwo znFfk{kXmPxBM#Gffti66kfixw)uwS4Q8uM`Rc=pH0TYDksF;ay zaQWQh9>sKcpl`5mSKmRU3RIJL1v-ehScD|CR@n)edP2#O2D=9L?NS^}IT(jQRXbQQ zB@+e|TaxQwJP6S8Z%{IUG|N|F2FkwAO!Ut-n5$u(nQhFA1ha zp)oErzGM8ZxM<^wzzd$OxSiWdYIaLqbT8Z zt}63%nZolRM&O5&2prDhsbNHtq^ZSLs%mY6u=qB*hCi z_+CPDnTS9jePTr*&QHnT4KZb}Ke(G%AEsS~em#z=Dg22QojLlSh_mF zP(Y%&`j?-Gv@aKy5`+uV`3P`+N7Z zy;9Pm|CV_N_lK5;jX%)u;C_g|Kelz*^*^@puvZ8K0HLVsWfqRia~G-CXiy9~TlZz1 zJygKtJ9+|!R!V6yfZEg=LSadRVIt5zIg})~xxY-OcU@AZW9U`*bLxf)(J}a1lHpE) z&Op;^4jIb?2S9gka(n_(eOpUawTE0+?4yy7c-V z>n&aR#t~YDnxP(`@4MfIO(08CGK93ThqYK-R@#`F{C$=*O~oiB=_>&0)G|nir+Xio zFv*yNt2y;#1H4X+Nj8}rcF1&imVGZHG|Qf+jVhD)r6BcGBQx{HseHA`$Q#0;)g~=S z!j5YgK<}+KX+WQrEkJAVF{;6QOZEhK6oq&cUB9j?^k45VC| zPo`iA8jA1+xSERf#qpgc5}Gkk?GT5J54B1`>FNBXl=xs0HS(Fso_KqhRzEXNv(~z# zcJM)rwi#>EByhv^S}Z1X+sQ&0kCmP$EMyZxEW_)x*aO-$)jaSE@qiimS|p>8qJEN< z*q;vFkXN!v7J(Z`0leviTar#-i`+l1XGqKH&@1>`Ryn+k)EmoG6K|b^g$dWY)vb|U3=cs8(8QxEJs%k7Uyly{ARz57o@qMn_vG+Dj zc9k6z;c6~rhkyAZ+=>;{`>`I^p{_lk$;Kl+1Jb^}UQz@ZISqXgW7lrizTTce#Ul0X zI^gQwGthO2=_OOReXNrr}G)sYV z;8L5sh%h5oXy8d$Q`|2f=y=(A>DbJ%Nauom-TMtUbw6yz5!7Dx=9cS?(egya`nY}l z?1{L&1HRV$OWR-C{$|NrRadLtDOqgpj5l{CtPeBJlhfdqKGUcZP^7wOz8#Si`%o55+257ffx-j)F_xm%JBG zM|Q;>)!<*#-yb=uKhf#!uG#pk0P zv%1;*=+<|hP1JSH2XA)0ckZW+iJkpR>)XCx@`JVCTMNIzTeY_aZVo5fp*6d5xdhIp_i;tF!2+rZaTOXGNUB{Nnzv@1F)>QMyDLoWF+X zwrI_j9hY~2X|R_od1YW3?B$;aXk+~#uVnXD-M`&hv?tH-XSqD=6(BaP7)G()fnz0y zFp%645s)&_58;W2);5e$40Kve7rSox1Q z?Qv7(bk1d4xClYvlCTN5%V1=8v?kgeeK6*D;Af`wcl2CMtIA^|)09aL0(X~o_}957 zIout_h9&X1Gpxf6SZHOy#^n{*Ik*9AJekvMRE)UHMmI^ljYvO&tukfE%_hlyI9}(5 z3Y_|Y-pP%nBEYSc38rT(HE~EYV2n~S1NlBTmdY2>EGV&4RMr4=>H@j{5EgBAfdHv# zLu=hQ0wx;(tD-+Xd4jm{fM@JPI>1!A(w9i}LppT}oM}RxonfOs%yvZGlB^}=fh!iUalL}u&S#5@ix_tFf^LjR9y7?( zrn%F<*;Gisw0=TbY7D7$a#m=yQ`u6@myQEi#&;=_KBU{x&*U8PALA3};y=WXVg%4F zUziB8QI`Kbc|jiwgy*l|WRrlPcHby&$1*~PCHpZ&GDGte_m2o&*MZU*PRKY~ubd?+ zzHQSc2<1X|Q37X>o}lUcOGjspF50W&_NvH*guNL$lX<0)`nTGyw#DxH7glqYes>DV)tuUA5B&p2%rGSPsu?KJTgB&C7wr!6U%*mq z1E3htz+=cvawCDJHf@mm=Z5S%6`~bQBCoF;#Q0>*k915f(9`9L? zlB?|+NsrC6ahPC1DNkGPl_1}d#}`ZuOOAr&+=6h&m93YzUVM(^N;S*n)o-o+#@c9b zcJRAHH-_ep&z+flGEv?Mz2Wlh;hg0{l7pSUeE!w#(XQE?Yx@(0txM}3c>C0~Q?q9v zwK@B4XKdY$o5G)&er&pxf9uFk*4(O$J$fYE7w&m;D`YN_{>$g1?XNz!T=hU~{Xn8h zij_%A71eKTySi<$Vne)Q!>n^|)7<9SClVD~V?|qut*u-tt9;9R)%=#@sv{c2ox`x< zf8}sR<;x|tvAUi_$?jO*?jbYr&oV`m>@8*0b{Gr4___R;sM$ zpB7himvbMK7jT5yqwzyO^BQJK}N&p_G4o655)G)j| zeKIGrom?m1F7vIRV+8`(A?SZ=V3Y+Fp~{g!QD$H$I|Mc5pPyj zsg^SRn^6{N8muy3S{5S|SNQvT7vwK3SXa7y0Kh3=C-o zcBTC_m)5tWkeqHAMy*GSk^V(K4v9+>b_V7$npT|DXbEt2y$CVVp*(f$JE~rXPdK3qcz=M5zoIS3CU61t~ zlwU)xN-kq}T&ecSFH>2sP>}tc40OSjyluvyJo&#-DC2AXE4eDkBCba%+}qXLE$zjl zGp@mXhkE*)gDy$25NqS|oW~ty#s{fP%^gZ~nXKO>>k1{eu{RR5q6pex#IV`IkPLa5 zJYFJ;C^KWAcM#--WDq*Kl}e!yr3&j@yI3z{jviu$aGS zt^3eg7afcqoUe&nAAu4}Heq9VTqs`p7d;PJ$ckp*FtMJkR9#jp9I=i();bH#Jd$J_TT zw)e){dlT)4<0Xd|gnkyQEH0ES2y2$}%NFzNKg@?pOCrB$b$} zwj}BvirXFnrl=u>Q+tq{G+JIOxl-}F6_LT~o1>H8>P+OLuz3E13&KMb4m@(9sBuAP zB5B|;emS46YSbk1>!)*;^VUQY95*IkJs!>XMDC)v;k|IJ+P3}W$ybymL7hnPJMDB zTW-lZVE3aZkJv3DpjX6DDmm&Q1@cF>K0kw>Op6X!1Y17DiZN_l{#&?Kfe>c2S0?Le z`~~_E0oa4pfz@DvZ1Q4r*nP2ODX-{?`La1u^X5pj{tfTdmPB6DwBeVzMauFvE;}TKLS&SsiLRJlbL5Y6ldQrt!W0pJk+J8CfH&UwV$X<-xh*`RWfh1!N_206T#G*QzAQ%;}lLXR0j=( zBx#3;lvl6ugAq(K-zitJG5AT}Tazp;_=bX2D%L>Cl`X#0$X3Z-%+Blr)6^{ssArj) zl36gpbV_(D+0tTE+zLs~3yoDn>ryrNN_C;tLiOPWvK$PK2Qe}!7GGo0aO)&>+eor! z+;*{N&n49klqK2mM1w=Ct@i7)pg(HTJ*K(RBGsYa1N&&vRM53nqqXUN$@>bW=cDuj z%#1>(8Fo?Th5WDFZ(O!R$3JNvfW`d(Z62H?ytlZQF`J=6u#g&q$Q1R!(uImT>3K`> zX)scg6Hn9ongM9v5i=UvNXS$YHA-rPtHK^t|C=O>4~rA-KmZR3k_fUjl*6=hMEU1P zE-Pfw0ZHXzWw;dn5taR$79c}r6Bftoi2r1T4o^d^OGZZ2e+JSt<9W~fN^ zqjF4(6%~n;k#F(#i&QXeD z90A)1`Hb3(aY}lKtc_}*`oK+g$*Uf{Dwm@I&)_fcN3ci$wL;n2SQ?p380$4sUbrqA zd^>b46dj9g+8xW^vtZi0lwW+M{BpT^F?qUv$!LAyYjlO*6X}bWY)Is_(8d0|aCO{T zGg}OGv1L562e>F!yl26-cd2+yv^rkV9xvX6_mTvXXyt?_Bd&O9ORS`Ic66>|ZrwaT zUq4?Ga}c+(?0_P7v?1YW0zXwy8nMR<)=eGwICa03pJ~G#>eMG)cU^K6U-HlRBO?h% z?X>=vRtHl)eC>Qx|LSuKwuaA)tM0d&IFs$g3ol%V8!MNKD_=c2ZTYxhZNz=Oa@IXJ 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/8] 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 49e0974d95dbc142e07bd47fba73f4114037fb38 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 00:19:12 +0000 Subject: [PATCH 4/8] feat(lan): serve LAN direct on ESP WiFi builds With [network.lan] enabled on a WiFi build, xtask enables board-esp's `lan` feature and spawns start_lan on the WiFi stack: - a task per connection plus a spare, each with its own TcpSocket, so lan_accept can replace a connection without a session; - the UDP discovery responder; - an address task that reports SystemState.lan_address on DHCP changes and runs a minimal mDNS responder (core-interface lan_mdns.rs: PTR, SRV, TXT and A, legacy unicast for the app's one-shot query). Logs the free heap on each connection and the handshake time, for the C3 measurements. LTE builds leave LAN out with a warning. CI lints and builds the example config with LAN on. Closes #121 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- .github/workflows/ci.yml | 17 ++ boards/esp/Cargo.toml | 18 +- boards/esp/main.template.rs | 2 +- boards/esp/src/lan.rs | 307 +++++++++++++++++++++++++++++++++ boards/esp/src/lib.rs | 6 +- boards/esp/src/network.rs | 8 +- boards/esp/xtask_builder.rs | 49 +++++- config.toml.example | 2 +- core-interface/src/lan_mdns.rs | 220 +++++++++++++++++++++++ core-interface/src/lib.rs | 2 + core-interface/tests/lan.rs | 170 ++++++++++++++++-- docs/architecture.md | 1 + docs/lan.md | 13 +- 13 files changed, 786 insertions(+), 29 deletions(-) create mode 100644 boards/esp/src/lan.rs create mode 100644 core-interface/src/lan_mdns.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3d50311..8156d1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -213,6 +213,23 @@ jobs: - name: Build Firmware via xtask run: cargo xtask build --board ${{ matrix.board }} --platform ${{ matrix.platform }} + # LAN direct is off in the example config, which leaves the ESP's LAN code (the `lan` + # feature) out. Lint and build it too, on the example's WiFi ESP32-C3. + - name: Make a WiFi config with LAN direct + if: matrix.board == 'esp' + run: | + sed '/^\[network.lan\]/,/^\[/ s/^enabled = false/enabled = true/' \ + config.toml.example > /tmp/esp-wifi-lan.toml + grep -A1 '^\[network.lan\]' /tmp/esp-wifi-lan.toml | grep -q '^enabled = true' + + - name: Run Clippy via xtask (ESP, LAN direct) + if: matrix.board == 'esp' + run: cargo xtask clippy /tmp/esp-wifi-lan.toml --platform ${{ matrix.platform }} + + - name: Build Firmware via xtask (ESP, LAN direct) + if: matrix.board == 'esp' + run: cargo xtask build /tmp/esp-wifi-lan.toml --platform ${{ matrix.platform }} + # The example config uses plain MQTT, which leaves the ESP's TLS code (the # `mqtt-tls` feature) out. Lint and build it too, on Xtensa over LTE. - name: Make throwaway MQTT certificates diff --git a/boards/esp/Cargo.toml b/boards/esp/Cargo.toml index 4305363..a623320 100644 --- a/boards/esp/Cargo.toml +++ b/boards/esp/Cargo.toml @@ -42,11 +42,21 @@ mqtt-tls = [ "dep:esp-alloc", ] -# Chip features — `hardware` (with `mqtt-tls`) plus the chip on every ESP dependency, for rust-analyzer. +# LAN direct (docs/lan.md): TCP connections, UDP discovery and mDNS on the WiFi stack. +# xtask enables it for WiFi builds with [network.lan].enabled. +lan = [ + "hardware", + "embassy-net/udp", + "embassy-net/multicast", + "dep:esp-alloc", +] + +# Chip features — `hardware` (with `mqtt-tls` and `lan`) plus the chip on every ESP dependency, for rust-analyzer. # Selected automatically by `cargo xtask ide` from the MCU in config.toml. esp32 = [ "hardware", "mqtt-tls", + "lan", "esp-hal/esp32", "esp-println/esp32", "esp-println/auto", "esp-radio/esp32", @@ -56,6 +66,7 @@ esp32 = [ esp32s3 = [ "hardware", "mqtt-tls", + "lan", "esp-hal/esp32s3", "esp-println/esp32s3", "esp-println/auto", "esp-radio/esp32s3", @@ -65,6 +76,7 @@ esp32s3 = [ esp32c3 = [ "hardware", "mqtt-tls", + "lan", "esp-hal/esp32c3", "esp-println/esp32c3", "esp-println/jtag-serial", "esp-radio/esp32c3", @@ -74,6 +86,7 @@ esp32c3 = [ esp32c6 = [ "hardware", "mqtt-tls", + "lan", "esp-hal/esp32c6", "esp-println/esp32c6", "esp-println/auto", "esp-radio/esp32c6", @@ -118,7 +131,8 @@ rand_core_010 = { package = "rand_core", version = "0.10", default-features = fa # TLS for MQTT (mqtts://). 0.2 is the last release on esp-hal 1.1; software crypto, # from the prebuilt libraries (no chip feature, so no C toolchain needed). mbedtls-rs = { version = "=0.2.0", default-features = false, features = ["tls", "log"], optional = true } -# Only for logging the free heap after the TLS handshake. Same version xtask injects. +# Only for logging the free heap (after the TLS handshake, on LAN connections). Same +# version xtask injects. esp-alloc = { version = "0.10.0", optional = true } # Versions for crates injected into generated .app_build / .app_test_build by xtask. diff --git a/boards/esp/main.template.rs b/boards/esp/main.template.rs index 9655ecd..d4b2d64 100644 --- a/boards/esp/main.template.rs +++ b/boards/esp/main.template.rs @@ -51,7 +51,7 @@ async fn main(spawner: Spawner) -> ! { BLE_MAX_BONDED_PHONES, BLE_CONTROLLER_LEASE_TTL_S, ).unwrap()); -{MQTT_DRIVER_SPAWN}{CAN_LOGGER_SPAWN} spawner.spawn({VEHICLE_CRATE_IDENT}::handle_basic_commands_task().unwrap()); +{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/esp/src/lan.rs b/boards/esp/src/lan.rs new file mode 100644 index 0000000..d52a9c0 --- /dev/null +++ b/boards/esp/src/lan.rs @@ -0,0 +1,307 @@ +//! LAN direct on WiFi builds (docs/lan.md): the TCP connections, the UDP discovery probe +//! and the mDNS responder, on the WiFi `embassy-net` stack. The board only moves bytes: +//! `core-interface` gives connection slots, runs the secure channel, says what to send, +//! and builds the discovery and mDNS answers. +//! +//! One task per connection, plus one spare: when every connection is taken, the spare +//! accepts the next one, so that `lan_accept` can give it the slot of a connection that +//! has no session yet (or refuse it). + +#[cfg(feature = "lan")] +mod hardware { + use alloc::format; + use alloc::vec::Vec; + + use core_interface::{ + FRAME_HANDSHAKE_INIT, LAN_MAX_CLIENTS, LAN_MDNS_GROUP, LAN_MDNS_PORT, + LAN_UDP_DISCOVERY_PORT, LanConnection, MAX_FRAME_BYTES, + }; + use embassy_futures::select::{Either, Either3, select, select3}; + use embassy_net::tcp::TcpSocket; + use embassy_net::udp::{PacketMetadata, UdpSocket}; + use embassy_net::{IpEndpoint, Ipv4Address}; + use embassy_sync::blocking_mutex::raw::NoopRawMutex; + use embassy_sync::channel::Channel; + use embassy_time::{Duration, Instant, Timer}; + use embedded_io_async::Write as _; + + use crate::network::NetStack; + + /// Connection tasks: one per client, and the spare. + const CONNECTION_TASKS: usize = LAN_MAX_CLIENTS + 1; + /// Sockets LAN direct adds to the stack: the connections, discovery and mDNS. + pub(crate) const LAN_SOCKETS: usize = CONNECTION_TASKS + 2; + /// Room for one whole frame and its length prefix. + const READ_BUFFER: usize = 2 + MAX_FRAME_BYTES; + /// TCP buffers per connection. Sent frames are small (states, responses), and the + /// writer waits for room, so a frame or two in flight is enough. + const TCP_RX_BUFFER: usize = 1024; + const TCP_TX_BUFFER: usize = 2048; + /// Dead peers: TCP keepalives find them, the timeout drops them. + const TCP_KEEP_ALIVE: Duration = Duration::from_secs(20); + const TCP_TIMEOUT: Duration = Duration::from_secs(60); + /// How often a connection checks that it still has a session. + const SESSION_CHECK: Duration = Duration::from_secs(1); + /// How often the address is checked (DHCP renewals, reconnections). + const ADDRESS_CHECK: Duration = Duration::from_secs(5); + + fn now_ms() -> u64 { + Instant::now().as_millis() + } + + fn free_heap() -> usize { + esp_alloc::HEAP.free() + } + + /// Spawns LAN direct on `stack`: the connections on TCP `port`, the UDP discovery + /// responder and, if `mdns`, the mDNS responder announcing the device as `name`. Also + /// keeps `SystemState.lan_address` up to date. + pub fn start_lan( + spawner: &embassy_executor::Spawner, + stack: &'static NetStack, + port: u16, + name: &'static str, + mdns: bool, + ) { + for _ in 0..CONNECTION_TASKS { + spawner.spawn(lan_connection_task(stack, port).unwrap()); + } + spawner.spawn(lan_discovery_task(stack, port).unwrap()); + spawner.spawn(lan_address_task(stack, port, name, mdns).unwrap()); + log::info!( + "LAN: TCP port {port}, up to {LAN_MAX_CLIENTS} clients, UDP discovery on {LAN_UDP_DISCOVERY_PORT}, mDNS {}", + if mdns { "on" } else { "off" } + ); + } + + // ── Connections ────────────────────────────────────────────────────────────── + + #[embassy_executor::task(pool_size = CONNECTION_TASKS)] + async fn lan_connection_task(stack: &'static NetStack, port: u16) { + let mut rx_buffer = [0u8; TCP_RX_BUFFER]; + let mut tx_buffer = [0u8; TCP_TX_BUFFER]; + loop { + if !stack.is_config_up() { + stack.wait_config_up().await; + } + let mut socket = TcpSocket::new(*stack, &mut rx_buffer, &mut tx_buffer); + socket.set_timeout(Some(TCP_TIMEOUT)); + socket.set_keep_alive(Some(TCP_KEEP_ALIVE)); + socket.set_nagle_enabled(false); + if socket.accept(port).await.is_err() { + Timer::after(Duration::from_secs(1)).await; + continue; + } + let peer = socket.remote_endpoint(); + match core_interface::lan_accept(now_ms()) { + None => log::info!("LAN: refused {peer:?}: every connection has a session"), + Some(conn) => { + log::info!( + "LAN: {peer:?} connected (slot {}), free heap {} B", + conn.slot, + free_heap() + ); + let reason = serve(&mut socket, conn).await; + core_interface::lan_close(conn); + log::info!( + "LAN: {peer:?} disconnected ({reason}), free heap {} B", + free_heap() + ); + } + } + socket.abort(); + let _ = socket.flush().await; + } + } + + /// Runs one connection until it ends; returns why. + async fn serve(socket: &mut TcpSocket<'_>, conn: LanConnection) -> &'static str { + let (mut reader, mut writer) = socket.split(); + // Handshake responses, from the reader to the writer. + let replies: Channel, 2> = Channel::new(); + + let read = async { + let mut buf = [0u8; READ_BUFFER]; + let mut filled = 0; + loop { + match reader.read(&mut buf[filled..]).await { + Ok(0) => return "closed by the peer", + Ok(n) => filled += n, + Err(_) => return "read error", + } + while filled >= 2 { + let len = u16::from_be_bytes([buf[0], buf[1]]) as usize; + if !core_interface::lan_frame_length_ok(len) { + return "bad frame length"; + } + if filled < 2 + len { + break; + } + let frame = buf[2..2 + len].to_vec(); + buf.copy_within(2 + len..filled, 0); + filled -= 2 + len; + let started = Instant::now(); + let reply = core_interface::lan_receive_frame(conn, &frame).await; + if frame[0] == FRAME_HANDSHAKE_INIT { + log::info!( + "LAN: handshake {} in {} ms", + if reply.is_some() { + "answered" + } else { + "dropped" + }, + started.elapsed().as_millis() + ); + } + if let Some(reply) = reply { + replies.send(reply).await; + } + } + } + }; + + let write = async { + loop { + let frame = + match select(replies.receive(), core_interface::lan_next_frame(conn)).await { + Either::First(frame) | Either::Second(Some(frame)) => frame, + Either::Second(None) => return "slot taken back", + }; + let length = (frame.len() as u16).to_be_bytes(); + if writer.write_all(&length).await.is_err() + || writer.write_all(&frame).await.is_err() + { + return "write error"; + } + } + }; + + let watch = async { + loop { + Timer::after(SESSION_CHECK).await; + if core_interface::lan_should_close(conn, now_ms()) { + return "no session"; + } + } + }; + + match select3(read, write, watch).await { + Either3::First(reason) | Either3::Second(reason) | Either3::Third(reason) => reason, + } + } + + // ── UDP discovery ──────────────────────────────────────────────────────────── + + #[embassy_executor::task] + async fn lan_discovery_task(stack: &'static NetStack, port: u16) { + let mut rx_meta = [PacketMetadata::EMPTY; 4]; + let mut rx_buffer = [0u8; 256]; + let mut tx_meta = [PacketMetadata::EMPTY; 4]; + let mut tx_buffer = [0u8; 128]; + let mut socket = UdpSocket::new( + *stack, + &mut rx_meta, + &mut rx_buffer, + &mut tx_meta, + &mut tx_buffer, + ); + if let Err(e) = socket.bind(LAN_UDP_DISCOVERY_PORT) { + log::warn!("LAN: no UDP discovery on port {LAN_UDP_DISCOVERY_PORT}: {e:?}"); + return; + } + let mut buf = [0u8; 64]; + loop { + // A datagram too long for the buffer isn't a probe. + let Ok((n, meta)) = socket.recv_from(&mut buf).await else { + continue; + }; + if let Some(reply) = core_interface::lan_discovery_reply(&buf[..n], port, now_ms()) { + let _ = socket.send_to(&reply, meta.endpoint).await; + } + } + } + + // ── Address and mDNS ───────────────────────────────────────────────────────── + + /// Reports the address in `SystemState.lan_address` whenever it changes and, if + /// `mdns`, answers mDNS queries and announces the device on each new address. + #[embassy_executor::task] + async fn lan_address_task(stack: &'static NetStack, port: u16, name: &'static str, mdns: bool) { + let mut rx_meta = [PacketMetadata::EMPTY; 4]; + let mut rx_buffer = [0u8; 1024]; + let mut tx_meta = [PacketMetadata::EMPTY; 4]; + let mut tx_buffer = [0u8; 1024]; + let mut socket = UdpSocket::new( + *stack, + &mut rx_meta, + &mut rx_buffer, + &mut tx_meta, + &mut tx_buffer, + ); + let mdns = mdns + && match socket.bind(LAN_MDNS_PORT) { + Ok(()) => true, + Err(e) => { + log::warn!("LAN: no mDNS ({e:?}); the UDP probe still works"); + false + } + }; + let group = IpEndpoint::new(Ipv4Address::from(LAN_MDNS_GROUP).into(), LAN_MDNS_PORT); + + let mut address: Option = None; + let mut buf = [0u8; 512]; + loop { + let current = stack.config_v4().map(|config| config.address.address()); + if current != address { + address = current; + let reported = current.map(|ip| format!("{ip}:{port}")); + log::info!("LAN: address {}", reported.as_deref().unwrap_or("none")); + core_interface::set_lan_address(reported.as_deref()); + if let (true, Some(ip)) = (mdns, current) { + if let Err(e) = stack.join_multicast_group(Ipv4Address::from(LAN_MDNS_GROUP)) { + log::warn!("LAN: cannot join the mDNS group: {e:?}"); + } + // Announced twice, a second apart (RFC 6762, section 8.3). + for i in 0..2 { + if i > 0 { + Timer::after(Duration::from_secs(1)).await; + } + if let Some(announcement) = + core_interface::lan_mdns_announcement(name, ip.octets(), port) + { + let _ = socket.send_to(&announcement, group).await; + } + } + } + } + + if !mdns { + Timer::after(ADDRESS_CHECK).await; + continue; + } + let received = + match select(socket.recv_from(&mut buf), Timer::after(ADDRESS_CHECK)).await { + Either::First(Ok(received)) => received, + _ => continue, + }; + let (n, meta) = received; + let Some(ip) = address else { + continue; + }; + let legacy_unicast = meta.endpoint.port != LAN_MDNS_PORT; + if let Some(answer) = core_interface::lan_mdns_response( + &buf[..n], + legacy_unicast, + name, + ip.octets(), + port, + ) { + let to = if legacy_unicast { meta.endpoint } else { group }; + let _ = socket.send_to(&answer, to).await; + } + } + } +} + +#[cfg(feature = "lan")] +pub use hardware::*; diff --git a/boards/esp/src/lib.rs b/boards/esp/src/lib.rs index 02b245f..11e1ec6 100644 --- a/boards/esp/src/lib.rs +++ b/boards/esp/src/lib.rs @@ -1,7 +1,7 @@ //! Board support crate for the ESP32 family. //! //! Wires the `core-interface` task set to ESP32-specific hardware drivers: BLE -//! (trouble-host), WiFi or LTE (esp-radio or a PPP modem, + embassy-net) with MQTT, and CAN buses (TWAI and/or +//! (trouble-host), WiFi or LTE (esp-radio or a PPP modem, + embassy-net) with MQTT and, on WiFi, LAN direct, and CAN buses (TWAI and/or //! MCP2515). The public API is kept minimal: [`start`] spawns the core protocol //! tasks, and hardware-init functions are re-exported for use by the generated //! `main.rs` entry point produced by `xtask`. @@ -12,6 +12,7 @@ extern crate alloc; mod ble; mod can; +mod lan; // Only the `hardware` code drives the modem; host builds compile its pure parts for tests. #[cfg_attr(not(feature = "hardware"), allow(dead_code, unused_imports))] mod modem; @@ -36,6 +37,9 @@ mod hardware { pub use network::{NetStack, can_logger_task, init_wifi, mqtt_driver_task}; + #[cfg(feature = "lan")] + pub use super::lan::start_lan; + pub use modem::{ControlPin, LteSettings, ModemKind, ModemPins, init_lte, new_modem_uart}; use core_interface::SYSTEM_COMMAND_CHANNEL; diff --git a/boards/esp/src/network.rs b/boards/esp/src/network.rs index ae1ec3f..1b8cc87 100644 --- a/boards/esp/src/network.rs +++ b/boards/esp/src/network.rs @@ -2,7 +2,8 @@ //! //! `init_wifi` brings up the ESP radio WiFi peripheral and creates the `embassy-net` stack, //! spawning an internal connection-management task that reconnects automatically. The -//! LTE uplink (`modem::init_lte`) creates the same kind of stack over PPP instead. +//! LTE uplink (`modem::init_lte`) creates the same kind of stack over PPP instead. LAN +//! direct (`lan.rs`) runs on the WiFi stack. //! //! `mqtt_driver_task` connects to the MQTT broker over TCP on whichever stack it is //! given (with TLS through MbedTLS for `mqtts://`, see `docs/mqtt-tls.md`), subscribes @@ -37,8 +38,11 @@ mod hardware { }; // 1 socket for the MQTT TCP connection + 1 for the SavvyCAN CAN logger + 1 for DNS - // + 2 for smoltcp internals (DHCP, ARP). + // + 2 for smoltcp internals (DHCP, ARP), and LAN direct's when it is built in. + #[cfg(not(feature = "lan"))] pub(crate) const NET_RESOURCES_SOCKETS: usize = 5; + #[cfg(feature = "lan")] + pub(crate) const NET_RESOURCES_SOCKETS: usize = 5 + crate::lan::LAN_SOCKETS; /// A network stack, over WiFi (`init_wifi`) or LTE (`init_lte`). pub type NetStack = Stack<'static>; diff --git a/boards/esp/xtask_builder.rs b/boards/esp/xtask_builder.rs index cd30e3d..f416d15 100644 --- a/boards/esp/xtask_builder.rs +++ b/boards/esp/xtask_builder.rs @@ -189,6 +189,11 @@ fn select_uplink( Ok(uplink) } +/// Whether LAN direct is built in: asked for, on a WiFi uplink. +fn lan_on_uplink(lan_enabled: bool, wifi_uplink: bool) -> bool { + lan_enabled && wifi_uplink +} + /// Checks `[network.lte]` with the rules the firmware applies to what it sends the modem. fn check_lte_settings(lte: &crate::LteConfig) -> Result<(), String> { let apn = lte @@ -537,11 +542,19 @@ impl TargetBuilder for Builder { cargo_toml.push_str("[dependencies]\n"); cargo_toml.push_str("core-interface = { path = \"../core-interface\" }\n"); let mqtt_security = crate::checked_mqtt_security(config); - let board_features = if matches!(mqtt_security, crate::MqttSecurity::Tls { .. }) { - "\"hardware\", \"mqtt-tls\"" - } else { - "\"hardware\"" - }; + // LAN direct needs the WiFi stack: `select_uplink` below rejects WiFi with LTE. + let lan_enabled = lan_on_uplink( + config.network.lan.enabled, + config.network.wifi.enabled && !config.network.lte.enabled, + ); + let mut board_features = vec!["\"hardware\""]; + if matches!(mqtt_security, crate::MqttSecurity::Tls { .. }) { + board_features.push("\"mqtt-tls\""); + } + if lan_enabled { + board_features.push("\"lan\""); + } + let board_features = board_features.join(", "); cargo_toml.push_str(&format!( "board-esp = {{ path = \"../boards/esp\", features = [{board_features}] }}\n" )); @@ -615,10 +628,11 @@ impl TargetBuilder for Builder { exit(1); }); let wifi_enabled = uplink == Uplink::Wifi; - if config.network.lan.enabled { + if config.network.lan.enabled && !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)." + "\u{26a0}\u{fe0f} [network.lan].enabled is ignored: LAN direct needs \ + [network.wifi].enabled = true (a build has one uplink, and a carrier network \ + doesn't let the phone reach the device)." ); } let wifi_ssid = if wifi_enabled { @@ -775,6 +789,17 @@ impl TargetBuilder for Builder { String::new() }; + let lan = &config.network.lan; + let lan_spawn = if lan_enabled { + format!( + " board_esp::start_lan(&spawner, net_stack, {port}, BLE_DEVICE_NAME_BASE, {mdns});\n", + port = lan.port_expr(), + mdns = lan.mdns, + ) + } else { + String::new() + }; + let is_dual_core = esp_hw.mcu == "esp32" || esp_hw.mcu == "esp32s3"; let heap_size = if is_dual_core { "160 * 1024" } else { "83 * 1024" }; // RAM used by the 2nd-stage bootloader is free once the app runs. On the RISC-V @@ -877,6 +902,7 @@ impl TargetBuilder for Builder { .replace("{BLE_DRIVER_SPAWN}", &ble_driver_spawn) .replace("{MQTT_DRIVER_SPAWN}", &mqtt_driver_spawn) .replace("{CAN_LOGGER_SPAWN}", &can_logger_spawn) + .replace("{LAN_SPAWN}", &lan_spawn) .replace("{IDLE_LOOP}", &idle_loop) .replace("{BUILD_KIND_INIT}", &crate::build_kind_init(config)); @@ -1121,6 +1147,13 @@ mod lte_tests { assert!(select_uplink(true, true, true, false).is_err()); } + #[test] + fn lan_needs_wifi() { + assert!(lan_on_uplink(true, true)); + assert!(!lan_on_uplink(true, false)); + assert!(!lan_on_uplink(false, true)); + } + #[test] fn lte_needs_a_modem() { assert!(select_uplink(false, true, false, false).is_err()); diff --git a/config.toml.example b/config.toml.example index 3910875..5de84c9 100644 --- a/config.toml.example +++ b/config.toml.example @@ -107,7 +107,7 @@ 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). +# and ESP WiFi builds (not LTE). [network.lan] enabled = false # port = 4734 # the contract's port ([lan] tcp_port in transport.toml) when unset diff --git a/core-interface/src/lan_mdns.rs b/core-interface/src/lan_mdns.rs new file mode 100644 index 0000000..0f64cc0 --- /dev/null +++ b/core-interface/src/lan_mdns.rs @@ -0,0 +1,220 @@ +//! A minimal mDNS responder for the one LAN service (docs/lan.md, RFC 6762 and 6763), for +//! boards without an mDNS library: it builds the answers, the board owns the UDP socket on +//! [`LAN_MDNS_PORT`] in the [`LAN_MDNS_GROUP`]. +//! +//! It answers questions for the service's PTR, the instance's SRV and TXT, and the host's +//! A record, always with all four records, so one answer is enough to connect. A query +//! from a port other than 5353 is a one-shot "legacy unicast" query (what the app sends): +//! the answer goes back to it by unicast, with its ID and questions and short TTLs. + +use alloc::format; +use alloc::string::String; +use alloc::vec::Vec; + +use crate::lan::{LAN_MDNS_SERVICE, lan_mdns_txt}; + +/// The mDNS UDP port. +pub const LAN_MDNS_PORT: u16 = 5353; +/// The mDNS IPv4 multicast group. +pub const LAN_MDNS_GROUP: [u8; 4] = [224, 0, 0, 251]; + +const TYPE_A: u16 = 1; +const TYPE_PTR: u16 = 12; +const TYPE_TXT: u16 = 16; +const TYPE_SRV: u16 = 33; +const TYPE_ANY: u16 = 255; +const CLASS_IN: u16 = 1; +/// The cache-flush bit of a unique record's class in a multicast answer. +const CACHE_FLUSH: u16 = 0x8000; +/// TTL of multicast answers, in seconds (RFC 6762 recommends 120 s for host records). +const TTL: u32 = 120; +/// TTL of legacy unicast answers: at most 10 s (RFC 6762, section 6.7). +const LEGACY_TTL: u32 = 10; +/// Longest DNS label. +const MAX_LABEL: usize = 63; + +/// The names the device answers for. +struct Names { + service: String, + instance: String, + host: String, +} + +fn names(instance_name: &str, key_id: &str) -> Names { + let service = format!("{LAN_MDNS_SERVICE}.local"); + // Two devices with the same name stay apart by their key IDs. + let short_id: String = key_id.chars().take(4).collect(); + let mut instance_label: String = format!("{instance_name}-{short_id}") + .chars() + .map(|c| if c == '.' { '-' } else { c }) + .collect(); + while instance_label.len() > MAX_LABEL { + instance_label.pop(); + } + let instance = format!("{instance_label}.{service}"); + let host = format!("opencar-{key_id}.local"); + Names { + service, + instance, + host, + } +} + +/// The reply to the mDNS `query`, from a querier on port 5353 (`legacy_unicast` false) or +/// another port (true), for a device named `instance_name` at `ipv4`, listening on TCP +/// `port`. `None` to stay silent: not a query, nothing asked about this device, or no +/// identity yet. +pub fn lan_mdns_response( + query: &[u8], + legacy_unicast: bool, + instance_name: &str, + ipv4: [u8; 4], + port: u16, +) -> Option> { + let txt = lan_mdns_txt()?; + let names = names(instance_name, &txt[0].1); + if query.len() < 12 { + return None; + } + let flags = u16::from_be_bytes([query[2], query[3]]); + // A response, or another opcode than a standard query. + if flags & 0x8000 != 0 || (flags >> 11) & 0xF != 0 { + return None; + } + let questions = u16::from_be_bytes([query[4], query[5]]); + let mut offset = 12; + let mut asked = false; + for _ in 0..questions { + let (name, after) = read_name(query, offset)?; + if query.len() < after + 4 { + return None; + } + let qtype = u16::from_be_bytes([query[after], query[after + 1]]); + offset = after + 4; + let is = |n: &str| name.eq_ignore_ascii_case(n); + asked |= (is(&names.service) && matches!(qtype, TYPE_PTR | TYPE_ANY)) + || (is(&names.instance) && matches!(qtype, TYPE_SRV | TYPE_TXT | TYPE_ANY)) + || (is(&names.host) && matches!(qtype, TYPE_A | TYPE_ANY)); + } + if !asked { + return None; + } + let mut out = Vec::with_capacity(256); + let id = if legacy_unicast { + [query[0], query[1]] + } else { + [0, 0] + }; + let echoed = if legacy_unicast { questions } else { 0 }; + header(&mut out, id, echoed); + if legacy_unicast { + out.extend_from_slice(&query[12..offset]); + } + records(&mut out, &names, &txt, ipv4, port, legacy_unicast); + Some(out) +} + +/// An unsolicited announcement of the device (RFC 6762, section 8.3), sent to the group +/// when its address is new. `None` without an identity. +pub fn lan_mdns_announcement(instance_name: &str, ipv4: [u8; 4], port: u16) -> Option> { + let txt = lan_mdns_txt()?; + let names = names(instance_name, &txt[0].1); + let mut out = Vec::with_capacity(256); + header(&mut out, [0, 0], 0); + records(&mut out, &names, &txt, ipv4, port, false); + Some(out) +} + +fn header(out: &mut Vec, id: [u8; 2], questions: u16) { + out.extend_from_slice(&id); + // A response, authoritative. + out.extend_from_slice(&0x8400u16.to_be_bytes()); + out.extend_from_slice(&questions.to_be_bytes()); + // Four answers, no authority or additional records. + out.extend_from_slice(&4u16.to_be_bytes()); + out.extend_from_slice(&[0, 0, 0, 0]); +} + +fn records( + out: &mut Vec, + names: &Names, + txt: &[(&'static str, String); 2], + ipv4: [u8; 4], + port: u16, + legacy_unicast: bool, +) { + let ttl = if legacy_unicast { LEGACY_TTL } else { TTL }; + // Unique records flush caches, except in legacy unicast answers. + let unique = if legacy_unicast { + CLASS_IN + } else { + CLASS_IN | CACHE_FLUSH + }; + + let mut ptr = Vec::new(); + write_name(&mut ptr, &names.instance); + record(out, &names.service, TYPE_PTR, CLASS_IN, ttl, &ptr); + + let mut srv = Vec::new(); + srv.extend_from_slice(&[0, 0, 0, 0]); + srv.extend_from_slice(&port.to_be_bytes()); + write_name(&mut srv, &names.host); + record(out, &names.instance, TYPE_SRV, unique, ttl, &srv); + + let mut text = Vec::new(); + for (key, value) in txt { + let entry = format!("{key}={value}"); + text.push(entry.len().min(255) as u8); + text.extend_from_slice(&entry.as_bytes()[..entry.len().min(255)]); + } + record(out, &names.instance, TYPE_TXT, unique, ttl, &text); + + record(out, &names.host, TYPE_A, unique, ttl, &ipv4); +} + +fn record(out: &mut Vec, name: &str, rtype: u16, class: u16, ttl: u32, data: &[u8]) { + write_name(out, name); + out.extend_from_slice(&rtype.to_be_bytes()); + out.extend_from_slice(&class.to_be_bytes()); + out.extend_from_slice(&ttl.to_be_bytes()); + out.extend_from_slice(&(data.len() as u16).to_be_bytes()); + out.extend_from_slice(data); +} + +/// `name` as length-prefixed labels and the closing zero. The instance label has no dots +/// (they are replaced), so splitting on them gives the labels. +fn write_name(out: &mut Vec, name: &str) { + for label in name.split('.').filter(|l| !l.is_empty()) { + let bytes = &label.as_bytes()[..label.len().min(MAX_LABEL)]; + out.push(bytes.len() as u8); + out.extend_from_slice(bytes); + } + out.push(0); +} + +/// The (possibly compressed) name at `offset`, with dots, and the offset after it. `None` +/// if it runs past the message or loops. +fn read_name(message: &[u8], offset: usize) -> Option<(String, usize)> { + let mut name = String::new(); + let mut position = offset; + let mut end = None; + for _ in 0..64 { + let length = *message.get(position)? as usize; + if length == 0 { + return Some((name, end.unwrap_or(position + 1))); + } + if length & 0xC0 == 0xC0 { + let low = *message.get(position + 1)? as usize; + end.get_or_insert(position + 2); + position = ((length & 0x3F) << 8) | low; + continue; + } + let label = message.get(position + 1..position + 1 + length)?; + if !name.is_empty() { + name.push('.'); + } + name.push_str(&String::from_utf8_lossy(label)); + position += 1 + length; + } + None +} diff --git a/core-interface/src/lib.rs b/core-interface/src/lib.rs index 68d0ec4..f72cb1e 100644 --- a/core-interface/src/lib.rs +++ b/core-interface/src/lib.rs @@ -19,6 +19,7 @@ mod dispatch; mod identity; mod isotp; mod lan; +mod lan_mdns; mod lifecycle; mod mqtt_tls; mod noise; @@ -185,6 +186,7 @@ pub use lan::{ 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, }; +pub use lan_mdns::{LAN_MDNS_GROUP, LAN_MDNS_PORT, lan_mdns_announcement, lan_mdns_response}; // Pairing registry pub use pairing::{ diff --git a/core-interface/tests/lan.rs b/core-interface/tests/lan.rs index 151f613..afbf838 100644 --- a/core-interface/tests/lan.rs +++ b/core-interface/tests/lan.rs @@ -3,18 +3,19 @@ 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, + LAN_MAX_CLIENTS, LAN_MAX_REPLIES_PER_SECOND, LAN_MDNS_SERVICE, 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_announcement, + lan_mdns_response, 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 _; @@ -457,6 +458,151 @@ fn mdns_announces_only_the_key_id_and_the_version() { assert_eq!(txt[1], ("v", "1".to_string())); } +fn dns_name(name: &str) -> Vec { + let mut out = Vec::new(); + for label in name.split('.') { + out.push(label.len() as u8); + out.extend_from_slice(label.as_bytes()); + } + out.push(0); + out +} + +fn mdns_query(id: u16, flags: u16, name: &str, qtype: u16) -> Vec { + let mut q = Vec::new(); + q.extend_from_slice(&id.to_be_bytes()); + q.extend_from_slice(&flags.to_be_bytes()); + q.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 0]); + q.extend_from_slice(&dns_name(name)); + q.extend_from_slice(&qtype.to_be_bytes()); + q.extend_from_slice(&1u16.to_be_bytes()); + q +} + +/// The records of an mDNS answer without name compression (what the device sends): name, +/// type, class, TTL and data, after `skip` bytes of echoed questions. +fn mdns_records(msg: &[u8], skip: usize) -> Vec<(String, u16, u16, u32, Vec)> { + fn name(msg: &[u8], mut at: usize) -> (String, usize) { + let mut labels = Vec::new(); + while msg[at] != 0 { + let len = msg[at] as usize; + labels.push(String::from_utf8(msg[at + 1..at + 1 + len].to_vec()).unwrap()); + at += 1 + len; + } + (labels.join("."), at + 1) + } + let count = u16::from_be_bytes([msg[6], msg[7]]); + let mut at = 12 + skip; + let mut out = Vec::new(); + for _ in 0..count { + let (n, after) = name(msg, at); + let field = |i: usize| u16::from_be_bytes([msg[after + i], msg[after + i + 1]]); + let ttl = u32::from_be_bytes(msg[after + 4..after + 8].try_into().unwrap()); + let len = field(8) as usize; + let data = msg[after + 10..after + 10 + len].to_vec(); + out.push((n, field(0), field(2), ttl, data)); + at = after + 10 + len; + } + assert_eq!(at, msg.len()); + out +} + +#[test] +fn mdns_answers_a_legacy_unicast_query_for_the_service() { + boot(); + let service = format!("{LAN_MDNS_SERVICE}.local"); + let query = mdns_query(0x1234, 0, &service, 12); + let reply = lan_mdns_response(&query, true, "OpenCar", [192, 168, 1, 20], 4734).unwrap(); + // Its ID, a response, the question echoed, four answers. + assert_eq!(reply[..12], [0x12, 0x34, 0x84, 0, 0, 1, 0, 4, 0, 0, 0, 0]); + let question = &query[12..]; + assert_eq!(&reply[12..12 + question.len()], question); + + let key_id = device_identity().unwrap().key_id; + let instance = format!("OpenCar-{}.{service}", &key_id[..4]); + let host = format!("opencar-{key_id}.local"); + let records = mdns_records(&reply, question.len()); + let types: Vec = records.iter().map(|r| r.1).collect(); + assert_eq!(types, [12, 33, 16, 1]); + assert!( + records.iter().all(|r| r.2 == 1 && r.3 == 10), + "IN, short TTL, no flush" + ); + assert_eq!(records[0].0, service); + assert_eq!(records[0].4, dns_name(&instance)); + assert_eq!(records[1].0, instance); + let mut srv = vec![0, 0, 0, 0, 0x12, 0x7e]; + srv.extend_from_slice(&dns_name(&host)); + assert_eq!(records[1].4, srv); + let mut txt = vec![(3 + key_id.len()) as u8]; + txt.extend_from_slice(format!("id={key_id}").as_bytes()); + txt.extend_from_slice(b"\x03v=1"); + assert_eq!(records[2].4, txt); + assert_eq!(records[3].0, host); + assert_eq!(records[3].4, [192, 168, 1, 20]); +} + +#[test] +fn mdns_answers_multicast_queries_to_the_group() { + boot(); + let service = format!("{LAN_MDNS_SERVICE}.local"); + let reply = lan_mdns_response( + &mdns_query(7, 0, &service, 255), + false, + "OpenCar", + [10, 0, 0, 2], + 4734, + ) + .unwrap(); + // No ID or question, cache flush on the unique records. + assert_eq!(reply[..8], [0, 0, 0x84, 0, 0, 0, 0, 4]); + let classes: Vec = mdns_records(&reply, 0).iter().map(|r| r.2).collect(); + assert_eq!(classes, [1, 0x8001, 0x8001, 0x8001]); + + let key_id = device_identity().unwrap().key_id; + let host = format!("OPENCAR-{key_id}.LOCAL"); + assert!( + lan_mdns_response( + &mdns_query(7, 0, &host, 1), + false, + "OpenCar", + [10, 0, 0, 2], + 4734 + ) + .is_some() + ); + let announcement = lan_mdns_announcement("OpenCar", [10, 0, 0, 2], 4734).unwrap(); + assert_eq!(announcement, reply); +} + +#[test] +fn mdns_stays_silent_for_anything_else() { + boot(); + let service = format!("{LAN_MDNS_SERVICE}.local"); + let ip = [10, 0, 0, 2]; + let ask = |query: &[u8]| lan_mdns_response(query, true, "OpenCar", ip, 4734); + assert!(ask(&mdns_query(1, 0, "_http._tcp.local", 12)).is_none()); + assert!( + ask(&mdns_query(1, 0, &service, 1)).is_none(), + "an A question for the service" + ); + assert!( + ask(&mdns_query(1, 0x8400, &service, 12)).is_none(), + "a response" + ); + let query = mdns_query(1, 0, &service, 12); + assert!(ask(&query[..query.len() - 3]).is_none(), "truncated"); + assert!(ask(&[0; 5]).is_none()); + // A compression pointer to itself. + let mut looping = query[..12].to_vec(); + looping.extend_from_slice(&[0xC0, 12, 0, 12, 0, 1]); + assert!(ask(&looping).is_none()); + // No identity, nothing to announce. + reset_device_identity_for_tests(); + assert!(ask(&query).is_none()); + assert!(lan_mdns_announcement("OpenCar", ip, 4734).is_none()); +} + // ── Handshake rate ──────────────────────────────────────────────────────────── #[test] diff --git a/docs/architecture.md b/docs/architecture.md index bc537b6..dee939c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -158,6 +158,7 @@ Embassy is used freely inside `core-interface`. Boards adapt to it — not the o * BLE: `ble::controller::BleConnector::new(peripherals.BT, ble::Config::default())` (2 args, no `init_radio()` call). * WiFi: `esp_radio::wifi::new(peripherals.WIFI, WifiControllerConfig::default())` returns `(controller, interfaces)`; use `interfaces.station` (not `.sta`); configure with `WifiModeConfig::Station(StationConfig::default().with_ssid(...).with_password(...))`. * **One uplink per build:** WiFi (`[network.wifi]`) or LTE (`[network.lte]`, needs a `[hardware.esp.modem]`; see [LTE](lte.md)). xtask generates the matching init as `net_stack` and spawns `mqtt_driver_task` on it. With both disabled, xtask omits the network constants and the `mqtt_driver_task` spawn from the generated `main.rs`; `ble_transport_task` is always spawned. +* **LAN direct:** with `[network.lan] enabled = true` on a WiFi build, xtask enables `board-esp`'s `lan` feature (UDP and multicast in embassy-net) and spawns `start_lan` on `net_stack`: a task per connection and a spare, the UDP probe, and the address and mDNS task. An LTE build leaves it out. See [LAN direct](lan.md#esp-board). * **MQTT over TLS:** for a `mqtts://` broker xtask enables `board-esp`'s `mqtt-tls` feature (MbedTLS, about 540 KB of flash) and passes the certificates as `MQTT_TLS`; plain builds leave it out. See [MQTT over TLS](mqtt-tls.md). * With `embassy-net 0.9`, the stack handle is `Stack<'static>` and TCP sockets are created with `TcpSocket::new(*stack, ...)`. * In the final binary crate, `esp-rtos` must enable `features = ["embassy", "esp-radio", "esp-alloc"]`; omitting `esp-radio` leads to unresolved `esp_rtos_*` linker errors. diff --git a/docs/lan.md b/docs/lan.md index 999a665..e2ca10f 100644 --- a/docs/lan.md +++ b/docs/lan.md @@ -11,7 +11,7 @@ enabled = true 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). +Off by default. It works on the PC board and on ESP WiFi builds. An LTE build never has it (one uplink per build, and a carrier network doesn't let the phone reach the device): xtask says so and leaves it out. ## How it fits together @@ -23,7 +23,7 @@ Off by default. It is on the PC board only for now; ESP WiFi builds ignore it un * **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. +* **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. Boards without an mDNS library use the responder in `lan_mdns.rs`: `lan_mdns_response` answers questions for the service's PTR, the instance's SRV and TXT, and the host's A record (`opencar-.local`) with all four records, and `lan_mdns_announcement` builds the unsolicited announcement. Its instance name is the BLE name and the first four characters of the key ID, so two devices stay apart. A query from a port other than 5353 is a one-shot "legacy unicast" query (what the app sends): the answer goes back to its sender with its ID and questions, TTLs of 10 s and no cache-flush bit; other answers go to the group. Nothing is served before the device has an identity: the handshake needs it, and the probe and mDNS name it. @@ -31,6 +31,15 @@ Nothing is served before the device has an identity: the handshake needs it, and `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. +## ESP board + +With `[network.lan] enabled = true` on a WiFi build, xtask enables board-esp's `lan` feature and spawns `board_esp::start_lan` on the WiFi stack (`boards/esp/src/lan.rs`): + +* **Connections:** one task per connection plus a spare (`LAN_MAX_CLIENTS + 1`), each with its own `TcpSocket` on the port. The spare accepts the connection after the last free slot, so `lan_accept` can give it the slot of a connection without a session, or refuse it. A connection runs its reader, its writer and a once-a-second `lan_should_close` check side by side; whichever ends first closes it. TCP keepalives every 20 s and a 60 s timeout drop a peer that vanished. +* **UDP discovery** on `LAN_UDP_DISCOVERY_PORT`, and **mDNS** on port 5353 in the group, with the responder above. The same task checks the address every 5 s (DHCP renewals, WiFi reconnections), reports it with `set_lan_address`, and on a new address joins the group again and announces twice, a second apart. +* **Sockets:** the stack gets `LAN_MAX_CLIENTS + 3` more (the connections, discovery, mDNS) next to MQTT, the CAN logger and DNS. +* **Cost:** each connection task holds 3 KB of TCP buffers and room for one frame; the logs say the free heap when a connection opens and closes, and how long each handshake took (`LAN: handshake answered in … ms`). That is how to measure it on a board. + ## Trying it `tools/lan_client.py` plays the app's part. With the PC firmware running the virtual car and `[network.lan] enabled = true`: From da1e97e3cf2544eaac17ad0b46107d3ff6cc797d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 00:20:34 +0000 Subject: [PATCH 5/8] docs(lan): say how to measure LAN direct's cost on an ESP Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiUcxbhmHS339r4nWo6 --- docs/lan.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/lan.md b/docs/lan.md index e2ca10f..161f8df 100644 --- a/docs/lan.md +++ b/docs/lan.md @@ -38,7 +38,7 @@ With `[network.lan] enabled = true` on a WiFi build, xtask enables board-esp's ` * **Connections:** one task per connection plus a spare (`LAN_MAX_CLIENTS + 1`), each with its own `TcpSocket` on the port. The spare accepts the connection after the last free slot, so `lan_accept` can give it the slot of a connection without a session, or refuse it. A connection runs its reader, its writer and a once-a-second `lan_should_close` check side by side; whichever ends first closes it. TCP keepalives every 20 s and a 60 s timeout drop a peer that vanished. * **UDP discovery** on `LAN_UDP_DISCOVERY_PORT`, and **mDNS** on port 5353 in the group, with the responder above. The same task checks the address every 5 s (DHCP renewals, WiFi reconnections), reports it with `set_lan_address`, and on a new address joins the group again and announces twice, a second apart. * **Sockets:** the stack gets `LAN_MAX_CLIENTS + 3` more (the connections, discovery, mDNS) next to MQTT, the CAN logger and DNS. -* **Cost:** each connection task holds 3 KB of TCP buffers and room for one frame; the logs say the free heap when a connection opens and closes, and how long each handshake took (`LAN: handshake answered in … ms`). That is how to measure it on a board. +* **Cost:** each connection task holds 3 KB of TCP buffers and room for one frame; the logs say the free heap when a connection opens and closes, and how long each handshake took (`LAN: handshake answered in … ms`). That is how to measure it on a board: the flash cost is the difference between the image sizes of the same config with `[network.lan] enabled` on and off, the RAM cost shows in the free heap before the first connection and with one and two clients, and the handshake time in its log line. ## Trying it From 1289f3cd6d220fa4e116f9dc26065a9105f5cad3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 01:54:29 +0000 Subject: [PATCH 6/8] 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 7/8] 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 ceb7500e3f72e53ffe0723f79b037f4d85dcba7a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 04:59:43 +0000 Subject: [PATCH 8/8] 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