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..3f44aea --- /dev/null +++ b/boards/esp/src/lan.rs @@ -0,0 +1,311 @@ +//! 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()) { + // A newer connection took the slot back between two checks. + if !core_interface::lan_is_open(conn) { + return "slot taken back"; + } + 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..3e16d84 --- /dev/null +++ b/core-interface/src/lan_mdns.rs @@ -0,0 +1,214 @@ +//! 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) -> Option { + let service = format!("{LAN_MDNS_SERVICE}.local"); + // The same label as every board announces (two devices with the same name stay + // apart by their key IDs). + let instance_label = crate::lan::lan_mdns_instance_name(instance_name)?; + let instance = format!("{instance_label}.{service}"); + let host = format!("opencar-{key_id}.local"); + Some(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 cf503b9..a6c0ceb 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; @@ -186,6 +187,7 @@ pub use lan::{ 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, }; +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 8ae6b9c..584c8d8 100644 --- a/core-interface/tests/lan.rs +++ b/core-interface/tests/lan.rs @@ -3,19 +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_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, + 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_instance_name, 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 _; @@ -488,6 +488,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()); +} + #[test] fn the_mdns_instance_name_tells_devices_with_the_same_name_apart() { boot(); diff --git a/docs/architecture.md b/docs/architecture.md index 61643cb..ec63ef4 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 dead975..59a16f3 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:** 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` 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. +* **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 the same on every board), 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. 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: 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 `tools/lan_client.py` plays the app's part. With the PC firmware running the virtual car and `[network.lan] enabled = true`: