diff --git a/IDF-ISSUE-1-localise.patch b/IDF-ISSUE-1-localise.patch new file mode 100644 index 00000000000..99d82eb9b8e --- /dev/null +++ b/IDF-ISSUE-1-localise.patch @@ -0,0 +1,97 @@ +Subject: [PATCH] nan_usd: instrument the USD action-frame Rx path (diagnostic) + +Diagnostic only; not a fix. Applies to cb73317. + +- Logs every entry to esp_nan_de_rx_action() with A1/A2/A3 and the first six + body bytes, and which early-return gate failed, if any. +- Logs every remain-on-channel request with allow_broadcast and its return + code, and every WIFI_EVENT_ROC_DONE. +- With -DLOCALISE_TX_BCAST=1/2/3 (C define), esp_nan_de_tx() replaces the NAN + Network ID with ff:ff:ff:ff:ff:ff in A1 / A3 / both, for group-addressed + SDFs only. This is the experiment showing A3 decides delivery. + +MSG_ERROR so the result does not depend on the configured log level. + +diff --git a/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c b/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c +index 30d54c8a8e..1ce5f5bcfd 100644 +--- a/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c ++++ b/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c +@@ -127,6 +127,7 @@ static void nan_de_tx_event_handler(void *arg, esp_event_base_t event_base, + } else if (event_id == WIFI_EVENT_ROC_DONE) { + wifi_event_roc_done_t *evt = (wifi_event_roc_done_t *)event_data; + int freq = esp_nan_chan_to_freq(evt->channel); ++ wpa_printf(MSG_ERROR, "NAN-USD: ROC_DONE chan=%u", (unsigned)evt->channel); + if (freq == -1) { + wpa_printf(MSG_ERROR, "Invalid channel received from ROC done handler"); + return; +@@ -144,8 +145,18 @@ int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t cha + struct ieee80211_hdr *rx_hdr = (struct ieee80211_hdr *)hdr; + struct nan_de *nan_de = NULL; + int freq; ++ static unsigned s_rx_count; ++ ++ /* LOCALISE: log every entry, MSG_ERROR so it does not depend on log level. */ ++ s_rx_count++; ++ wpa_printf(MSG_ERROR, "NAN-USD: rx_action #%u len=%u chan=%u A1=" MACSTR " A2=" MACSTR " A3=" MACSTR ++ " body=%02x %02x %02x%02x%02x %02x", ++ s_rx_count, (unsigned)len, (unsigned)channel, MAC2STR(rx_hdr->addr1), MAC2STR(rx_hdr->addr2), ++ MAC2STR(rx_hdr->addr3), len > 0 ? payload[0] : 0, len > 1 ? payload[1] : 0, len > 2 ? payload[2] : 0, ++ len > 3 ? payload[3] : 0, len > 4 ? payload[4] : 0, len > 5 ? payload[5] : 0); + + if (len < 6) { ++ wpa_printf(MSG_ERROR, "NAN-USD: gate len<6"); + /* Frame too short for NAN-SDF frame */ + return ESP_FAIL; + } +@@ -169,6 +180,8 @@ int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t cha + /* Received a valid NAN Service Discovery Frame */ + } else { + /* Frame is not a NAN SDF frame */ ++ wpa_printf(MSG_ERROR, "NAN-USD: gate not-SDF cat=%u pa=%u oui=%06x type=%u", ++ category, public_action, (unsigned)oui_value, oui_type); + return ESP_FAIL; + } + +@@ -179,8 +192,10 @@ int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t cha + } + + if (!nan_usd_try_lock_active(&nan_de)) { ++ wpa_printf(MSG_ERROR, "NAN-USD: gate lock/inactive"); + return ESP_FAIL; + } ++ wpa_printf(MSG_ERROR, "NAN-USD: -> nan_de_rx_sdf freq=%d", freq); + nan_de_rx_sdf(nan_de, rx_hdr->addr2, rx_hdr->addr3, freq, payload, len - 6); + NAN_USD_DATA_UNLOCK(); + return ESP_OK; +@@ -204,6 +219,18 @@ static int esp_nan_de_tx(void *ctx, unsigned int freq, unsigned int wait_time, + req->wait_time_ms = wait_time; + memcpy(req->dest_mac, dst, ETH_ALEN); + memcpy(req->bssid, bssid, ETH_ALEN); ++#ifdef LOCALISE_TX_BCAST ++ /* LOCALISE experiment: replace the NAN Network ID 51:6f:9a:01:00:00 (multicast, not broadcast) ++ * with ff:ff:ff:ff:ff:ff. Bit 0 = A1 (dest), bit 1 = A3 (BSSID). Only group-addressed SDFs are touched. */ ++ if (dst[0] & 1) { ++ if (LOCALISE_TX_BCAST & 1) { ++ memset(req->dest_mac, 0xff, ETH_ALEN); ++ } ++ if (LOCALISE_TX_BCAST & 2) { ++ memset(req->bssid, 0xff, ETH_ALEN); ++ } ++ } ++#endif + req->no_ack = false; + req->data_len = buf_len; + req->rx_cb = esp_nan_de_rx_action; +@@ -250,7 +277,11 @@ static int esp_nan_de_listen(void *ctx, unsigned int freq, unsigned int duration + req->done_cb = NULL; + req->allow_broadcast = true; + +- if (esp_wifi_remain_on_channel(req) != ESP_OK) { ++ esp_err_t roc_err = esp_wifi_remain_on_channel(req); ++ /* LOCALISE: show every listen request the subscriber makes, and whether the library accepted it. */ ++ wpa_printf(MSG_ERROR, "NAN-USD: ROC req chan=%d dur=%u allow_bcast=%d -> %d", channel, duration, ++ req->allow_broadcast, roc_err); ++ if (roc_err != ESP_OK) { + wpa_printf(MSG_ERROR, "ROC request failure"); + os_free(req); + return ESP_FAIL; diff --git a/IDF-ISSUE-1-nan-usd-rx.md b/IDF-ISSUE-1-nan-usd-rx.md new file mode 100644 index 00000000000..1f822b1f109 --- /dev/null +++ b/IDF-ISSUE-1-nan-usd-rx.md @@ -0,0 +1,177 @@ +# NAN-USD: group-addressed SDFs are dropped before the ROC Rx callback unless A3 is broadcast, so USD discovery never completes + +**Status: draft, ready.** Measured on current silicon (ESP32 rev v3.1 and +ESP32-S2) with instrumented logging in the open-source receive path. The loss +is localised to below the supplicant, and the deciding address field is +identified. + +## Summary + +With `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y`, a USD subscriber that is listening on +the right channel never has its ROC receive callback (`rx_cb`, +`esp_nan_de_rx_action()`) entered for the publisher's Service Discovery +Frames, so discovery never completes. Two ESP boards running the unmodified +`usd_publisher` / `usd_subscriber` examples never discover each other, in +either role assignment. + +The frames are dropped because their **Address 3 (BSSID) is the NAN Network ID +`51:6f:9a:01:00:00`, not broadcast**. Changing only A3 to +`ff:ff:ff:ff:ff:ff` makes them arrive and discovery complete in under a +second. Changing only A1 does not. + +This contradicts the documented behaviour of `wifi_roc_req_t.allow_broadcast`, +which the USD listen path sets to `true`: + +> If set to true, broadcast/multicast action frames from any network +> (Address3/BSSID=ANY) will be received in the ROC Rx callback + +## Environment + +| | | +|---|---| +| ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | +| Targets | ESP32-U4WDH **rev v3.1** (40 MHz crystal) and ESP32-S2FNR2 rev v1.0 | +| Projects | `examples/wifi/wifi_aware/usd_publisher` and `usd_subscriber`, unchanged apart from logging | +| Config | `CONFIG_IDF_EXPERIMENTAL_FEATURES=y`, `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y`, `CONFIG_ESP_WIFI_DEBUG_PRINT=y`, `esp_log_level_set("wpa", ESP_LOG_DEBUG)` | +| Mode | `WIFI_MODE_NULL`, no association, default channel 6 | +| Capture | a third ESP32 in promiscuous mode on channel 6, written to pcap | + +An earlier round on an ESP32 rev v0.0 and an ESP32-S3 showed the same +outcome. Everything below is from the rev v3.1 and S2 boards. + +## Instrumentation + +All in open source, in `esp_supplicant/src/esp_nan_usd.c`, at `MSG_ERROR` so +the result does not depend on log level (patch attached as +`IDF-ISSUE-1-localise.patch`): + +- the first line of `esp_nan_de_rx_action()` logs every entry with A1, A2, A3 + and the first six body bytes, and each early-return gate logs which gate + failed; +- `esp_nan_de_listen()` logs every `esp_wifi_remain_on_channel()` request, + its `allow_broadcast` value and its return code; +- the `WIFI_EVENT_ROC_DONE` handler logs each completion. + +## What was measured + +**The subscriber is listening on the right channel the whole time.** In a 60 s +run it issued 56 consecutive ROC requests on channel 6, 1000 ms each, +`allow_broadcast=1`, every one returning `ESP_OK`, each followed by +`ROC_DONE`: + +``` +D (677) wpa: NAN: Assigned new subscribe handle 1 for ESP-USD-TEST +E (687) wpa: NAN-USD: ROC req chan=6 dur=1000 allow_bcast=1 -> 0 +E (1687) wpa: NAN-USD: ROC_DONE chan=6 +E (1687) wpa: NAN-USD: ROC req chan=6 dur=1000 allow_bcast=1 -> 0 +... +``` + +**The publisher's SDFs are on the air, well-formed and strong.** In the same +60 s, the sniffer captured 134 USD publish SDFs from the publisher on channel +6 at about −10 dBm: Public Action, Vendor Specific, WFA OUI, OUI type `0x13`, +SDA and SDEA attributes, with A1 = A3 = `51:6f:9a:01:00:00`. Two other NAN +devices nearby added 164 more SDFs on channel 6, at −32 and −61 dBm. + +**`rx_cb` is never entered.** Not once for any of those roughly 300 frames. +Because the entry log is the first statement in the callback, no gate in the +open-source path is involved. The frames are discarded below the supplicant. + +The same holds with the roles swapped (ESP32 publishing, ESP32-S2 +subscribing): 39 accepted ROC windows on channel 6, 87 publish SDFs on air, +zero callback entries, no discovery. + +## The deciding experiment + +The publisher was rebuilt so that `esp_nan_de_tx()` replaces the NAN Network +ID with `ff:ff:ff:ff:ff:ff` in A1, in A3, or in both, for group-addressed SDFs +only. Nothing else changed. ESP32-S2 publishing, ESP32 rev v3.1 subscribing: + +| A1 (DA) | A3 (BSSID) | `rx_cb` entered | discovery | +|---|---|---|---| +| `51:6f:9a:01:00:00` | `51:6f:9a:01:00:00` | never (134 frames on air) | never | +| `ff:ff:ff:ff:ff:ff` | `51:6f:9a:01:00:00` | never (101 frames on air) | never | +| `51:6f:9a:01:00:00` | `ff:ff:ff:ff:ff:ff` | yes | 1.0 s after boot | +| `ff:ff:ff:ff:ff:ff` | `ff:ff:ff:ff:ff:ff` | yes | 0.9 s after boot | + +With A3 broadcast, the first frame arrives and is processed normally: + +``` +E (867) wpa: NAN-USD: rx_action #1 len=24 chan=6 A1=ff:ff:ff:ff:ff:ff A2=7c:e8:b1:4a:11:14 A3=ff:ff:ff:ff:ff:ff body=04 09 506f9a 13 +D (877) wpa: NAN: RX SDF from 7c:e8:b1:4a:11:14 freq=2437 len=18 +I (897) wpa: NAN_USD DISCOVERY_RESULT - subscribe_id = 1 peer_publish_id = 1 peer_address = 7c:e8:b1:4a:11:14 service_protocol_type = 0 +``` + +The reverse direction (ESP32 publishing with A3 broadcast, ESP32-S2 +subscribing) also discovers at once: the subscriber matched before its USB +console attached, about a second after boot, and its unicast follow-ups to the +publisher are on air from the start of the capture. With the stock A3 it +never discovers. + +**Unicast frames are not affected.** Follow-ups addressed to the receiver's +own MAC, with A3 still `51:6f:9a:01:00:00`, reach `rx_cb` normally; the +ESP32 publisher logged 20 such entries and 11 follow-up receptions. So the +filter applies to group-addressed frames whose A3 is not broadcast. + +## Why ESP-to-ESP USD can never work as shipped + +The supplicant itself transmits USD SDFs with A3 set to the NAN Network ID. +In `components/wpa_supplicant/src/common/nan_de.c`, `nan_de_tx_multicast()`: + +```c + if (srv->is_p2p) { + network_id = p2p_network_id; + bssid = wildcard_bssid; + } else { + network_id = nan_network_id; + bssid = nan_network_id; + } +``` + +So every non-P2P USD publish or active subscribe an ESP sends carries an A3 +that another ESP's receive path discards. Discovery between two ESPs cannot +complete, in either direction, whatever the timing or channel. + +## Already ruled out + +- **Channel.** Both ends on channel 6; `esp_nan_chan_to_freq(6)` = 2437. The + subscriber is on channel 6 for essentially the whole run (ROC log above). +- **The open-source gate chain.** The entry log precedes every gate and never + prints, so none of `len < 6`, category/action/OUI/type, + `esp_nan_chan_to_freq()` or `nan_usd_try_lock_active()` is involved. +- **Signal level.** The publisher was received by the sniffer at −10 to + −17 dBm, the other devices at −32 and −61 dBm; none reached `rx_cb`. +- **Transmit failure.** The frames are on air, and with A3 changed the same + frames are received. +- **Chip.** ESP32 rev v3.1 and ESP32-S2 behave identically, both directions. +- **`.type` / active vs passive.** The USD path ignores it: + `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()` hardcodes `.active = false` and + `ESP_USD_PUBLISH_DEFAULT_PARAMS()` hardcodes `.unsolicited = true, + .solicited = true`. + +## Impact + +NAN-USD discovery does not work between ESP devices on ESP-IDF today. It also +cannot receive standard USD SDFs from other implementations, since the Wi-Fi +Aware specification puts a non-broadcast value in A3 (the NAN Cluster ID in +v4.0; the comment in `nan_de.c` near the follow-up path discusses this). The +same filter also drops NAN-Sync SDFs, whose A3 is a Cluster ID such as +`50:6f:9a:01:db:dd`: none of those reached `rx_cb` either. + +Since `ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES` +and not on `SOC_WIFI_NAN_SUPPORT`, USD is the only Wi-Fi Aware mode on parts +such as the ESP32-S3, and the only one that can run alongside a STA +association. + +## Asks + +1. **Make `allow_broadcast` behave as documented**: when set on a ROC + request, deliver group-addressed Public Action frames to `rx_cb` whatever + their A3, not only when A3 is broadcast. +2. Until then, consider whether `nan_de_tx_multicast()` should use the + wildcard BSSID for A3 on the non-P2P path, as it already does for P2P. + That alone makes ESP-to-ESP USD work (measured above), though it does not + fix reception from other implementations. +3. If the current filtering is intended, please correct the + `allow_broadcast` documentation, and say how a USD subscriber is meant to + receive SDFs whose A3 is the NAN Network ID or a Cluster ID. diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md new file mode 100644 index 00000000000..54d548aa029 --- /dev/null +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -0,0 +1,150 @@ +# NAN: a spurious error-level availability log, and ACCEPTED reported after a parse error + +**Status: draft, not filed.** Two small defects, both reproduced on three +targets. A third ask about NDP Response timing was withdrawn — see +[The withdrawn timing ask](#the-withdrawn-timing-ask). + +## Summary + +Wi-Fi Aware data paths between an ESP32 and an Android phone work. On +current silicon they came up in **16 of 16** runs — 6 on an ESP32-S2 +(solicited), 6 on an ESP32 rev v3.1 (solicited), 4 on the same v3.1 +(unsolicited). + +Two defects remain, neither affecting whether the data path forms: + +1. An **error-level log** fires on runs that succeed. +2. The NDP Response reports **ACCEPTED** after the parse that built it + returned an error. + +## Environment + +| | | +|---|---| +| ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | +| Targets | ESP32-U4WDH **rev v3.1**, ESP32-S2 (Lolin S2 Mini) | +| Example | `wifi_aware/nan_publisher`, solicited and unsolicited | +| Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | +| Capture | monitor on channel 6 with ACK frames recorded, zero drops | + +## Ask 1 — do not log an error for a map carrying only Potential entries + +The ESP logs + +``` +E (12422) wifi:Avail: missing a conditional or committed entry +``` + +on runs where the NDP **confirms successfully**. It appears on **all three +targets**, including every one of the 16 successful runs on current silicon. +It never indicated a negotiation failure: it is an error-level message for a +non-error. + +The peer's NDP Request carries two Availability attributes — map 0 with a +**conditional** channel-6 entry covering all 32 slots, and map 1 with +**potential** 5 GHz entries (op class 128, bitmap `0x0020`, the block +centred on 155 containing NAN's 5 GHz discovery channel 149). Potential-only +is exactly what a map-1 entry is for. + +`nan_parse_ndp_req` calls `nan_dp_parse_availability` from an attribute walk +(backward branch `0x442 -> 0x135`), consistent with the error coming from the +map-1 pass. Per-map storage exists — `nan_get_avail_by_map_id` walks 92-byte +records keyed on map ID — but it is called from `nan_sched_alloc_conditional`, +`nan_sched_allocate_crbs` and `nan_dp_indicate_faw_start`, never from the +parser. + +This message sent two independent investigations down the wrong path for +days. + +## Ask 2 — do not report ACCEPTED after the parse returned an error + +In `ieee80211_nan_datapath.o`, `nan_dp_parse_availability` logs and returns +262 at `0x1a8`, jumping to `0x41f` — two instructions before `retw.n` at +`0x422`. The success path returns 0 at `0x417`. The M2 the ESP then +transmits carries status `0x11`, ACCEPTED. The log and the frame disagree. + +## The withdrawn timing ask + +Earlier revisions asked Espressif to change how the esp32 library schedules +the NDP Response, on the evidence that its first transmission was never +acknowledged and setup succeeded in only 9 of 16 runs. **That evidence came +entirely from one board, and that board turned out to be faulty.** + +The board was a SparkFun ESP32 Thing, ESP32-D0WDQ6 **rev v0.0**, 26 MHz +crystal, external flash. Its radio link to the phone is bad in both +directions: + +| | rev-0 Thing | ESP32 rev v3.1 | ESP32-S2 | +|---|---|---|---| +| transmissions per unicast frame | **9.81** | 1.00 | 1.01 | +| first transmission acked, 0–4 ms into DW | **44/388 = 11 %** | 275/278 = 99 % | — | +| data path established | 9 of 16 | 6 of 6 | 6 of 6 | + +At 0–4 ms into the Discovery Window the peer is certainly listening, and the +phone still failed to receive or decode **89 %** of that board's frames. The +same board also received the phone's 48 Mbps OFDM poorly when used as a +sniffer. A bidirectional RF-level problem — carrier frequency offset from +the 26 MHz crystal, or rev-0 RF — fits both directions; it was not measurable +with the available equipment. + +So the M2 failures cannot be attributed to transmit timing, and the ask is +withdrawn rather than reworded. + +### What remains interesting about it + +One observation survives as a curiosity rather than a defect. The esp32 +library answers inside the Discovery Window the request arrived in, with a +guard before the end of slot 0 of **1.841 ms = 1.80 TU** on v3.1 (mean of +six runs, sd 0.051 ms) — a designed constant, within 2 µs of 1843.2 µs. + +On the rev-0 board the equivalent guard was 1.167 ms. The ratio, 0.634, sits +between 26/40 = 0.650 and 25/40 = 0.625, which a crystal-derived scaling of +the guard would produce; 26/40 predicts a delay of 15.188 ms against 15.217 +measured. The direction requires a guard converted to ticks with the real +26 MHz crystal and then consumed against a 40 MHz timebase — not a +hard-coded 40 used where the real value belonged, which would lengthen the +guard rather than shorten it. + +Nothing in the blob supports or refutes it. Neither `libnet80211.a` nor +`libpp.a` references any crystal or clock frequency helper among their 1453 +and 447 undefined symbols; no literal `40000000`, `26000000`, `73728` or +`1843200` appears; `ieee80211_nan_datapath.o`'s literal pool holds nothing of +guard-time magnitude, only log line numbers; `hal_tsf.o` has no literals at +all. The only clock-dependent external called is ROM's `ets_delay_us`. + +A rev v3.x board with a 26 MHz crystal would settle it — predicted first M2 +at about 15.19 ms. We have no such board, and with the RF fault identified +the question is academic for ESP-IDF purposes. + +It is worth noting that the two anomalies on that board may share one cause. +A clock problem that scaled a guard interval by roughly 26/40 would also +produce a carrier frequency offset, and carrier offset degrades OFDM decode +in both directions — which is exactly the 11 %-versus-99 % asymmetry and the +poor 48 Mbps reception. One faulty crystal or clock path explains the timing +floor and the RF loss together, and neither needs an ESP-IDF defect to +account for it. + +## Previously fenced observations, now attributed to the faulty board + +- **The ESP missing M1 up to seven times running** — zero occurrences on + v3.1 or S2. +- **Run 19's M2 constructed and never transmitted** — zero occurrences on + v3.1 or S2. +- **Off-AP discovery failing with an unsolicited publish** — does not + reproduce. The v3.1 board discovered in 0.55–0.76 s in 4 of 4 runs, with + about 114 group-addressed publish SDFs per run, and the data path came up + every time. The phone does not ignore group-addressed SDFs off-AP; runs 5 + and 6 failed because of the publisher. + +## Related + +`IDF-ISSUE-3-nan-schedule-request.md` — the ESP has no handling for NAF +subtypes 10–13, so a peer's Schedule Request is never answered and idle data +paths are torn down. That one reproduces on every target and is unaffected +by any of the above. + +## Credit + +Hardware, captures and decode by the bench session running the monitor, +which identified the faulty board and supplied the measurements that +withdrew the timing ask. diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md new file mode 100644 index 00000000000..c5c1925a955 --- /dev/null +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -0,0 +1,225 @@ +# NAN: Schedule Request from a peer is never answered, and idle data paths are torn down + +**Status: draft, ready.** The mechanism is identified in the binary, and the +behaviour is reproduced on current silicon (ESP32 rev v3.1 and ESP32-S2) as +well as on the first board. The impact is narrower than first thought: idle +data paths are torn down, data paths carrying traffic survive. + +## Summary + +After a NAN data path is established, an Android peer sends a unicast NAN +Action Frame **Schedule Request (subtype 10)**. The ESP acknowledges it at the +link layer and then does nothing: no Schedule Response (subtype 11) is ever +transmitted, and nothing is logged. The peer retries once, waits, and then +terminates the data path locally. + +The ESP has **no handling for NAF subtypes 10–13 at all**. + +## Environment + +| | | +|---|---| +| ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | +| Targets | ESP32-U4WDH **rev v3.1** and ESP32-S2FNR2 rev v1.0 (also ESP32-D0WDQ6 rev v0.0, see below) | +| Firmware | `wifi_aware/nan_publisher`, solicited and unsolicited | +| Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | +| Capture | a separate ESP32 / ESP32-S2 monitor on channel 6, with ACK frames recorded | + +## Reproduced on current silicon + +The first runs (7, 8, 9 below) used an ESP32 rev v0.0 board that later turned +out to have an RF fault. Everything was therefore repeated on an ESP32 rev +v3.1 and an ESP32-S2, where the data path itself comes up reliably (16 of 16 +runs). The Schedule Request behaviour is unchanged. + +**Idle data path, ESP32 rev v3.1, unsolicited publish, no traffic after +confirm:** + +| run | phone on an AP? | Schedule Requests (after confirm) | ESP response | NDP lifetime | how it ended | +|---|---|---|---|---|---| +| 39 | yes | +12.0 s, +18.0 s, both MAC-ACKed | none | 21.0 s | phone HAL `eventDataPathTerminated` | +| 40 | yes | +12.0 s, +18.0 s, both MAC-ACKed | none | 20.9 s | phone HAL `eventDataPathTerminated` | +| 41 | no | +12.0 s, +18.0 s, both MAC-ACKed | none | 20.9 s | phone HAL `eventDataPathTerminated` | +| 42 | no | +12.0 s, +18.0 s, both MAC-ACKed | none | 21.0 s | phone HAL `eventDataPathTerminated` | + +In all four, the phone also sent 2–6 Schedule Update Notifications (none +answered), the ESP logged nothing after `NDP confirmed`, and no NDP +Termination frame appeared on air from either side. + +**Across every current-silicon run** (runs 23–42: six on the ESP32-S2, fourteen +on the ESP32 rev v3.1, most with a 2 s keepalive), the phone sent a Schedule +Request in 19 of 20 runs, 23 frames in all, and the ESP MAC-ACKed every one. +The ESP transmitted only NDP Response (subtype 6) in every run, and never a +Schedule Response (subtype 11) or any other subtype in `0x0a`–`0x0d`. + +The rule is the same in all of them, 12 s, then 6 s, then teardown at 21 s +when idle. It does not depend on the chip, on publish type, or on whether the +phone is associated to an AP. + +## First observed, ESP32 rev v0.0, in three runs under both AP conditions + +Run 7 (phone associated to an AP on channel 64), run 8 (phone not associated +at all) and run 9 (not associated, with keepalive traffic) all show the ESP +never answering. Runs 7 and 8 were idle and both ended in a teardown: + +1. NDP confirms; the IPv6 data path works. A TCP probe to the peer's + link-local address over `aware_data0` is refused, which proves the peer's + stack answered. +2. About **12 s after confirm**, the phone sends a unicast NAF **Schedule + Request** to the ESP. The ESP **ACKs it** — captured directly as ACK-by-RA, + not inferred. +3. About **6 s later** the phone sends a second Schedule Request. The ESP ACKs + that too. +4. No Schedule Response (subtype 11) appears anywhere in either capture, and + the ESP logs nothing. +5. The phone terminates the data path locally — HAL + `eventDataPathTerminated`, and the app's `onLost` at 26.4 s. In run 8 there + is **no over-the-air NDP Termination from the phone at all**; it simply + gives up. + +The Schedule Request is not an unreasonable one. Its content in run 8: + +- **map 0** — potential channel 6 slot 0 (`01000000`), plus **COMMITTED** + channel 6 slots 1–31 (`feffffff`) +- **map 1** — 5 GHz potential (band `fff0ffff`, op class 128 `0x0020`, slots + `000f0000`) +- plus NDC (15), NDL (4), NDL-QoS (3) + +The phone is offering to **commit to exactly the channel-6 schedule the ESP +itself committed to** (`crb1=[2,31]`). This is the peer doing the right thing +and converting a conditional arrangement into a committed one. The ESP ignores +it. + +## Confirmed across every capture + +NAN Action Frames are Public Action / Vendor Specific / WFA OUI with **OUI +type `0x18`** and the subtype in the following byte. (The Service Discovery +Frame uses OUI type `0x13` instead, and carries attributes directly.) +Counting subtypes by sender across every capture — runs 3 to 16: + +| sender | subtypes ever transmitted | +|---|---| +| phone | `0x05` M1, `0x06` M2, `0x09` NDP-Term, **`0x0a` Schedule Request**, `0x0d` Schedule Update Notification | +| ESP | `0x05` M1, `0x06` M2, `0x09` NDP-Term — **and nothing else, in any run** | + +The ESP sends only NDP **setup and teardown** frames: M1 when it initiates +(run 4, as subscriber), M2 when it responds, and one NDP Termination (run 7). +**It never transmits any subtype in the range `0x0a`–`0x0d`.** + +That set — 5, 6, 9 — is exactly the set the binary has handlers for. The +dispatcher `nan_rx_naf` parses 5 to 9 and the object carries construct and +send functions for the same range, so the on-air behaviour and the binary +agree precisely about what this implementation can do. + +**Subtype `0x0b`, Schedule Response, appears zero times in any capture**, +while the phone sends Schedule Requests repeatedly. + +Schedule Requests appear only in the three runs that established a data path, +which is expected — runs 8 (2 frames), 9 (17) and 16 (1). The phone also sends +Schedule Update Notifications in all three: 3, 5 and 5 frames. None is ever +answered. + +Run 9's 17 frames are worth a note. The bench session reports three *logical* +Schedule Requests in that run, so the phone appears to retry each one roughly +five or six times before giving up — the same shape as the ESP's own M2 +bursts. The phone is not asking once and forgetting; it is asking +insistently and being ignored. + +## Mechanism, from the binary + +`ieee80211_nan_datapath.o` in `libnet80211.a`. The same five parse handlers, +and no schedule handlers, are present in the `esp32`, `esp32s2`, `esp32c5` and +`esp32c61` libraries at `7cd4d7b2`. In the esp32 library, the receive dispatcher +`nan_rx_naf` references exactly **five** parse handlers: + +``` +nan_parse_ndp_req subtype 5 Data Path Request +nan_parse_ndp_resp subtype 6 Data Path Response +nan_parse_ndp_confirm subtype 7 Data Path Confirm +nan_parse_ndp_security_install subtype 8 Data Path Key Installment +nan_parse_ndp_terminate subtype 9 Data Path Termination +``` + +The complete function list for the object confirms there is no counterpart for +any of: + +``` +subtype 10 Schedule Request +subtype 11 Schedule Response +subtype 12 Schedule Confirm +subtype 13 Schedule Update Notification +``` + +There is no `nan_parse_sched_*`, no `nan_construct_sched_*`, and no +`nan_send_sched_*`. Every `nan_sched_*` symbol present +(`nan_sched_construct_availability`, `nan_sched_allocate_crbs`, +`nan_sched_alloc_conditional` and so on) is availability construction for the +NDP exchange, not NAF schedule negotiation. + +`nan_rx_naf` carries the string `Unknown NAN Action subtype - %d`, and that +string lives in `.rodata_wlog_error.144` — it is an **error-level** message. + +## No log is emitted + +`nan_rx_naf` carries the string `Unknown NAN Action subtype - %d`, and that +string sits in `.rodata_wlog_error.144` — **error level**. If the dispatcher's +default case were reached, that line should appear. + +It does not. Across runs 2, 3, 7, 8 and 9, and the current-silicon idle +runs 39–42, there are **zero** occurrences of `Unknown NAN Action subtype` +in any ESP log. In run 9 the console was captured +continuously for about 110 s: the last line is `NDP confirmed` at 12.8 s, +followed by 100 s of silence while three Schedule Requests arrived, at least +the first of them MAC-acknowledged. Error-level `wifi:` lines are plainly not +suppressed in these logs — `Avail: missing a conditional or committed entry` +prints in the same runs. + +So the frames appear to be discarded somewhere before the dispatcher's default +case, despite the MAC acknowledging them. This cannot be proved from outside +the libraries — there may be a path into `nan_rx_naf` that skips the log — so +the accurate statement is: **no log is emitted, although error-level `wifi:` +logs are visible in the same capture.** + +## Impact + +**An idle NAN data path is torn down about 20 s after it is established.** A +data path carrying traffic is not: in run 9 the link stayed up for the full +100 s capture, and in run 16 — with the duplicate-probe bug fixed, so a +single keepalive series every 2 s rather than two — it stayed up to the end +of a 55 s capture. No teardown and no `eventDataPathTerminated` in either. + +Traffic also changes how often the peer asks. On an idle link the Schedule +Requests came about 6 s apart (runs 7 and 8); with traffic they came about +30–36 s apart (run 9). The phone tolerates unanswered requests for at least +100 s when the link is in use. + +So the teardown observed in runs 7 and 8 required **both** conditions: an idle +link *and* an unanswered Schedule Request. State that as the observed +correlation, not as cause. Whether a spec-compliant Schedule Response would +by itself prevent the idle teardown cannot be known without a peer that +answers one, and no such peer was available. + +What is certain either way is the first half: there is no code to answer a +Schedule Request, so the ESP cannot participate in schedule renegotiation at +all. The user-visible consequence today is that an idle data path does not +survive, and that a peer's attempts to adjust the schedule are silently +ignored however often it tries. + +## Asks + +1. **Handle NAF Schedule Request (subtype 10) and reply with a Schedule + Response (subtype 11).** At minimum, accept a request that proposes a + schedule compatible with the one already committed, which is what the peer + sent here. +2. **Handle Schedule Update Notification (subtype 13)**, which the phone also + broadcasts after confirm and which is likewise unhandled. +3. **Do not silently discard unknown NAF subtypes on an active NDL.** A + MAC-acknowledged frame that produces no log at all, while error-level + `wifi:` logging is demonstrably working, suggests something upstream of + `nan_rx_naf` is dropping it. + +## Credit + +Captures, decode and the observation that the Schedule Requests go unanswered +come from the bench session running the hardware; the binary analysis is from +the captures it supplied. diff --git a/RESEARCH-dns-sd-wifi-aware.md b/RESEARCH-dns-sd-wifi-aware.md new file mode 100644 index 00000000000..330c2f9ef04 --- /dev/null +++ b/RESEARCH-dns-sd-wifi-aware.md @@ -0,0 +1,591 @@ +# DNS-SD + Wi-Fi Aware (NAN) support in CircuitPython — research + +Tracking: tyeth/deepsleep_espnow_wifi_and_ble_env_collector#18 +CircuitPython @ upstream `762ab15ca0` · ESP-IDF pin `v6.1-dev-6096-g29d36039e56` (adafruit `circuitpython-v6.1`) +**v6** — two reversals from new hardware work. **§13.1a: USD does *not* inherently break an associated STA** — the earlier result was my own channel pinning. **§13.2a: the USD defect is localised** — 407 SDFs reach the NIC and the discovery engine is never called. Also reframes "needs NAN silicon" as a firmware gate (§14.2a), and revises §6/§7.1/§9/§10/§12 which v4 had left stale. v5 fixed three errors a review caught; v1's central conclusion was wrong too (§11). + +## 0. TL;DR + +* **There are two Wi-Fi Aware protocols, not one**, and nearly every conclusion depends on which you mean: + * **NAN-Sync** — clustered, synchronised. Gives pairing and an **IPv6 datapath** (real sockets). Gated by `SOC_WIFI_NAN_SUPPORT`: **esp32, esp32s2, esp32c5, esp32c61, esp32s31** — *not* S3/C3/C6. **Exclusive radio mode in this IDF** (`wifi:mode : NAN`, confirmed on hardware). See §14.2a — "needs NAN silicon" is *not* a justified reading of that gate. + * **NAN-USD** — unsynchronised. Publish / subscribe / follow-up messages only, **no datapath, no pairing**. Runs on the **STA interface**, and needs **no special hardware at all**: `ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES` (`esp_wifi/Kconfig:620`), never on `SOC_WIFI_NAN_SUPPORT` (which gates only `ESP_WIFI_NAN_SYNC_ENABLE`, `:595-598`). Confirmed on hardware: the ESP32-S3, with zero `SOC_WIFI_NAN_SUPPORT`, ran the USD stack and put well-formed NAN frames on the air. **A USD publish is an ordinary Public Action vendor-specific management frame** — anything that can transmit one and do remain-on-channel could in principle speak USD. +* **USD looked like the right answer for issue #18 — hardware says not yet.** Two measured results (§13): + * **USD *does* coexist with STA — on the AP's channel** (§13.1a). An earlier version of this document claimed USD is inherently radio-owning; that was an artefact of my own harness pinning USD to channel 6 while the AP was on channel 1. Re-run with USD following the AP's channel, **both boards stayed associated for 100 s and the home channel never left the AP**. Off-channel, though, the link dies **silently** — no `STA_DISCONNECTED`, stale IP kept. **API rule that falls out of this: default USD's channel to the associated AP's, and only allow another when no STA is up.** +* **USD discovery is broken in the pinned IDF, and the defect is now localised** (§13.2a). The subscriber's own radio receives **407 NAN SDFs** while its USD subscribe is active, yet `nan_de_rx_sdf()` is **never entered** (proved with a positive control on the same log tag). Frames arrive at the NIC; the closed Wi-Fi blob never delivers them to the engine's remain-on-channel callback. Not a misconfiguration — a fileable upstream bug, with a reproducer that needs no NAN code. +* **NAN-Sync, by contrast, works** (§14): cluster → service match → **open (unsecured)** IPv6 datapath in **4.9 s from boot**, then ICMPv6 at **2 ms RTT, 0 % loss**, between a classic ESP32 and an ESP32-S31. Scope this honestly: **one run, ESP-to-ESP, both boards always-on, no security**. Issue #18's two distinguishing needs — **phone interop and deep sleep — are untested**, and phone interop requires `ESP_WIFI_NAN_SECURITY` / `ESP_WIFI_NAN_PAIRING`, which *are* gated on `IDF_EXPERIMENTAL_FEATURES`, the same label held against USD. For ESP-to-ESP without phones, ESP-NOW already does AP-less transport at lower wake cost; Sync's unique value lies precisely in the untested part. +* **Sync owns the radio — but honestly** (§14.4). Starting it on a live STA fires `STA_DISCONNECTED` immediately, clears the IP, refuses `esp_wifi_connect()` with `ESP_ERR_WIFI_MODE`, and gives STA back in **1.5 s** on stop. Every transition is observable, so `wifi.radio` can model it. USD, by contrast, keeps STA alive on the AP's channel (§13.1a) but fails *silently* when taken off it — so a USD binding's job is to pick the channel for you, while a Sync binding's job is to own the radio. +* **No common working denominator.** espressif has working Sync and broken USD; zephyr-cp has USD only — **and I never tested it**, so that column is "unknown", not "broken". Note too that Zephyr's hostap USD needs a driver with `remain_on_channel`/`send_action`, which the CYW43/AIROC driver lacks, so zephyr-cp USD reaches at most `frdm_rw612`. Either way Wi-Fi Aware is espressif-only and Sync-based for now — a port-specific, radio-owning module (§7.2), not the portable one §7.1 imagined. +* **Consequence: start with Feature A (DNS-SD).** It is the only part of issue #18 that is both portable and working. +* **ESP32-S3**: v1 said it was excluded outright, which was wrong — it runs the USD stack and transmits valid NAN frames (confirmed on hardware). Since the recommendation is now Sync-based, the S3 is excluded *in practice* — but by Espressif's `SOC_WIFI_NAN_SUPPORT` declaration, which is **not demonstrably a silicon limit** (§14.2a). Worth raising with Espressif rather than treating as physics. +* **CircuitPython already ships DNS-SD** as `mdns` (espressif + raspberrypi). The gap is zephyr-cp. +* **No prior art anywhere in our ecosystem**: no NAN in MicroPython, none in arduino-esp32. +* **zephyr-cp's pinned Zephyr is USD-only** — which looked like the convergence point for a portable design, until USD turned out to be the broken half (§14.3). + +--- + +## 1. What the issue asks for + +An AP-less, DHCP-less, internet-less transport for a deep-sleeping environmental sensor collector, with a DNS-SD-shaped API and iOS/Android interop. Two separable features: + +| | Feature | Status | +|---|---|---| +| **A** | **DNS-SD** over mDNS on a normal IP network | **exists** as `mdns`; missing on zephyr-cp | +| **B** | **Wi-Fi Aware (NAN)** — AP-less discovery + optional datapath | **does not exist** in any port | + +Feature A is independently shippable and should go **first**. + +--- + +## 2. CircuitPython today + +`shared-bindings/mdns/` — `Server` (`hostname`, `instance_name`, `find()`, `advertise_service()`) and `RemoteService`. Backends: espressif (wraps the IDF `mdns` component) and raspberrypi. Gated by `CIRCUITPY_MDNS ?= $(CIRCUITPY_WIFI)`. **zephyr-cp has no `mdns`.** No NAN anywhere. + +--- + +## 3. ESP-IDF — the Sync/USD split + +### 3.1 The decisive facts, from the pinned tree + +| Fact | Evidence | +|---|---| +| Sync start **forces** `WIFI_MODE_NAN` | `nan_app.c:2003` | +| Sync stop takes the whole radio down | `nan_app.c:2057` (`esp_wifi_stop()`) | +| `wifi_mode_t` has no combined NAN+STA | `esp_wifi_types_generic.h:25-33` | +| **USD runs on `WIFI_MODE_STA`** | `nan_app.c:2986` | +| USD gated only on `IDF_EXPERIMENTAL_FEATURES`, **not** on NAN silicon | `esp_wifi/Kconfig:620-623` | +| USD example targets incl. **S3, C3, C6, C2** | `examples/wifi/wifi_aware/usd_publisher/README.md:1` | +| Sync and USD **cannot coexist** | `nan_app.c:1943` | +| Hard limits: **2 services, 2 datapath peers, 2 stored credentials** | `esp_wifi_types_generic.h:875,876,884` | +| SSI payloads: follow-up ≤2048 B, publish ≤512 B | `esp_wifi_types_generic.h:890-891` | + +CP already sets `IDF_EXPERIMENTAL_FEATURES` (`ports/espressif/esp-idf-config/sdkconfig.defaults:158`), so USD, pairing and secured NDP are all reachable — but note that is Espressif-labelled **experimental** code. + +### 3.2 Chip support + +`SOC_WIFI_NAN_SUPPORT` is defined only for **esp32, esp32s2, esp32c5, esp32c61, esp32s31**. That gates **NAN-Sync and the datapath only**. + +CP board counts: esp32 **52**, esp32s2 **56**, esp32c5 **2**, esp32c61 **1**. + +**USD, and therefore discovery + messaging, works on every ESP Wi-Fi chip including the whole S3 fleet.** + +### 3.3 The `wifi_aware` component is Sync-only + +Espressif's `wifi_aware` component (`esp-wifi-apps`, Apache-2.0, v0.1.0) is the DNS-SD-shaped wrapper issue #18 links to. It calls `esp_wifi_nan_sync_start()` directly (`wa_init.c:113`) and its USD path is `#if 0`'d (`wa_init.c:115-122`). + +So **the component implies the exclusive radio mode and the datapath**. It also: +* has **no messaging API** — init / advertise / discover / pair / connect / disconnect only (`wifi_aware.h:453-642`); follow-ups are consumed internally for its SRV/TXT exchange; +* selects peer platform at **compile time** via a Kconfig *choice* — Default / iOS / Android, **mutually exclusive** (component `Kconfig:3-31`), because Android peers support no group ciphers. **One firmware cannot serve both iOS and Android.** +* includes a **private IDF header** (`apps_private/wifi_apps_private.h`) and calls `esp_nan_set_compatibility_mode_internal` — a v0.1.0 component bound to private API on a `-dev` IDF pin. + +IDF ≥6.1 is what unlocks pairing / secured NDP / iOS, and we are on 6.1-dev. That part of v1 stands. + +--- + +## 4. Zephyr + +### 4.1 DNS-SD: advertise yes, browse no + +`zephyr/net/dns_sd.h` + `mdns_responder_set_ext_records()` cover advertising. **Browsing is absent** — `CONFIG_MDNS_RESOLVER` does `.local` A/AAAA only, with no PTR→SRV→TXT enumeration. `mdns.Server.find()` has nothing to wrap. + +### 4.2 NAN: USD-only at our pin + +zephyr-cp pins `adafruit/zephyr@ab22ad4b` (`ports/zephyr-cp/zephyr-config/west.yml`). At that revision: +* `enum wifi_nan_operation` has six ops: PUBLISH, CANCEL_PUBLISH, UPDATE_PUBLISH, SUBSCRIBE, CANCEL_SUBSCRIBE, TRANSMIT; +* hostap builds only `nan_usd.c`, `nan_usd_ap.c`, `nan_de.c`; +* **no cluster sync and no NDP anywhere in the stack.** + +Upstream Zephyr main has since added `nan_ndp.c`, `nan_sec.c`, `nan_bootstrap.c` and `NAN_NDP_REQUEST`/`NAN_PAIR` control commands — only the `wifi_mgmt.h` glue is missing. So "Zephyr has no datapath" is true for us but has a **short shelf life**. + +`CONFIG_WIFI_NAN_MAX_SSI_LEN` defaults to **128 bytes** — the tightest payload ceiling in the system. + +### 4.3 Two zephyr-cp blockers + +* **No IPv6 at all.** `CONFIG_NET_IPV6` appears nowhere in zephyr-cp. `frdm_rw612/board.conf` is IPv4 + DHCPv4 only. Any IPv6 datapath story is moot there. +* **`frdm_rw612/board.conf` has no hostap/NAN config**, and whether Wi-Fi even works on that board in zephyr-cp is unverified. + +--- + +## 5. Prior art (as asked) + +* **MicroPython: no NAN** (0 hits for `esp_wifi_nan`), **no core DNS-SD module**. The esp32 port uses the IDF mdns component only for `.local` lookups. Third-party: cbrand/micropython-mdns, nickovs/slimDNS (both pure Python). **PyDevices PR #108** adds a C `mdns` module **modeled on CircuitPython's API** — influence runs our way, so don't churn `mdns`'s shape. +* **arduino-esp32: no NAN** (0 hits). `ESPmDNS` only. **No Arduino path to cross-check against** — bring-up must use ESP-IDF's own examples. + +### Phones +* **Android:** Wi-Fi Aware since 8.0 / API 26. USD support is much more recent (believed Android 16) with a small follow-up payload — **verify before committing to a USD-only design**. +* **iOS 26:** `WiFiAware` framework over Network framework; implements **DNS-SD naming on top of NAN**; service strings like `_ESP-Demo._udp` declared in `Info.plist`. **Pairing is mandatory** (6-digit PIN, no open datapath) — i.e. **iOS requires NAN-Sync + datapath**, which excludes S3 and excludes STA coexistence. + +### Testing constraints +* **The Android emulator cannot test this.** No NAN HAL; `WifiAwareManager` reports unavailable. A physical Android 8+ handset is required. +* **Apple gates iOS behind the `com.apple.developer.wifi-aware` entitlement** — request and approval needed before the app will build, plus Xcode 26 and a physical iOS 26 device. **Apply now.** + +--- + +## 6. Deep sleep — the finding that reframes the use case + +NAN-Sync is structurally hostile to a deep-sleeping sensor: +* defaults `scan_time = 3 s` and `warm_up_sec = 5` before taking anchor-master role (`esp_nan.h:19-28`); +* discovery only in windows every **524 ms** (`nan_i.h:37`); +* every wake is a cold start: scan → join/form cluster → wait for a discovery window → (for iOS) PASN pairing-verify → NDP handshake; +* **estimated** seconds of radio-on per wake vs. tens of milliseconds for ESP-NOW — one to two orders of magnitude more energy per report. *Derived from constants, not measured.* +* MAC randomisation is on by default, so each wake is a new identity and a new peer handle unless paired with NVS caching; +* the peer must be on air at wake time — a phone app must have a live session. + +**USD would avoid all of this**: no cluster, and `ttl = 0` sends a single publish (`esp_wifi_types_generic.h:1061`). One measured number now anchors the Sync side: **4.9 s from boot to a usable IPv6 datapath** (§14.1), of which 3.0 s is the default `scan_time` and so is tunable. That is a real figure to weigh against ESP-NOW's tens of milliseconds, and it confirms the order-of-magnitude estimate above rather than replacing it — the energy integral is still unmeasured. + +**But USD cannot be used for this today** (§13.2a), so the deep-sleep argument for preferring USD is currently academic. If the upstream RX defect is fixed, this section becomes the strongest argument for USD over Sync; until then it is a reason to measure Sync's wake cost properly rather than to assume either. + +**And the datapath may not be needed at all.** A sensor reading fits in a publish SSI (≤512 B) or one follow-up (≤2048 B) — no NDP, no IPv6, no sockets. + +--- + +## 7. Proposed CircuitPython API — revised + +v1 proposed capability tiers with `supported_features`. **That should be dropped.** There is no precedent for a capability-set API in `shared-bindings`; the house mechanism is module presence in the support matrix plus `NotImplementedError` on individual methods (e.g. `ports/raspberrypi/common-hal/wifi/Radio.c:540`). A module where half the classes raise on half the ports is exactly the "behaves differently per port" shape reviewers reject. + +**Split by what is genuinely common instead.** + +### 7.1 Core: a small USD-shaped module — **on hold** + +> **Status after §13/§14: do not build this yet.** It was proposed as the portable core because both backends can nominally do USD. They cannot *usefully*: espressif's USD discovery is broken upstream (§13.2a) and zephyr-cp's is untested and reaches at most one board (§14.3). The shape below is still the right shape — it is what a fixed USD should expose — but there is nothing working to implement it against today. Build §7.2 instead, or wait for the upstream fix. + +The intended shape, kept for when USD works: + +```python +import wifiaware +pub = wifiaware.publish("_envcollect._udp", ssi=b"t=21.5", ttl=0) +sub = wifiaware.subscribe("_envcollect._udp") +for peer in sub: + peer.send(b"ack") # follow-up +``` + +Three constraints the hardware work added to this design: + +* **Channel is not an implementation detail.** When a STA is associated, the binding must default USD's channel to the AP's, because off-channel USD kills the link *silently* (§13.1a). That is an API decision, not a tuning knob. +* **Payload limits differ** (ESP 2048 / Zephyr 128) — expose the ceiling as a constant rather than hiding it. +* **SSI is not interoperable as-is.** The ESP fork puts service-specific info on the wire raw; upstream hostap prepends the WFA OUI and protocol type and requires them on receive (§13.2). A portable API must decide which it speaks, or peers will discover each other and then fail to understand the payload. + +### 7.2 Datapath + pairing: espressif-only, separate + +Not a tier that raises — **classes that simply do not exist on other ports**, documented as espressif-only, like any other port-specific module. This is where iOS interop lives. + +Because NAN-Sync is an **exclusive radio mode**, the entry point belongs **on or beside `wifi.radio`**, not a free-standing object: `wifi.radio` owns mode and tracks `started`/`sta_mode`/`ap_mode` (`ports/espressif/common-hal/wifi/Radio.c:62,81,102,107`). Anything that calls NAN start behind its back desynchronises that state, and web workflow / `settings.toml` auto-connect will fight it. It needs defined errors when STA/AP is active. + +Agreed with v1: a new module, not an extension of `mdns` (`mdns.Server` requires a `network_interface`, `shared-bindings/mdns/Server.c:27-51`). + +### 7.3 Scoped IPv6 — real, but smaller than v1 claimed + +`connect`/`sendto`/`bind` all call `mp_obj_get_array_fixed_n(addr_in, 2, …)` (`shared-bindings/socketpool/Socket.c:91,129,299`), so a 4-tuple raises `ValueError` today. But output already carries scope (`getaddrinfo`/`recvfrom` return 4-tuples with `sin6_scope_id`), and lwIP parses the zoned string form `fe80::x%`. So `connect(("fe80::…%na1", port))` may already work untouched, or `Endpoint.address` can return the zoned string. Proper 4-tuple support is ~20 lines plus a common-hal signature change. **Not the dominant cost.** Moot on zephyr-cp, which has no IPv6. + +--- + +## 8. Feature A — do this first + +Porting `mdns` to zephyr-cp splits cleanly: +* `advertise_service()` → `dns_sd_rec` array + `mdns_responder_set_ext_records()`. Mechanical. +* `find()` → nothing to wrap. **Write a DNS-SD browser in `shared-module/`** over a plain UDP multicast socket. + +The shared-module browser gives `mdns.Server.find()` to **every port with sockets**, present and future — directly serving the "easily facilitate other network platforms later" goal. Independently shippable, no hardware risk. Start IPv4-only (zephyr-cp has no IPv6). + +--- + +## 9. Risks + +| # | Risk | Status | +|---|---|---| +| 1 | **NAN-Sync cannot coexist with STA/AP** | **Confirmed on hardware** (§14.4): `WIFI_MODE_NAN` is exclusive, `wifi_mode_t` has no NAN+STA value. Transitions are clean and observable, and STA returns in 1.5 s. | +| 1b | **USD cannot coexist with STA** | **Disproved** (§13.1a). USD on the AP's channel holds the link for 100 s. Off-channel it dies *silently* — so the binding must pick the channel. | +| 2 | Datapath gated by `SOC_WIFI_NAN_SUPPORT` (no S3/C3/C6) | Confirmed as a Kconfig gate; **not demonstrably silicon** (§14.2a). USD needs no such gate at all. | +| 2b | **USD discovery is broken upstream** | **Confirmed and localised** (§13.2a): 407 SDFs reach the NIC, `nan_de_rx_sdf()` never runs. Blocks every USD plan until fixed. | +| 3 | **Per-wake energy/latency of NAN-Sync** | Partly measured: 4.9 s boot→datapath (§14.1). Energy still unmeasured. | +| 4 | **Compile-time iOS/Android exclusivity** | Confirmed; one firmware cannot serve both | +| 5 | **USD (Zephyr) vs Sync (component) mismatch** | Worse than stated: zephyr-cp USD is untested *and* reaches at most `frdm_rw612` (§14.3). Also, the ESP fork puts SSI on the wire raw where upstream hostap prepends the WFA OUI — so even a working USD may not interop with a Zephyr/Android peer (§13.2). | +| 6 | Limits of 2 services / 2 datapaths / 2 credentials | Confirmed | +| 7 | zephyr-cp has **no IPv6**, and rw612 Wi-Fi unverified | Confirmed | +| 8 | `wifi_aware` is v0.1.0 on private IDF API | Maintenance risk | +| 9 | Apple entitlement lead time | Apply now | +| 10 | No Android emulator path | Physical handset needed | +| 11 | Android USD API level + payload size | **Unverified** — but moot while USD discovery is broken | +| 12 | **Secured NDP / pairing is itself experimental** | `ESP_WIFI_NAN_SECURITY` and `ESP_WIFI_NAN_PAIRING` depend on `IDF_EXPERIMENTAL_FEATURES` — the same gate held against USD, and untested here. Phone interop needs them. | + +--- + +## 10. Sequencing + +Revised against §13/§14. Steps 2a and 2b of the v2 plan are **done**; the rest is reordered because USD is blocked upstream. + +1. **Feature A — the portable DNS-SD browser.** Written and building (`shared-module/mdns/Browser.c`, selected by `CIRCUITPY_MDNS_SHARED`). Remaining: validate against a real responder on hardware, then the zephyr-cp `advertise_service()` half. No dependency on anything below. +2. **File the USD RX defect upstream** (§13.2a). Everything USD-shaped is blocked behind it, and the reproducer is small. +3. **Measure Sync's wake cost** — boot→datapath is 4.9 s (§14.1); the energy integral per report versus ESP-NOW is the number that actually decides issue #18. +4. **Test secured NDP and pairing** (risk #12). Untested, experimental, and the prerequisite for any phone interop. +5. **Apply for the Apple entitlement** — long lead time, start regardless. +6. **Then** decide the module: a `wifiaware` Sync module, espressif-only, owning `wifi.radio` (§7.2) — *or*, if step 2 lands a fix, revisit USD, which needs no `SOC_WIFI_NAN_SUPPORT` and coexists with STA on the AP's channel. + +Note what is *not* on this list any more: "`wifiaware` USD module, espressif + zephyr" (v2 step 5). There is no working USD on either backend to build it on. + +--- + +## 11. What changed from v1 + +| v1 claim | Correction | +|---|---| +| "Every ESP32-S3 board is out, permanently" | **Wrong.** The S3 runs USD; only the datapath is gated by `SOC_WIFI_NAN_SUPPORT` — which is itself a firmware declaration, not a proven silicon limit (§14.2a). | +| STA+NAN coexistence "blocking, verify on hardware" | **Settled from source** — Sync forces `WIFI_MODE_NAN`. No experiment needed. | +| NAN-USD | **Missed entirely.** v1 cited `usd_publisher` without noticing what it was, and missed `usd_subscriber`. | +| Capability tiers + `supported_features` | Dropped — no precedent in `shared-bindings`, likely rejected. | +| "Tier 1 messaging: ESP + Zephyr" | The `wifi_aware` component **has no messaging API**. | +| Zephyr facts | Verified against upstream main, **not** the pinned `adafruit/zephyr@ab22ad4b`. Pinned tree is USD-only. | +| Scoped IPv6 "may be the biggest hidden cost" | Overstated — ~20 lines, and possibly already works via zoned strings. | +| Deep sleep | Not considered. It is arguably the most important constraint of all. | +| `esp_wifi_nan_start` | On 6.x it is `esp_wifi_nan_sync_start`. | + +--- + +## 12. Other CircuitPython network platforms + +Scope is **not** limited to the deepsleep project, and **NAN-Sync is wanted as well as USD**. Surveying every Wi-Fi backend CircuitPython has: + +| Platform | DNS-SD | NAN | Evidence | +|---|---|---|---| +| **espressif** (native) | `mdns` ✔ | **Sync + USD** ✔ | IDF 6.1; USD hardware-confirmed below | +| **raspberrypi** Pico W / Pico 2 W (CYW43) | `mdns` ✔ (lwIP) | **none** | 0 hits for NAN in `georgerobotics/cyw43-driver` | +| **zephyr-cp** | advertise only, no browse | **USD only** at our pin | §4 | +| **AirLift / WiFiNINA** (`nina-fw`) | via firmware | **none** | 0 hits for NAN in `adafruit/nina-fw` | +| **ESP-Hosted** | via host IP stack | **none exposed** | `rpc_v2.proto` has no NAN RPC — only "Nano" false positives; `esp_wifi_nan` appears solely in `esp_netif_defaults` | +| **ESP8266** | — | **none** (no NAN in the NONOS SDK; CP has no esp8266 port) | — | + +Conclusions for the wider scope: + +* **NAN is espressif-silicon-only in practice.** Every co-processor path (AirLift, ESP-Hosted, CYW43) would need firmware or RPC work before CircuitPython could expose NAN on it. AirLift and ESP-Hosted *run on NAN-capable ESP32 silicon*, so the capability exists — it is the host protocol that does not carry it. ESP-Hosted is the more tractable of the two, since extending `rpc_v2.proto` is additive; `nina-fw` is a frozen Arduino-era command set. +* Infineon's WHD has some NAN event plumbing under `COMPONENT_WIFI6`, but that is not the driver Pico W / Pico 2 W use — `cyw43-driver` has none. +* **DNS-SD is reachable on more platforms — but not "everywhere", as this section previously claimed.** Corrected after review: + * **AirLift / WiFiNINA does *not* terminate its IP stack on the host.** nina-fw runs the stack on the co-processor, CircuitPython reaches it through the Python `adafruit_esp32spi` library rather than C `socketpool`, and `common_hal_mdns_server_construct` rejects any interface but the built-in radio. A `shared-module` browser over `socketpool` therefore does **not** reach AirLift. + * Pico W already has a native `find()`, so it gains nothing. + * **The realistic beneficiary of the shared browser is zephyr-cp** (plus any future socket-capable port). That is still worth doing — it is the only portable, working piece of issue #18 — but the "lights up four platforms at once" claim was wrong. +* `esp32s31` is a **preview target** in this IDF (`tools/idf_py_actions/constants.py:53`), so it builds only with `--preview`. + +--- + +### 12.1 What "needs NAN hardware" actually means + +Reframed after §13/§14, because the earlier wording ("NAN is espressif-silicon-only in practice") conflated two very different barriers. + +| | What it needs | Who is blocked, and by what | +|---|---|---| +| **NAN-USD** | Nothing special. A publish is an ordinary **Public Action vendor-specific management frame** (`04 09 50:6f:9a 13 …`), plus remain-on-channel. `ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES`. | Nobody, at the silicon level. Every blocker is a **driver or host-protocol exposure** gap: `cyw43-driver` exposes no action-frame TX/ROC path, `nina-fw`'s command set is frozen, ESP-Hosted's `rpc_v2.proto` carries no NAN RPC. | +| **NAN-Sync** | TSF/cluster scheduling, several concurrent RX addresses (NMI + NDI + cluster BSSID), slot-based TDMA. Gated by `SOC_WIFI_NAN_SUPPORT`. | esp32, esp32s2, esp32c5, esp32c61, esp32s31 only — but see §14.2a: that gate is Espressif's declaration, not a demonstrated silicon limit. | + +The practical consequence is more hopeful than v3 implied: **the platforms that cannot do Wi-Fi Aware are mostly blocked by software they do not expose, not by radios that cannot do it.** ESP-Hosted is the tractable one — extending `rpc_v2.proto` is additive, and the co-processor is NAN-capable ESP32 silicon. AirLift sits on the same silicon but a frozen Arduino-era firmware. CYW43 would need action-frame plumbing the driver does not have, though Infineon's own WHD carries NAN event definitions under `COMPONENT_WIFI6`. + +None of that is work worth starting while USD discovery is broken on the one backend we *can* test (§13.2a). It does mean the ceiling is higher than "espressif only" if that defect is fixed. + +--- + +## 13. Hardware results (rpi-hil006) + +Built from CircuitPython's own pinned IDF (`v6.1-dev-6096`) and flashed to real boards. Both boards' original flash was backed up first (4 MB each, under `~/usd-test/backup/`). + +**USD runs on the STA interface — confirmed on hardware, not just from source.** `usd_subscriber` on a classic ESP32: + +``` +I (658) wifi:mode : null +I (658) wifi:mode : sta (e8:9f:6d:32:50:04) +I (658) nan_app: NaN-USD Started +I (668) nan_app: Started Subscribing to ESP-USD-TEST [Service ID - 1] +``` + +This corroborates `nan_app.c:2986`. It was the basis for expecting STA coexistence — and §13.1 shows that expectation was wrong once the board is actually *associated*. + +### 13.1 USD and an associated STA — the first, flawed run + +The decisive experiment. Purpose-built firmware (not the stock examples): associate to a WPA2 AP, confirm an IP, *then* call `esp_wifi_nan_usd_start()`, and log association state, home channel and a real DNS lookup every 5 s. Run on both boards simultaneously, 100 s. + +ESP32-S3, abridged: + +``` +I (2712) coex: PRE-USD: associated ssid= ch=1 rssi=-68 bssid=ec:fc:2f:83:dc:d8 +I (2712) coex: GOT_IP 192.168.1.203 +I (2712) coex: esp_wifi_nan_usd_start() = ESP_OK +I (2712) coex: mode after usd_start = STA +I (2722) coex: [t= 0s] home_channel=1 +I (2722) coex: publish: chan=6 ... +I (7722) coex: [t= 5s] home_channel=6 <-- radio leaves the AP's channel +I (10982) coex: wifi_event id=21 <-- STA_BEACON_TIMEOUT +W (29722) coex: [t= 20s] DNS FAIL err=202 (6999ms) +W (39722) coex: [t= 30s] mode=STA NOT-ASSOC ip=192.168.1.203 disc=0 +``` + +**The two boards did *not* behave identically** — a claim this section wrongly made before review. Per board: + +| | ESP32-S3 (publisher) | classic ESP32 (subscriber) | +|---|---|---| +| Home channel | 6 for the whole run | 6 for 13 of 16 samples, back to 1 at t=25 s and t=35 s | +| Beacon timeouts | 3 | 5, every ~10 s | +| Association | **lost at 35.8 s** (`ap_probe_send over, reset wifi status to disassoc`, `run -> init`) | **held for the full 75 s** — never once `NOT-ASSOC` | +| `STA_DISCONNECTED` | never delivered; stale IP kept | n/a | + +So the honest result is **"publisher-on-S3 lost the link; subscriber-on-ESP32 was degraded but survived"**, with role and chip confounded (one run each). The likely mechanism is airtime, not chip: the publisher transmits ~5×/s on the USD channel while the subscriber only remains-on-channel ~1×/s, so the publisher spends far more time away from the AP. + +### 13.1a Resolved: it was the channel, not USD + +The above was run with USD pinned to **channel 6** (left over from the §13.2 discovery debugging) while the AP was on **channel 1**. Review flagged that as a confound I had introduced, so I re-ran it with the harness reading `esp_wifi_sta_get_ap_info()->primary` after association and pinning USD to **the AP's own channel**: + +``` +coex: PRE-USD: associated ssid=free4all ch=1 ... +coex: USD channel = 1 (FOLLOWING THE AP) +coex: [t= 0s] home_channel=1 ... coex: [t= 40s] home_channel=1 +``` + +| over 100 s | publisher (S3) | subscriber (ESP32) | +|---|---|---| +| Home channel | **1 throughout** — never leaves the AP | **1 throughout** | +| `NOT-ASSOC` samples | **0** | **0** | +| Beacon timeouts | 1 | 7 | + +**Both boards stayed associated for the entire run.** Compare the ch6 run, where the publisher lost its association at 35.8 s. + +**So "USD is a radio-owning mode" is wrong, and §0 said so on my evidence alone.** USD does not inherently take the radio; *USD pinned to a channel other than the AP's* does, because one radio cannot be in two places. Put USD on the AP's channel and STA survives. + +What survives from §13.1 is narrower but still worth having: + +* When USD *does* go off-channel, the link dies **silently** — no `STA_DISCONNECTED`, stale IP retained. That remains the API-relevant hazard. +* A CircuitPython USD binding should therefore **default `usd_default_channel` / `usd_chan_bitmap` to the associated AP's channel**, and only allow a different channel when no STA is up (or make the cost explicit). That is a concrete, cheap API rule that this experiment produced. +* The cost of staying on the AP's channel is that discovery only reaches peers that happen to use that channel — a real limitation for an AP-less use case, but irrelevant when the device is associated anyway. + +| Observation | Consequence | +|---|---| +| Mode stays `WIFI_MODE_STA` across `usd_start` | The *mode* claim in §3.1 holds — but mode is not the whole story | +| `home_channel` moves 1 → 6 and **stays** there | The single radio is parked on the USD channel; the AP link is abandoned | +| `WIFI_EVENT_STA_BEACON_TIMEOUT` (id 21) repeatedly | Firmware knows beacons are being missed | +| `getaddrinfo` goes from failing in ~25 ms to timing out at ~7 s | Queries are now going unanswered rather than being refused — see the caveat below | +| `esp_wifi_sta_get_ap_info()` → `NOT_CONNECT` by t=30 s | Association genuinely lost | +| **`disc=0` — no `STA_DISCONNECTED` ever fires** | The application is never told. `esp_netif` keeps the stale IP (`192.168.1.203`) and the socket layer keeps answering as if connected | + +**Caveat on the DNS numbers, found later (§14).** The test AP has no working resolver: on a *healthy* STA link `getaddrinfo` already fails, immediately (~25 ms, `err=202`). So DNS failure alone is not proof that USD killed traffic. What does change under USD is the *shape* of the failure — ~25 ms refusal becomes a ~7 s timeout, i.e. queries stop being answered at all. The load-bearing evidence for this section is therefore the unambiguous radio-level facts: the home channel moving to 6 and staying, repeated `STA_BEACON_TIMEOUT`, and `esp_wifi_sta_get_ap_info()` returning `NOT_CONNECT`. Those do not depend on the AP's resolver. + +> ~~**This changes the design.** USD cannot be a quiet background service alongside `wifi.radio.connect()`; it is a radio-owning mode and the entry point belongs on `wifi.radio`.~~ +> +> **Superseded by §13.1a.** That conclusion was drawn from this run alone, and this run had USD pinned to a channel the AP was not on. The mitigation this paragraph suggested "testing later" turned out to be the whole story: pin USD to the AP's channel and the problem disappears. Kept here because the logs remain the evidence for the *silent* failure mode, which is real and still matters. + +### 13.2 Discovery never completes — publisher is correct, subscriber is deaf + +Across every configuration tried, **no `WIFI_EVENT_NAN_SVC_MATCH` ever fires.** Ruled out, each by direct measurement: + +| Hypothesis | Test | Result | +|---|---|---| +| Channel mismatch | Both pinned to ch 6 via `usd_chan_bitmap` | both confirm `ch=6`; no change | +| Boards started at different times / TTL expiry | Simultaneous reset (<400 ms apart), TTL 600 s | no change | +| World-mode regulatory block on TX | `set_country("GB", MANUAL)`; was `cc=01 nchan=11` | accepted; no change | +| Power save sleeping through frames | `esp_wifi_set_ps(WIFI_PS_NONE)` | no change | +| Transmission failing | Log `WIFI_EVENT_ACTION_TX_STATUS` | `status=0` then `2` (started → duration-completed), **never `FAILED`** | +| Receiver off-channel | Log `WIFI_EVENT_ROC_DONE` + `esp_wifi_get_channel()` | ROC on ch 6 every 1 s, `status=0`, home channel 6 throughout | +| Chip- or direction-specific bug | Swap roles: ESP32 publishes, S3 subscribes | **still zero matches both ways** | + +**One row removed after review: setting `.type` was a no-op.** The public `.type` field is never read on the USD path — `esp_nan_usd.c` uses fixed defaults from `esp_private/esp_nan_usd.h`: `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()` hardcodes `.active = false` and `ESP_USD_PUBLISH_DEFAULT_PARAMS()` hardcodes `.unsolicited = true, .solicited = true`. That test changed nothing, so it ruled nothing out. (It does, however, mean the effective config — unsolicited publisher, passive subscriber — is a combination that *should* match, which argues against misconfiguration.) + +Then the frames were captured off the air. The classic ESP32 was temporarily reflashed as a promiscuous sniffer on channel 6 while the S3 published: + +``` +sniff: VSA src=f4:12:fa:59:64:84 dst=51:6f:9a:01:00:00 bssid=51:6f:9a:01:00:00 + oui=50:6f:9a type=13 rssi=-58 ch=6 len=62 + 04 09 50 6f 9a 13 | 03 09 00 be7d08e9ddb7 01 00 00 | 0e 0d 00 01 01 00 0800 "PUBHELLO" +``` + +Decoded: Public Action (`04`), Vendor Specific (`09`), WFA OUI `50:6f:9a`, **OUI type `0x13` = NAN SDF**; then a Service Descriptor Attribute (`0x03`, service-ID hash `be7d08e9ddb7`, instance 1) and a Service Descriptor Extension Attribute (`0x0e`) carrying the 8-byte payload. Repeating roughly every 150 ms at −58 dBm. + +**So the publisher is fully correct and the RF link is fine** — the same board, same antenna, hears the frames perfectly in promiscuous mode. The failure is squarely in the USD **receive/match** path. + +#### 13.2a The defect, localised + +Two further experiments pin it down exactly. + +**(1) The discovery engine is never called.** `wpa_printf()` maps to `ESP_LOG_LEVEL_LOCAL(level, "wpa", …)`, and `nan_de.c:1271` logs `NAN: RX SDF from …` at `MSG_DEBUG` immediately after the function's only early return. Raising that tag to `ESP_LOG_DEBUG` at runtime gives a clear **positive control** — the engine does log: + +``` +D (785) wpa: NAN: Assigned new subscribe handle 1 for ESP-USD-TEST <-- subscriber +D (343) wpa: NAN: Publish in single channel state for 900 TU; ... <-- publisher +D (1273) wpa: NAN: TX wait for response ended (freq=2437) +``` + +and **`NAN: RX SDF from` never appears, not once.** `nan_de_rx_sdf()` is never entered. + +**(2) The frames do arrive at the receiver's own NIC.** Running the subscriber with promiscuous mode enabled *alongside* its USD subscribe, counting Public-Action/WFA/OUI-type-`0x13` frames: + +``` +coex: promisc on = ESP_OK +coex: [t= 60s] promisc NAN SDFs seen = 407 +``` + +**407 NAN SDFs received by the subscriber's own radio, and zero delivered to the USD engine.** + +That is conclusive and leaves no room for misconfiguration: the frames are transmitted correctly, reach the right board on the right channel, are demodulated by its NIC — and the closed Wi-Fi blob never hands them to the action-frame callback the USD engine registered via remain-on-channel. The open `nan_de.c` code is not at fault; it is simply never called. + +It also **weakens my own A1/A3 address-filter hypothesis**: enabling promiscuous mode (which opens the hardware address filter) did not make discovery work. Promiscuous delivery is a separate path from the ROC `rx_cb`, so this does not strictly refute the theory — but the mechanism is no longer something I can determine from outside the blob, and the bug report does not need it. + +**This is now fileable**, with a minimal reproducer that needs no NAN code at all: call `esp_wifi_remain_on_channel()` with an `rx_cb` and `allow_broadcast=true` while another board publishes, and show the callback never fires for frames a promiscuous sniffer on the same board counts in the hundreds. + +Most likely cause, not yet proven: the frames are addressed to the NAN Network ID `51:6f:9a:01:00:00` in both **A1 and A3**. That is a multicast address that is not broadcast, so a STA-mode hardware RX filter will drop it unless the receiver's BSSID filter has been set to the NAN Network ID. In NAN-Sync the device joins the cluster and that filter is set; on the USD path over a plain STA interface it appears not to be. + +**A competing explanation, equally plausible:** the Wi-Fi blob at this pin (`e12a754`) has as its HEAD commit *"fix(nan): Fix bug bounty reported and discovered vulnerabilities in NAN Rx"* (2026-07-14). A hardening regression in the RX path fits the evidence just as well as a filter that never worked. + +*(A previous version of this section offered "the subscriber never transmits either" as corroboration. It is not: the subscriber is passive by construction — see the `.active = false` default above — and only transmits a follow-up after receiving a publish. Zero `ACTION_TX` is the same fact as zero matches, not independent evidence.)* + +**Before filing upstream**, two cheap tests would make this decisive: (1) enable promiscuous mode with the MGMT filter on the subscriber while USD runs — if `SVC_MATCH` starts firing, the hardware filter is confirmed; (2) build with `CONFIG_WPA_DEBUG_PRINT=y` (off in my builds, which is why the verbose logging in run p2 showed nothing — the discovery engine logs via `wpa_printf`) and look for `NAN: RX SDF from`. Its absence proves the callback is never entered. + +**A portability quirk worth recording:** the ESP fork puts service-specific info on the wire raw, whereas upstream hostap prepends the WFA OUI and protocol type and requires them on receive. So "the publisher is fully correct" should read **"correct for ESP peers"** — a hostap/Zephyr/Android peer would discard that SSI. §7.1's `ssi=b"t=21.5"` inherits this. + +**Status: NAN-USD on ESP-IDF `v6.1-dev-6096` transmits but does not discover.** It is an experimental feature behind `CONFIG_IDF_EXPERIMENTAL_FEATURES`, and this looks like an upstream defect worth reporting. Until it is fixed, **USD cannot be the foundation of a CircuitPython `wifiaware` module** — which, combined with §13.1, is the single most important result of the hardware work. + +### 13.3 What this does to the plan + +* §8 (**DNS-SD browser in `shared-module/`**) is untouched by any of this and is unambiguously the right first step. No hardware risk, no upstream dependency, serves every port with sockets. +* The `wifiaware` module (§7.1) should **not** be started on USD against this IDF — not because USD is the wrong protocol, but because its receive path is broken (§13.2a). +* NAN-Sync was subsequently tested and works end to end: see §14. + +### 13.4 Reproduction + +All test firmware is in the session scratchpad. `coex_pub/` + `coex_sub/` is the main harness, with four build switches: `-DROLE_PUB=` (publish vs subscribe), `-DCOEX_WITH_STA=` (join an AP first), `-DUSD_PROMISC=` (run promiscuous RX alongside USD, for §13.2a) and `-DUSD_FIXED_CHAN=` (the fallback channel when no AP is associated; with one, it follows the AP). `swap_pub32/` + `swap_subs3/` is the role swap, `sniff/` the standalone promiscuous NAN SDF sniffer, `synccoex/` the four-phase Sync-vs-STA probe. Logs are on the Pi under `~/usd-test/{coex,sync,synccoex,apchan,diag}/`, and copied locally under `hil-logs/` with a manifest. Both boards' original 4 MB flash images are in `~/usd-test/backup/`. + +Board notes: the QT Py ESP32-S3 needs `CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y`, since UART0 is not wired to USB; and with native USB it re-enumerates under a different `/dev/serial/by-id` name in ROM download mode, which breaks naive by-id addressing in scripts. Serial capture needs a DTR/RTS reset toggle before any output appears. + +--- + +## 14. NAN-Sync hardware results — it works + +Tested after §13, on the two rig boards that actually have NAN silicon: **classic ESP32** (publisher) and **ESP32-S31** (subscriber). Stock IDF examples, security disabled, active subscribe, datapath + IPv6 ping enabled. + +First, a build-level signal that was missed earlier: **Sync is not an experimental feature.** It needs only `CONFIG_ESP_WIFI_NAN_SYNC_ENABLE=y`. USD additionally requires `CONFIG_IDF_EXPERIMENTAL_FEATURES` (§3.1), and §13.2 shows why. + +### 14.1 Full sequence, measured + +Subscriber (ESP32-S31): + +``` +I (265) wifi:mode : NAN (1e:29:04:81:b5:97) +I (3345) NAN: Start own Cluster, Id 50:6f:9a:01:db:dd +I (3345) nan_app: Started Subscribing to ESP-SYNC-TEST [Service ID - 5] +I (4395) nan_app: Service matched with ea:9f:6d:c6:e9:16 [Peer Publish id - 5] +I (4925) wifi:NDL for Peer ea:9f:6d:c6:e9:16 ch6: ndc=[2,2] crb1=[3,16] crb2=[0,0] +I (4925) nan_app: NDP confirmed [NDP ID - 1, Peer IPv6 - FE80::E89F:6DFF:FEC6:E916] +I (10215) subscriber: 64 bytes from FE80::E89F:6DFF:FEC6:E916 icmp_seq=1 ttl=0 time=292 ms +I (11925) subscriber: 64 bytes from FE80::E89F:6DFF:FEC6:E916 icmp_seq=3 ttl=0 time=2 ms +--- FE80::E89F:6DFF:FEC6:E916 ping statistics --- +5 packets transmitted, 5 received, 0% packet loss, time 300ms +``` + +The publisher independently confirms the same NDP from its side, and logs `NAN: Join Cluster with Id ...` rather than starting its own — the two devices genuinely formed one cluster. + +| Milestone | Time from boot | +|---|---| +| `WIFI_MODE_NAN` up | 0.27 s | +| Cluster formed | 3.35 s | +| **Service matched** | **4.40 s** | +| **IPv6 datapath confirmed (NDP)** | **4.93 s** | +| First ICMPv6 reply | 10.2 s (example waits 5 s deliberately) | +| Steady-state RTT | **2 ms**, 0 % loss | + +**This is a working, AP-less, DHCP-less IPv6 transport with real sockets on it** — exactly what issue #18 asks for, and the thing USD can never provide even when fixed (USD has no datapath at all). + +### 14.2 What it costs + +* **Exclusive radio mode, confirmed on hardware.** The log reads `wifi:mode : NAN`, a mode distinct from STA/AP, with its own **NAN Management Interface MAC**. That MAC is **randomised at every start** — only the OUI is derived (`e8:9f:6d` → `ea:9f:6d`, locally-administered bit set); the low three bytes differ on every boot (`c6:e9:16`, `80:3e:81`, `83:f6:00`, `ea:1b:bc` across four runs). **Consequence: the peer's datapath link-local IPv6 changes on every wake**, since it is the EUI-64 of that MAC — a real problem for a deep-sleeping collector, and one §7 has not accounted for. `disable_random_mac` / NVS caching exist in `wifi_nan_sync_config_t`; neither was tested. This corroborates `nan_app.c:2003`/`:2057` from §3.1. Note §13.1 showed USD imposes effectively the same cost in practice while pretending not to — so exclusivity is no longer a discriminator between the two. +* **`SOC_WIFI_NAN_SUPPORT` required** — set only for **esp32, esp32s2, esp32c5, esp32c61, esp32s31**, excluding the ESP32-S3 and the C3/C6 parts a great many CircuitPython boards use. Whether that reflects silicon is a separate question; see §14.2a. +* The datapath IPv6 is a **link-local address derived from the peer's NMI as an EUI-64**, so anything using it needs scope/zone handling — see §7.3. + +### 14.2a Is `SOC_WIFI_NAN_SUPPORT` a hardware limit? Probably not. + +Earlier drafts wrote "needs NAN silicon" and called Sync's exclusivity a hardware cost. Neither is justified, and the distinction matters: it turns the S3/C3/C6 exclusion from a law of physics into something reasonable to ask Espressif about. + +What `SOC_WIFI_NAN_SUPPORT` actually is: a macro in each chip's `soc_caps.h` — Espressif's declaration of what their Wi-Fi firmware supports on that part. It gates exactly one Kconfig symbol, `ESP_WIFI_NAN_SYNC_ENABLE`. Since the Wi-Fi MAC firmware is a closed blob, nothing outside it can distinguish "the block isn't there" from "we didn't implement it for this lineage". + +Evidence that it is a product decision rather than silicon: + +* **The chip list has the wrong shape.** ESP32 (2016) ✓, S2 ✓, S3 ✗, C3 ✗, C6 ✗, then C5 ✓, C61 ✓, S31 ✓. A physical block does not vanish for a generation and return. +* **The C6 is the awkward case.** It has `SOC_WIFI_HE_SUPPORT` — Wi-Fi 6, including TWT's negotiated scheduled wake windows, the same class of machinery NAN's Discovery Windows and NDL slot bitmaps need, and the IDF event enum carries `ITWT_SETUP`/`BTWT_SETUP`/`TWT_WAKEUP` to show the stack drives it. Yet no NAN. +* **Two timing domains on one radio already ship.** It is tempting to argue a station's TSF is slaved to its AP so a NAN cluster's timebase cannot coexist — but CircuitPython's own port sets `WIFI_MODE_APSTA` (`ports/espressif/common-hal/wifi/Radio.c:50`), where the softAP beacons its own TSF while the STA follows the upstream AP's. So "one counter cannot follow two sources" is not an available argument. +* **Other vendors ship NAN concurrently with STA.** Android phones run Wi-Fi Aware while associated as a matter of course; the spec permits concurrency and vendor firmware decides. + +The one genuinely hardware-shaped question left is the number of concurrent VIF slots, TSF counters and RX address filters — Sync wants NMI + NDI + cluster BSSID, which on top of an active STA might exceed them. That is a real question, but it is a question, not a known. + +**What survives regardless:** `nan_app.c:2003` forces `WIFI_MODE_NAN`, and `wifi_mode_t` has no combined NAN+STA value (`esp_wifi_types_generic.h:27-32`). Whether that is silicon or a product decision, CircuitPython cannot flip it — so the API conclusion (Sync owns `wifi.radio`) holds either way. + +### 14.3 The architectural consequence + +v2 §0 proposed building on USD because "both backends can do it" — espressif and zephyr-cp converging on USD. The hardware says that convergence is **on the one thing that does not work**: + +| | espressif (pinned IDF) | zephyr-cp (pinned Zephyr) | +|---|---|---| +| NAN-Sync | **works, datapath and all** (§14.1) | not available | +| NAN-USD | transmits, never discovers (§13.2) | **untested** — and reaches at most one board (below) | + +Two things weaken this table, both in the direction of "I know less than I implied": + +* **The zephyr column is unknown, not broken.** I tested no Zephyr USD at all. And "same hostap `nan_de` lineage" cuts *against* transferring the ESP result: the open `nan_de` code reads correctly, and the ESP defect appears to be in the closed blob — so the ESP failure predicts nothing about Zephyr. +* **Zephyr USD is barely available anyway.** hostap USD needs a driver exposing `remain_on_channel`/`send_action`; in the Zephyr tree only `nrf_wifi`, `nxp` and `hwsim` have them — not the Infineon AIROC driver behind Pico W / Pico 2 W. With `hal_espressif` blocklisted in `west.yml`, that leaves `frdm_rw612`, which has no hostap/NAN config today. +* **One IDF snapshot.** USD is experimental, at a `-dev` pin, possibly broken by a dated hardening commit. That is a "re-test at the next IDF bump" item, not a permanent architectural fact. + +So **there is no common working denominator today.** A portable `wifiaware` module cannot be built on USD (broken here) or on Sync (absent there, and silicon-limited). Any Wi-Fi Aware work in CircuitPython is therefore **espressif-only and Sync-based** for now, which is precisely the §7.2 shape — a port-specific module that owns the radio, not a portable one. + +That reinforces, rather than weakens, the §8 conclusion: **DNS-SD first**. It is the only part of issue #18 that is portable *and* working. + +### 14.4 Sync vs STA — measured, and it behaves *well* + +A purpose-built four-phase probe on the classic ESP32: bring STA up, start Sync on top of it, exercise STA while Sync runs, then stop Sync and try to recover. + +``` +PHASE A [A/after-sta] mode=STA sta=ASSOC chan=1 ip=192.168.1.143 disc=0 +PHASE B *** STA_DISCONNECTED reason=8 (#1) *** <-- fires immediately + ### NAN_CLUSTER_JOIN ### ### NAN_SYNC_STARTED ### + nan_sync_start() = ESP_OK + [B/after-nan-start] mode=NAN sta=ESP_ERR_WIFI_CONN chan=6 ip=0.0.0.0 disc=1 +PHASE C publish_service while NAN = id 5 <-- NAN genuinely usable + esp_wifi_connect() while NAN (no set_mode) = ESP_ERR_WIFI_MODE +PHASE D nan_sync_stop() = ESP_OK + [D/after-nan-stop] mode=NAN ... <-- stop does NOT restore the old mode + set_mode(STA)/start/connect -> STA recovery: RECOVERED in 1.5 s +``` + +`esp_wifi_nan_sync_start()` unconditionally calls `esp_wifi_set_mode(WIFI_MODE_NAN)` (`nan_app.c:2003`) with no check for a live STA, and `esp_wifi_nan_sync_stop()` calls `esp_wifi_stop()` (`:2058`). So Sync does take the radio — **but it takes it honestly**, and that is the whole difference from §13.1: + +| | NAN-USD (§13.1) | NAN-Sync (§14.4) | +|---|---|---| +| Mode reported after start | stays `STA` — misleading | `NAN` — accurate | +| `STA_DISCONNECTED` delivered | **never** | **yes, `reason=8`, immediately** | +| `esp_netif` IP | **stale address retained** | **cleared to `0.0.0.0`** | +| STA API while active | appears to work, silently dead | `esp_wifi_connect()` → **`ESP_ERR_WIFI_MODE`** | +| Recovery | n/a | `nan_sync_stop()` → `set_mode` → `connect`: **1.5 s to a new IP** | + +**This is a mode CircuitPython can model honestly.** Every transition is observable: the disconnect event fires, the address is dropped, misuse is refused with a real error code, and teardown is fast and complete. That is precisely what `wifi.radio` needs in order to keep `started`/`sta_mode`/`ap_mode` truthful (§7.2) — and precisely what USD does *not* give. + +Two sharp edges for the binding to handle: + +* **`esp_wifi_set_mode(WIFI_MODE_STA)` while Sync is running silently stops NAN.** Observed directly: `NAN_SYNC_STOPPED` fired on the `set_mode` call, and a subsequent `esp_wifi_nan_publish_service()` returned id `0`. The clobber is not symmetric — `connect()` under NAN is refused, but a mode change under NAN is not. Nothing but the binding can prevent user code from doing this. +* **`esp_wifi_nan_sync_stop()` leaves the mode at `NAN`.** The caller must restore STA explicitly; the stop alone leaves the radio in a state with no station and no NAN. + +*(Method note: the first run of this probe put `set_mode(STA)` before the publish in Phase C, which silently stopped NAN and invalidated Phases C and D — `nan_sync_stop()` then returned `ESP_FAIL` simply because NAN was already stopped. Reordered and re-run; the numbers above are from the corrected run. The discarded run is what revealed the silent-clobber edge above.)* + +### 14.5 Still open + +* **Validate the DNS-SD browser against a real responder.** It builds and its parser is unit-tested and fuzzed, but no packet of its has met an Avahi/mDNSResponder instance. Nothing should be built on it until that happens. +* **zephyr-cp's `advertise_service()` half**, plus enabling `mdns` there at all. The browser side is ready and the build wiring now emits `CIRCUITPY_MDNS_SHARED` when the port has no `common-hal/mdns`, but that path is unverified — no zephyr board on this rig. + +* **Secured NDP and pairing** (`ESP_WIFI_NAN_SECURITY`, `ESP_WIFI_NAN_PAIRING`) — untested, gated on `IDF_EXPERIMENTAL_FEATURES`, and the prerequisite for any phone interop. iOS vs Android is reportedly a compile-time choice. +* **NMI randomisation vs deep sleep** (§14.2): the peer IPv6 moves every boot unless `disable_random_mac` or NVS caching is used. Untested, and it shapes the API. +* **Flash/RAM cost** of enabling NAN-Sync on classic ESP32 and ESP32-S2 CircuitPython builds — unmeasured, and ESP32-S2 alone is ~56 boards. +* **The ESP32-S31 is a preview target** with no CircuitPython boards; the Sync result rests on a chip we do not ship. +* **An oddity to resolve before a binding exposes it:** in `t3-pub.log` the publisher prints its *own* EUI-64 as "Peer IPv6". The responder-side address in the NDP-confirm event may not be trustworthy. +* **`esp_wifi_nan_sync_start()` blocks for ~3 s** (5682 → 8692 ms in `run2.log`), of which 3.0 s is the default `scan_time`. A binding must keep background tasks running across that, and the 4.9 s figure is tunable rather than a floor. +* Secured NDP (`ESP_WIFI_NAN_SECURITY`, PMK/passphrase, ND-GTK) untested — and it is what iOS/Android interop will require. +* Power cost of cluster membership across deep sleep: unmeasured, and it is the crux of issue #18. A 4.9 s boot-to-datapath is already a meaningful number to weigh against ESP-NOW. + +### 14.6 Bench notes (cost me real time) + +* **`pyserial` asserts DTR and RTS on `open()`.** On an ESP32-S3/S31 native USB-JTAG CDC that reboots the part into the bootloader, so the console goes silent and looks like a dead firmware. Build the port object and set `dtr`/`rts` `False` *before* `open()`: + ```python + s = serial.Serial(); s.port = p; s.baudrate = 115200 + s.dtr = False; s.rts = False + s.open() + ``` + Every "no output" dead end in §13–§14 traced back to this. +* Resetting an S31 drops its native USB off the bus, so a capture must re-attach *after* re-enumeration. +* `esp32s31` needs `idf.py --preview set-target`, flashes with **`--no-stub`**, and its **bootloader goes at `0x2000`** (not `0x0`/`0x1000`). +* The CP2102N bridge on the S31 board is unreliable — it stops answering USB control transfers (`cp210x: failed set request 0x0 status: -110`) and only a host reboot brings it back. diff --git a/nan-pcap-parse.py b/nan-pcap-parse.py new file mode 100644 index 00000000000..a6bd0ae32a4 --- /dev/null +++ b/nan-pcap-parse.py @@ -0,0 +1,90 @@ +import struct, sys + +def frames(path): + d = open(path, 'rb').read() + if len(d) < 24: + return + magic = d[:4] + if magic == b'\xd4\xc3\xb2\xa1': + endi, usec = '<', True + elif magic == b'\xa1\xb2\xc3\xd4': + endi, usec = '>', True + elif magic == b'\x4d\x3c\xb2\xa1': + endi, usec = '<', False + elif magic == b'\xa1\xb2\x3c\x4d': + endi, usec = '>', False + else: + print("unknown magic", magic.hex(), file=sys.stderr); return + link = struct.unpack(endi + 'I', d[20:24])[0] + off = 24 + while off + 16 <= len(d): + ts, tu, incl, orig = struct.unpack(endi + 'IIII', d[off:off + 16]) + off += 16 + pkt = d[off:off + incl] + off += incl + if len(pkt) < incl: + break + t = ts + (tu / 1e6 if usec else tu / 1e9) + body = pkt + rate = None + if link == 127 and len(pkt) >= 8: # radiotap + rtlen = struct.unpack('> 2) & 3 + sub = (fc >> 4) & 0xF + a1 = a2 = a3 = None + if ftype == 1: # control + if len(body) >= 10: + a1 = body[4:10].hex(':') + else: + if len(body) >= 10: a1 = body[4:10].hex(':') + if len(body) >= 16: a2 = body[10:16].hex(':') + if len(body) >= 22: a3 = body[16:22].hex(':') + yield dict(t=t, ftype=ftype, sub=sub, a1=a1, a2=a2, a3=a3, + rate=rate, body=body) + +NAN_OUI = bytes.fromhex('506f9a') + +def nan_info(f): + """Return a short NAF description, or None.""" + if f['ftype'] != 0 or f['sub'] != 13: + return None + b = f['body'] + if len(b) < 24 + 6: + return None + p = b[24:] + if p[0] != 0x04 or p[1] != 0x09: # public action / vendor + return None + if p[2:5] != NAN_OUI: + return None + oui_type = p[5] + if oui_type != 0x13: + return f"NAF oui_type=0x{oui_type:02x}" + # NAN attributes follow + attrs = [] + q = p[6:] + i = 0 + while i + 3 <= len(q): + aid = q[i] + alen = struct.unpack(' 0); + // lwIP's select() checks the sockets again after it wakes, so it can + // return 0 even with no timeout: the main task has already read the + // datagram that woke it (the shared mDNS browser reads its own system + // socket, for one). Nothing is ready, so just wait again. + if (num_triggered == 0) { + continue; + } // Notice event trigger if (FD_ISSET(socket_change_fd, &readfds)) { diff --git a/ports/zephyr-cp/cptools/build_circuitpython.py b/ports/zephyr-cp/cptools/build_circuitpython.py index 87a97939062..45f46fdbe93 100644 --- a/ports/zephyr-cp/cptools/build_circuitpython.py +++ b/ports/zephyr-cp/cptools/build_circuitpython.py @@ -439,6 +439,14 @@ async def build_circuitpython(): # noqa: C901 translation = os.environ.get("TRANSLATION") or cmake_args["TRANSLATION"] or "en_US" for module in ALWAYS_ON_MODULES: circuitpython_flags.append(f"-DCIRCUITPY_{module.upper()}=1") + # mdns has two implementations: a port's native responder in common-hal, or + # the portable browser in shared-module. The source selection below already + # falls back to shared-module when a port has no common-hal for a module, + # but shared-bindings/mdns/*.h also need to know which struct to include, + # and that is a compile-time decision. Keep the two in step. + zephyr_common_hal = pathlib.Path(__file__).resolve().parents[1] / "common-hal" + if not (zephyr_common_hal / "mdns").is_dir(): + circuitpython_flags.append("-DCIRCUITPY_MDNS_SHARED=1") lto = cmake_args.get("LTO", "n") == "y" # LVGL module enabled for this board. The flag comes from CONFIG_LVGL via # ExternalProject args so it stays in sync with the Kconfig choice. Any board that diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index e92e8722b4c..04bf172c795 100755 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -659,6 +659,12 @@ SRC_COMMON_HAL_ALL = \ wifi/ScannedNetworks.c \ wifi/__init__.c \ +ifeq ($(CIRCUITPY_MDNS_SHARED),1) +# The portable browser replaces the port's common-hal/mdns entirely; the +# shared-module sources are added to SRC_SHARED_MODULE_ALL below. +SRC_COMMON_HAL_ALL := $(filter-out mdns/%, $(SRC_COMMON_HAL_ALL)) +endif + SRC_COMMON_HAL = $(filter $(SRC_PATTERNS), $(SRC_COMMON_HAL_ALL)) ifeq ($(CIRCUITPY_BLEIO_HCI),1) @@ -980,6 +986,23 @@ $(filter $(SRC_PATTERNS), \ endif # All possible sources are listed here, and are filtered by SRC_PATTERNS. +ifeq ($(CIRCUITPY_MDNS_SHARED),1) +SRC_SHARED_MODULE_ALL += \ + mdns/__init__.c \ + mdns/Server.c \ + mdns/RemoteService.c +# Browser.c has no shared-bindings counterpart, so it belongs in the INTERNAL +# list rather than SRC_SHARED_MODULE_ALL, which is prefixed with both paths. +SRC_SHARED_MODULE_INTERNAL += \ + mdns/Browser.c +endif + +# A port with a native mDNS responder but no browser can get find() alone by +# adding shared-module/mdns/Browser.c to its own sources and calling +# shared_module_mdns_find() from its common-hal find(). Browser.c is a separate +# translation unit precisely so that does not also pull in Server.c's +# common_hal_mdns_server_* definitions. + SRC_SHARED_MODULE = $(filter $(SRC_PATTERNS), $(SRC_SHARED_MODULE_ALL)) SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ diff --git a/py/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk index 7c6fb206e05..a542dc864a7 100755 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -495,6 +495,14 @@ CFLAGS += -DCIRCUITPY_MAX3421E=$(CIRCUITPY_MAX3421E) CIRCUITPY_MDNS ?= $(CIRCUITPY_WIFI) CFLAGS += -DCIRCUITPY_MDNS=$(CIRCUITPY_MDNS) +# Use the portable DNS-SD browser in shared-module/mdns instead of a per-port +# common-hal/mdns. It needs only socketpool, so it suits ports with an IP stack +# but no native mDNS library. It is a browser only: advertise_service() raises +# NotImplementedError. Ports with a native implementation leave this at 0. +CIRCUITPY_MDNS_SHARED ?= 0 +CFLAGS += -DCIRCUITPY_MDNS_SHARED=$(CIRCUITPY_MDNS_SHARED) +# The socketpool dependency is checked below, where CIRCUITPY_SOCKETPOOL is set. + CIRCUITPY_MEMORYMAP ?= 0 CFLAGS += -DCIRCUITPY_MEMORYMAP=$(CIRCUITPY_MEMORYMAP) @@ -653,6 +661,13 @@ CFLAGS += -DCIRCUITPY_SKIP_SAFE_MODE_WAIT=$(CIRCUITPY_SKIP_SAFE_MODE_WAIT) CIRCUITPY_SOCKETPOOL ?= $(CIRCUITPY_NETWORK) CFLAGS += -DCIRCUITPY_SOCKETPOOL=$(CIRCUITPY_SOCKETPOOL) +# The shared-module mDNS browser is built on socketpool. +ifeq ($(CIRCUITPY_MDNS_SHARED),1) +ifneq ($(CIRCUITPY_SOCKETPOOL),1) +$(error CIRCUITPY_MDNS_SHARED requires CIRCUITPY_SOCKETPOOL) +endif +endif + CIRCUITPY_SPITARGET ?= 0 CFLAGS += -DCIRCUITPY_SPITARGET=$(CIRCUITPY_SPITARGET) diff --git a/shared-bindings/mdns/RemoteService.h b/shared-bindings/mdns/RemoteService.h index c7efa64083d..c39831c076b 100644 --- a/shared-bindings/mdns/RemoteService.h +++ b/shared-bindings/mdns/RemoteService.h @@ -9,7 +9,11 @@ #pragma once #include "py/obj.h" +#if CIRCUITPY_MDNS_SHARED +#include "shared-module/mdns/RemoteService.h" +#else #include "common-hal/mdns/RemoteService.h" +#endif extern const mp_obj_type_t mdns_remoteservice_type; diff --git a/shared-bindings/mdns/Server.c b/shared-bindings/mdns/Server.c index 1c16348d425..4d56b9c30b1 100644 --- a/shared-bindings/mdns/Server.c +++ b/shared-bindings/mdns/Server.c @@ -166,7 +166,10 @@ static MP_DEFINE_CONST_FUN_OBJ_KW(mdns_server_find_obj, 1, _mdns_server_find); //| If web workflow is active, the port it uses can't also be used to advertise a service. //| //| **Limitations**: Publishing TXT records (up to 32) is supported only on RP2xxx. -//| There is currently no TXT record support on Espressif boards. +//| There is currently no TXT record support on Espressif boards. On boards that +//| use the portable DNS-SD browser rather than a native mDNS responder, this +//| raises `NotImplementedError`: those boards can discover services but not +//| advertise them. //| //| :param str service_type: The service type such as "_http" //| :param str protocol: The service protocol such as "_tcp" diff --git a/shared-bindings/mdns/Server.h b/shared-bindings/mdns/Server.h index df4b6f438db..ba456a8b099 100644 --- a/shared-bindings/mdns/Server.h +++ b/shared-bindings/mdns/Server.h @@ -8,7 +8,11 @@ #include +#if CIRCUITPY_MDNS_SHARED +#include "shared-module/mdns/Server.h" +#else #include "common-hal/mdns/Server.h" +#endif #include "shared-bindings/mdns/RemoteService.h" diff --git a/shared-module/mdns/Browser.c b/shared-module/mdns/Browser.c new file mode 100644 index 00000000000..015e641f50f --- /dev/null +++ b/shared-module/mdns/Browser.c @@ -0,0 +1,502 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// A portable DNS-SD browser built on socketpool, so that mdns.Server.find() +// works on any port that terminates an IP stack on the host rather than only on +// those with a native mDNS library. +// +// This is a "one-shot multicast DNS query" in the sense of RFC 6762 Section 5.1: +// the query goes to 224.0.0.251 from an ephemeral port. Because that source +// port is not 5353, RFC 6762 Section 6.7 requires responders to answer by +// unicast straight back to it, so we never have to join the multicast group or +// share port 5353. That matters because socketpool exposes IP_MULTICAST_TTL but +// has no IP_ADD_MEMBERSHIP, so a group-joining browser is not portable today. +// The unicast-response (QU) bit is set as well; it asks for the same thing. +// +// Multicast on Wi-Fi gets no link-layer retries, so the query or a reply is +// easily lost. find() therefore repeats the query for as long as its timeout +// allows, at the intervals RFC 6762 Section 5.2 sets for repeated queries. + + +// The portable DNS-SD browser. +// +// Deliberately its own translation unit, separate from the common_hal_* entry +// points in Server.c. A port that has a native mDNS *responder* but no browser +// (zephyr-cp, say) can keep its own common-hal/mdns and compile just this file +// to get find(); linking Server.c instead would drag in a second definition of +// every common_hal_mdns_server_* symbol. + +#include "shared-module/mdns/Browser.h" + +#include +#include + +#include "py/runtime.h" +#include "py/mphal.h" + +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/mdns/RemoteService.h" +#include "shared-bindings/socketpool/Socket.h" +#include "shared-bindings/socketpool/SocketPool.h" +#include "supervisor/shared/tick.h" + +#define MDNS_MULTICAST_IPV4 "224.0.0.251" +#define MDNS_PORT (5353) + +#define DNS_RRTYPE_A (1) +#define DNS_RRTYPE_PTR (12) +#define DNS_RRTYPE_SRV (33) + +#define DNS_RRCLASS_IN (1) +// Top bit of QCLASS in a question asks for a unicast reply; in a resource +// record the same bit is the cache-flush flag. Mask it off before comparing. +#define DNS_CLASS_UNICAST_RESPONSE (0x8000) +#define DNS_CLASS_MASK (0x7fff) + +#define DNS_HEADER_LEN (12) +// mDNS responses may be larger, but a single DNS-SD service rarely needs more +// and anything truncated is simply re-queried by calling find() again. +#define MDNS_PACKET_SIZE (1460) + +// When to repeat the PTR query: 1 s after the first, then with the gap doubling +// each time (RFC 6762 Section 5.2 requires at least 1 s between the first two). +#define MDNS_FIRST_REPEAT_MS (1000) + +// How long to wait between polls of the socket while a browse is running. +#define MDNS_POLL_INTERVAL_MS (10) + +// Longest label plus NUL, matching RemoteService's instance_name field. +#define MDNS_LABEL_SIZE (64) +// ...local - enough to validate any name we read. +#define MDNS_MAX_LABELS (4) + +// Case-insensitive compare, since DNS labels are case-insensitive (RFC 1035 +// Section 2.3.3) and responders do not preserve the case of the query. +static bool name_eq(const char *a, const char *b) { + while (*a != '\0' && *b != '\0') { + char ca = *a; + char cb = *b; + if (ca >= 'A' && ca <= 'Z') { + ca += 'a' - 'A'; + } + if (cb >= 'A' && cb <= 'Z') { + cb += 'a' - 'A'; + } + if (ca != cb) { + return false; + } + a++; + b++; + } + return *a == *b; +} + +// Read a DNS name at `offset`, following compression pointers (RFC 1035 Section +// 4.1.4). Writes up to `max_labels` leading labels into `labels`, and the number +// actually written into `n_labels`. +// +// Several labels rather than one: validating a record means checking the whole +// owner name, not its first label. An SRV for "Dev._ssh._tcp.local" and one for +// "Dev._http._tcp.local" share a first label, and matching on that alone made +// whichever arrived last win. +// +// Returns the offset of the byte after the name *in the record being read* - +// which is not where parsing ended if a pointer was followed - or 0 on a +// malformed name. +static size_t read_name(const uint8_t *pkt, size_t pkt_len, size_t offset, + char labels[][MDNS_LABEL_SIZE], size_t max_labels, size_t *n_labels) { + size_t resume = 0; + size_t jumps = 0; + size_t got = 0; + + for (size_t i = 0; i < max_labels; i++) { + labels[i][0] = '\0'; + } + if (n_labels != NULL) { + *n_labels = 0; + } + + while (offset < pkt_len) { + uint8_t len = pkt[offset]; + if (len == 0) { + // End of name. + if (n_labels != NULL) { + *n_labels = got; + } + return resume != 0 ? resume : offset + 1; + } + if ((len & 0xc0) == 0xc0) { + if (offset + 1 >= pkt_len) { + return 0; + } + size_t pointer = ((size_t)(len & 0x3f) << 8) | pkt[offset + 1]; + if (resume == 0) { + resume = offset + 2; + } + // Bound the jumps so a self-referential packet cannot hang us. + jumps++; + if (jumps > 8 || pointer >= pkt_len || pointer == offset) { + return 0; + } + offset = pointer; + continue; + } + if ((len & 0xc0) != 0) { + // Reserved label type. + return 0; + } + offset++; + if (offset + len > pkt_len) { + return 0; + } + if (got < max_labels) { + size_t copy = len; + if (copy > MDNS_LABEL_SIZE - 1) { + copy = MDNS_LABEL_SIZE - 1; + } + memcpy(labels[got], pkt + offset, copy); + labels[got][copy] = '\0'; + got++; + } + offset += len; + } + return 0; +} + +// Skip a name without decoding it. Same return convention as read_name(). +static size_t skip_name(const uint8_t *pkt, size_t pkt_len, size_t offset) { + return read_name(pkt, pkt_len, offset, NULL, 0, NULL); +} + +// Does a name's labels[1..] name the service this browse asked about, i.e. is +// `labels` of the form ..[.local]? +static bool is_instance_of(char labels[][MDNS_LABEL_SIZE], size_t n_labels, + const char *service_type, const char *protocol) { + return n_labels >= 3 && + name_eq(labels[1], service_type) && + name_eq(labels[2], protocol); +} + +static uint16_t read_u16(const uint8_t *p) { + return ((uint16_t)p[0] << 8) | p[1]; +} + +typedef struct { + mdns_remoteservice_obj_t *out; + size_t count; + size_t max; + const char *service_type; + const char *protocol; +} find_state_t; + +// Look up an in-progress result by instance name, appending a new one if there +// is room. Returns NULL when the result array is full. +static mdns_remoteservice_obj_t *get_entry(find_state_t *state, const char *instance_name, bool create) { + if (instance_name[0] == '\0') { + return NULL; + } + for (size_t i = 0; i < state->count; i++) { + if (name_eq(state->out[i].instance_name, instance_name)) { + return &state->out[i]; + } + } + if (!create || state->count >= state->max) { + return NULL; + } + mdns_remoteservice_obj_t *entry = &state->out[state->count]; + memset(entry, 0, sizeof(*entry)); + entry->base.type = &mdns_remoteservice_type; + strlcpy(entry->instance_name, instance_name, sizeof(entry->instance_name)); + strlcpy(entry->service_name, state->service_type, sizeof(entry->service_name)); + strlcpy(entry->protocol, state->protocol, sizeof(entry->protocol)); + state->count++; + return entry; +} + +// Walk every resource record in a response. +// +// `want_addresses` selects the pass: the first pass takes PTR and SRV records to +// learn which instances exist and what host each one points at, the second takes +// A records and attaches addresses to the instances found. Two passes because +// the A record for an SRV target usually arrives in the additional section, +// which may be *before* or after the SRV record that needs it. +static void parse_records(find_state_t *state, const uint8_t *pkt, size_t pkt_len, bool want_addresses) { + if (pkt_len < DNS_HEADER_LEN) { + return; + } + // Only parse responses. + if ((pkt[2] & 0x80) == 0) { + return; + } + size_t questions = read_u16(pkt + 4); + size_t records = (size_t)read_u16(pkt + 6) + read_u16(pkt + 8) + read_u16(pkt + 10); + + size_t offset = DNS_HEADER_LEN; + for (size_t i = 0; i < questions; i++) { + offset = skip_name(pkt, pkt_len, offset); + if (offset == 0 || offset + 4 > pkt_len) { + return; + } + offset += 4; + } + + char owner[MDNS_MAX_LABELS][MDNS_LABEL_SIZE]; + size_t owner_n; + for (size_t i = 0; i < records; i++) { + offset = read_name(pkt, pkt_len, offset, owner, MDNS_MAX_LABELS, &owner_n); + if (offset == 0 || offset + 10 > pkt_len) { + return; + } + uint16_t type = read_u16(pkt + offset); + uint16_t rrclass = read_u16(pkt + offset + 2) & DNS_CLASS_MASK; + uint16_t rdlength = read_u16(pkt + offset + 8); + size_t rdata = offset + 10; + offset = rdata + rdlength; + if (offset > pkt_len) { + return; + } + if (rrclass != DNS_RRCLASS_IN) { + continue; + } + + if (!want_addresses && type == DNS_RRTYPE_PTR) { + // The owner is ..local. Check BOTH labels: a PTR + // for _http._udp must not satisfy a browse for _http._tcp. + if (owner_n < 2 || !name_eq(owner[0], state->service_type) || + !name_eq(owner[1], state->protocol)) { + continue; + } + // RDATA is the full instance name: ... + char target[MDNS_MAX_LABELS][MDNS_LABEL_SIZE]; + size_t target_n; + if (read_name(pkt, pkt_len, rdata, target, MDNS_MAX_LABELS, &target_n) == 0) { + continue; + } + if (!is_instance_of(target, target_n, state->service_type, state->protocol)) { + continue; + } + get_entry(state, target[0], true); + } else if (!want_addresses && type == DNS_RRTYPE_SRV) { + // The owner is ...local and RDATA is + // priority(2) weight(2) port(2) target-name. + if (rdlength < 7) { + continue; + } + // Check the whole owner name, not just the instance label, so an SRV + // for a different service of the same instance cannot overwrite us. + if (!is_instance_of(owner, owner_n, state->service_type, state->protocol)) { + continue; + } + // Only complete an instance the PTR pass already accepted, so an + // unrelated SRV cannot add a result this browse did not ask for. + mdns_remoteservice_obj_t *entry = get_entry(state, owner[0], false); + if (entry == NULL) { + continue; + } + entry->port = read_u16(pkt + rdata + 4); + char target[1][MDNS_LABEL_SIZE]; + if (read_name(pkt, pkt_len, rdata + 6, target, 1, NULL) != 0) { + strlcpy(entry->hostname, target[0], sizeof(entry->hostname)); + } + } else if (want_addresses && type == DNS_RRTYPE_A) { + if (rdlength != 4) { + continue; + } + // Attach to every instance whose SRV target is this host. The + // hostname guard matters: without it an entry that has no SRV yet + // (empty hostname) matches an A record with a root owner name. + for (size_t j = 0; j < state->count; j++) { + mdns_remoteservice_obj_t *entry = &state->out[j]; + if (entry->ipv4_address == 0 && entry->hostname[0] != '\0' && + owner_n >= 1 && name_eq(entry->hostname, owner[0])) { + // Keep the bytes in network order, as the native backends do. + entry->ipv4_address = (uint32_t)pkt[rdata] | + (uint32_t)pkt[rdata + 1] << 8 | + (uint32_t)pkt[rdata + 2] << 16 | + (uint32_t)pkt[rdata + 3] << 24; + } + } + } + // TXT records are skipped: RemoteService has nowhere to put them today. + } +} + +// Build "..local" as a length-prefixed DNS QNAME, +// followed by QTYPE and QCLASS. Returns the total query length, or 0 if the +// names do not fit. +static size_t build_query(uint8_t *buf, size_t buf_len, const char *instance, + const char *service_type, const char *protocol, uint8_t qtype) { + if (buf_len < DNS_HEADER_LEN) { + return 0; + } + memset(buf, 0, DNS_HEADER_LEN); + // ID 0 is correct for multicast DNS (RFC 6762 Section 18.1). + buf[5] = 1; // QDCOUNT = 1 + size_t offset = DNS_HEADER_LEN; + + // With an instance the name is ...local (an + // SRV follow-up for one result); without, ..local. + const char *labels[4]; + size_t n_labels = 0; + if (instance != NULL && instance[0] != '\0') { + labels[n_labels++] = instance; + } + labels[n_labels++] = service_type; + labels[n_labels++] = protocol; + labels[n_labels++] = "local"; + for (size_t i = 0; i < n_labels; i++) { + size_t len = strlen(labels[i]); + if (len == 0 || len > 63 || offset + 1 + len + 5 > buf_len) { + return 0; + } + buf[offset++] = len; + memcpy(buf + offset, labels[i], len); + offset += len; + } + buf[offset++] = 0; // Root label. + + buf[offset++] = 0; + buf[offset++] = qtype; + uint16_t qclass = DNS_RRCLASS_IN | DNS_CLASS_UNICAST_RESPONSE; + buf[offset++] = qclass >> 8; + buf[offset++] = qclass & 0xff; + return offset; +} + +// Receive one datagram, treating a timeout or would-block as "nothing arrived" +// rather than letting it escape as an OSError. A browse is best-effort. +static size_t try_recv(socketpool_socket_obj_t *sock, uint8_t *buf, size_t buf_len) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_uint_t received = common_hal_socketpool_socket_recvfrom_into(sock, buf, buf_len, NULL); + nlr_pop(); + return received; + } + return 0; +} + +size_t shared_module_mdns_find(mp_obj_t network_interface, const char *service_type, + const char *protocol, mp_float_t timeout, mdns_remoteservice_obj_t *out, size_t out_len) { + + if (out_len == 0) { + return 0; + } + + // Zero both objects: they live on the C stack, and socketpool_socket() does + // not set every field. On espressif it leaves ssl_socket and connected alone + // (heap and static sockets are already zeroed), and socketpool_socket_close() + // treats a non-NULL ssl_socket as an SSL socket to close, so stack garbage + // there crashed the board in close(). + socketpool_socketpool_obj_t pool = { 0 }; + pool.base.type = &socketpool_socketpool_type; + common_hal_socketpool_socketpool_construct(&pool, network_interface); + + socketpool_socket_obj_t sock = { 0 }; + if (!socketpool_socket(&pool, SOCKETPOOL_AF_INET, SOCKETPOOL_SOCK_DGRAM, 0, &sock)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to start mDNS query")); + } + + find_state_t state; + state.out = out; + state.count = 0; + state.max = out_len; + state.service_type = service_type; + state.protocol = protocol; + + // Everything below must not leak the socket, which socketpool_socket() + // deliberately leaves unregistered. + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + // An ephemeral source port is what makes this a one-shot query rather + // than a full mDNS responder sharing port 5353. + if (common_hal_socketpool_socket_bind(&sock, "", 0, 0) != 0) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to start mDNS query")); + } + // RFC 6762 Section 11 wants a TTL of 255. Not every backend implements + // the option, and the default of 1 still reaches the local link, so a + // failure here is not fatal. + uint8_t ttl = 255; + common_hal_socketpool_socket_setsockopt(&sock, SOCKETPOOL_IPPROTO_IP, + SOCKETPOOL_IP_MULTICAST_TTL, &ttl, sizeof(ttl)); + common_hal_socketpool_socket_settimeout(&sock, MDNS_POLL_INTERVAL_MS); + + // Deliberately static, not m_malloc(): mdns_server_find() is called + // from the supervisor's web workflow where there may be no VM heap to + // allocate from. Documented as non-reentrant on that basis. + static uint8_t buf[MDNS_PACKET_SIZE]; + + size_t query_len = build_query(buf, MDNS_PACKET_SIZE, NULL, service_type, protocol, + DNS_RRTYPE_PTR); + if (query_len == 0) { + mp_raise_ValueError(MP_ERROR_TEXT("Invalid service type")); + } + common_hal_socketpool_socket_sendto(&sock, MDNS_MULTICAST_IPV4, + strlen(MDNS_MULTICAST_IPV4), MDNS_PORT, buf, query_len); + + uint64_t start_ticks = supervisor_ticks_ms64(); + // A negative timeout would wrap to an effectively infinite loop. + uint64_t timeout_ms = timeout > 0 ? (uint64_t)(timeout * 1000) : 0; + // Run to the full timeout even once the array is full: later packets + // still carry the SRV and A records that complete entries already found. + // A responder MAY answer with only the PTR and leave SRV/A to a + // follow-up (RFC 6763 Section 12.1 is a SHOULD, not a MUST). Without + // chasing those the browse returns entries with port 0 and no address, + // which looks like a flaky browser. Ask once, halfway through. + bool chased = false; + // Repeat the PTR query at 1 s, 3 s, 7 s, ... in case the first query or + // its replies were lost. Responders answer again, and get_entry() merges + // the duplicates by instance name. + uint64_t repeat_gap_ms = MDNS_FIRST_REPEAT_MS; + uint64_t next_repeat_ms = MDNS_FIRST_REPEAT_MS; + while (supervisor_ticks_ms64() - start_ticks < timeout_ms && + !mp_hal_is_interrupted()) { + RUN_BACKGROUND_TASKS; + uint64_t elapsed = supervisor_ticks_ms64() - start_ticks; + if (elapsed >= next_repeat_ms) { + repeat_gap_ms *= 2; + next_repeat_ms += repeat_gap_ms; + // buf holds the last packet received, so build the query again. + query_len = build_query(buf, MDNS_PACKET_SIZE, NULL, service_type, protocol, + DNS_RRTYPE_PTR); + common_hal_socketpool_socket_sendto(&sock, MDNS_MULTICAST_IPV4, + strlen(MDNS_MULTICAST_IPV4), MDNS_PORT, buf, query_len); + } + if (!chased && elapsed > timeout_ms / 2) { + chased = true; + for (size_t i = 0; i < state.count; i++) { + if (state.out[i].port != 0) { + continue; + } + size_t n = build_query(buf, MDNS_PACKET_SIZE, state.out[i].instance_name, + service_type, protocol, DNS_RRTYPE_SRV); + if (n != 0) { + common_hal_socketpool_socket_sendto(&sock, MDNS_MULTICAST_IPV4, + strlen(MDNS_MULTICAST_IPV4), MDNS_PORT, buf, n); + } + } + } + if (!common_hal_socketpool_readable(&sock)) { + // Without a yield this loop spins at 100% CPU for the whole + // timeout, which also starves the background tasks it runs. + mp_hal_delay_ms(1); + continue; + } + size_t received = try_recv(&sock, buf, MDNS_PACKET_SIZE); + if (received == 0) { + continue; + } + parse_records(&state, buf, received, false); + parse_records(&state, buf, received, true); + } + nlr_pop(); + } else { + socketpool_socket_close(&sock); + nlr_jump(nlr.ret_val); + } + socketpool_socket_close(&sock); + + return state.count; +} diff --git a/shared-module/mdns/Browser.h b/shared-module/mdns/Browser.h new file mode 100644 index 00000000000..e445666b074 --- /dev/null +++ b/shared-module/mdns/Browser.h @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// A portable DNS-SD browser built on socketpool, so that mdns.Server.find() +// works on any port that terminates an IP stack on the host rather than only on +// those with a native mDNS library. +// +// This is a "one-shot multicast DNS query" in the sense of RFC 6762 Section 5.1: +// the query goes out from an ephemeral port with the unicast-response (QU) bit +// set, so responders reply directly to us and we never have to join the +// 224.0.0.251 multicast group. That matters because socketpool exposes +// IP_MULTICAST_TTL but has no IP_ADD_MEMBERSHIP, so a group-joining browser is +// not portable today. The cost is that responses a responder chooses to +// multicast instead (RFC 6762 Section 5.4 permits this when it has not answered +// recently) are missed; a repeat find() generally picks them up. + + +#pragma once + +#include "py/obj.h" + +#include "shared-bindings/mdns/RemoteService.h" + +// Run one DNS-SD browse over plain sockets and return how many services were +// written into `out` (at most `out_len`). +// +// Needs only a SocketPool, so it works on any backend that terminates an IP +// stack on the host. `network_interface` is what a SocketPool is constructed +// from. May raise; callers without an nlr handler must wrap it. +// +// Not reentrant: it uses a single static receive buffer so that it can run in +// supervisor context, where there may be no VM heap. +size_t shared_module_mdns_find(mp_obj_t network_interface, const char *service_type, + const char *protocol, mp_float_t timeout, mdns_remoteservice_obj_t *out, size_t out_len); diff --git a/shared-module/mdns/RemoteService.c b/shared-module/mdns/RemoteService.c new file mode 100644 index 00000000000..f9e2b7d3c89 --- /dev/null +++ b/shared-module/mdns/RemoteService.c @@ -0,0 +1,41 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mdns/RemoteService.h" + +#include "shared-bindings/ipaddress/IPv4Address.h" + +const char *common_hal_mdns_remoteservice_get_service_type(mdns_remoteservice_obj_t *self) { + return self->service_name; +} + +const char *common_hal_mdns_remoteservice_get_protocol(mdns_remoteservice_obj_t *self) { + return self->protocol; +} + +const char *common_hal_mdns_remoteservice_get_instance_name(mdns_remoteservice_obj_t *self) { + return self->instance_name; +} + +const char *common_hal_mdns_remoteservice_get_hostname(mdns_remoteservice_obj_t *self) { + return self->hostname; +} + +mp_int_t common_hal_mdns_remoteservice_get_port(mdns_remoteservice_obj_t *self) { + return self->port; +} + +uint32_t mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self) { + return self->ipv4_address; +} + +mp_obj_t common_hal_mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self) { + uint32_t addr = mdns_remoteservice_get_ipv4_address(self); + if (addr == 0) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(addr); +} diff --git a/shared-module/mdns/RemoteService.h b/shared-module/mdns/RemoteService.h new file mode 100644 index 00000000000..420ade61a20 --- /dev/null +++ b/shared-module/mdns/RemoteService.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +// Field names and sizes match the native backends (see +// ports/raspberrypi/common-hal/mdns/RemoteService.h) so that shared-bindings +// and the web workflow are agnostic to which implementation is built. +typedef struct { + mp_obj_base_t base; + uint32_t ipv4_address; // Network byte order, as the native backends store it. + uint16_t port; + char protocol[5]; // RFC 6763 Section 7.2 - 4 bytes + 1 for NUL + char service_name[17]; // RFC 6763 Section 7.2 - 16 bytes + 1 for NUL + char instance_name[64]; // RFC 6763 Section 7.2 - 63 bytes + 1 for NUL + char hostname[64]; // RFC 6762 Appendix A - 63 bytes for label + 1 for NUL + mp_obj_t next; +} mdns_remoteservice_obj_t; diff --git a/shared-module/mdns/Server.c b/shared-module/mdns/Server.c new file mode 100644 index 00000000000..42d262972ae --- /dev/null +++ b/shared-module/mdns/Server.c @@ -0,0 +1,148 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// A portable DNS-SD browser built on socketpool, so that mdns.Server.find() +// works on any port that terminates an IP stack on the host rather than only on +// those with a native mDNS library. +// +// This is a "one-shot multicast DNS query" in the sense of RFC 6762 Section 5.1: +// the query goes out from an ephemeral port with the unicast-response (QU) bit +// set, so responders reply directly to us and we never have to join the +// 224.0.0.251 multicast group. That matters because socketpool exposes +// IP_MULTICAST_TTL but has no IP_ADD_MEMBERSHIP, so a group-joining browser is +// not portable today. The cost is that responses a responder chooses to +// multicast instead (RFC 6762 Section 5.4 permits this when it has not answered +// recently) are missed; a repeat find() generally picks them up. + + +#include "shared-bindings/mdns/Server.h" + +#include +#include + +#include "py/objtuple.h" +#include "py/runtime.h" + +#include "shared-bindings/mdns/RemoteService.h" +#include "shared-module/mdns/Browser.h" + +#if CIRCUITPY_WIFI +#include "shared-bindings/wifi/__init__.h" +#endif + +// The allocating find() collects into a bounded scratch array rather than an +// unbounded list, so a chatty network cannot exhaust the heap mid-browse. +#define MDNS_MAX_RESULTS (16) + + +void mdns_server_construct(mdns_server_obj_t *self, bool workflow) { + self->hostname[0] = '\0'; + self->instance_name[0] = '\0'; + // The web workflow calls this directly on a static object, so default the + // interface here rather than only in common_hal_mdns_server_construct(). + #if CIRCUITPY_WIFI + self->network_interface = MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj); + #else + self->network_interface = mp_const_none; + #endif + self->workflow = workflow; + self->inited = true; +} + +void common_hal_mdns_server_construct(mdns_server_obj_t *self, mp_obj_t network_interface) { + #if CIRCUITPY_WIFI + if (network_interface != MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj)) { + mp_raise_ValueError(MP_ERROR_TEXT("mDNS only works with built-in WiFi")); + } + #endif + mdns_server_construct(self, false); + self->network_interface = network_interface; +} + +void common_hal_mdns_server_deinit(mdns_server_obj_t *self) { + self->inited = false; +} + +void mdns_server_deinit_singleton(void) { + // find() opens and closes its own socket, so nothing outlives a call and + // there is nothing to tear down when the radio stops. espressif's + // common_hal_wifi_radio_set_enabled() calls this unconditionally. +} + +bool common_hal_mdns_server_deinited(mdns_server_obj_t *self) { + return !self->inited; +} + +const char *common_hal_mdns_server_get_hostname(mdns_server_obj_t *self) { + return self->hostname; +} + +void common_hal_mdns_server_set_hostname(mdns_server_obj_t *self, const char *hostname) { + strlcpy(self->hostname, hostname, sizeof(self->hostname)); +} + +const char *common_hal_mdns_server_get_instance_name(mdns_server_obj_t *self) { + if (self->instance_name[0] == '\0') { + return self->hostname; + } + return self->instance_name; +} + +void common_hal_mdns_server_set_instance_name(mdns_server_obj_t *self, const char *instance_name) { + strlcpy(self->instance_name, instance_name, sizeof(self->instance_name)); +} + +void common_hal_mdns_server_advertise_service(mdns_server_obj_t *self, const char *service_type, + const char *protocol, mp_int_t port, const char *txt_records[], size_t num_txt_records) { + // This implementation is a browser only: answering queries needs a + // responder holding port 5353, which belongs in the port's own common-hal. + // + // The supervisor advertises the web workflow through this same entry point + // (supervisor/shared/web_workflow/web_workflow.c), with no nlr handler in + // place, so raising there would be fatal. Report the limitation to user code + // and let the supervisor carry on unadvertised - its HTTP server still + // serves, it simply cannot be discovered by name. + if (self->workflow) { + return; + } + mp_raise_NotImplementedError(MP_ERROR_TEXT("Advertising services is not supported on this board")); +} + +// Non-allocating entry point, also used by the supervisor's web workflow +// (supervisor/shared/web_workflow/web_workflow.c). That caller has no nlr +// handler, so nothing may escape from here: a failed browse is zero results. +size_t mdns_server_find(mdns_server_obj_t *self, const char *service_type, const char *protocol, + mp_float_t timeout, mdns_remoteservice_obj_t *out, size_t out_len) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + size_t count = shared_module_mdns_find(self->network_interface, service_type, protocol, + timeout, out, out_len); + nlr_pop(); + return count; + } + // Swallowed on purpose; see the comment above. Raising here would longjmp + // into a handler that does not exist. + return 0; +} + +mp_obj_t common_hal_mdns_server_find(mdns_server_obj_t *self, const char *service_type, + const char *protocol, mp_float_t timeout) { + // Browse into a scratch array, then hand out one GC object per result so + // each is independently tracked, matching the native backends. + mdns_remoteservice_obj_t *scratch = m_new(mdns_remoteservice_obj_t, MDNS_MAX_RESULTS); + size_t count = shared_module_mdns_find(self->network_interface, service_type, protocol, + timeout, scratch, MDNS_MAX_RESULTS); + + mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(count, NULL)); + for (size_t i = 0; i < count; i++) { + mdns_remoteservice_obj_t *service = m_new_obj(mdns_remoteservice_obj_t); + *service = scratch[i]; + service->base.type = &mdns_remoteservice_type; + service->next = NULL; + tuple->items[i] = MP_OBJ_FROM_PTR(service); + } + return MP_OBJ_FROM_PTR(tuple); +} diff --git a/shared-module/mdns/Server.h b/shared-module/mdns/Server.h new file mode 100644 index 00000000000..398f43b8bc6 --- /dev/null +++ b/shared-module/mdns/Server.h @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +#include "shared-module/mdns/RemoteService.h" + +typedef struct { + mp_obj_base_t base; + // The radio this server queries through. Kept so find() can build a + // SocketPool on demand rather than holding a socket open. + mp_obj_t network_interface; + // Stored for the hostname/instance_name properties. This implementation has + // no responder, so they are not advertised anywhere; see + // common_hal_mdns_server_advertise_service(). + char hostname[64]; // RFC 6762 Appendix A - 63 bytes for label + 1 for NUL + char instance_name[64]; // RFC 6763 Section 7.2 - 63 bytes + 1 for NUL + // Set for the supervisor's web workflow object, which cannot handle an + // exception. See common_hal_mdns_server_advertise_service(). + bool workflow; + bool inited; +} mdns_server_obj_t; + +// Called by a port's wifi code before the radio stops, as the native +// responders need. The browser holds no state between find() calls, so it has +// nothing to release; it exists so those ports still link with the browser. +void mdns_server_deinit_singleton(void); diff --git a/shared-module/mdns/__init__.c b/shared-module/mdns/__init__.c new file mode 100644 index 00000000000..9ea5e1a844d --- /dev/null +++ b/shared-module/mdns/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No mdns module functions.