From dc595256e18fd66b85c67663bd348a3b4cce0ca0 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Thu, 19 Nov 2026 22:57:59 -0600 Subject: [PATCH 1/2] feat(switch2_pro): pair a new console without forgetting the current one clear_bond() was the only way into pairing mode, so entering it erased the stored console (NVS + NimBLE key record) before any new console had paired: a pairing window that ended without one left the controller bonded to nothing. start_pairing() behaves like a real controller's sync button: it advertises for discovery but keeps the current bond aside, in NVS and in NimBLE's security store. A console that completes the 0x15 handshake replaces it (and the previous console's key record is dropped unless it is the same console pairing again); cancel_pairing() restores it (reconnect mode, LTK re-injected, reconnect advertising unless stop_advertising() suppressed it), and so does a reboot, since NVS is never touched. If the previous console reconnects with its stored key during the window, the window closes on its bond. is_pairing() reports an open window; clear_bond() also forgets a kept bond. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/switch2_pro/README.md | 14 ++ .../switch2_pro/include/switch2_pro.hpp | 43 ++++++ components/switch2_pro/src/switch2_pro.cpp | 127 +++++++++++++++++- 3 files changed, 180 insertions(+), 4 deletions(-) diff --git a/components/switch2_pro/README.md b/components/switch2_pro/README.md index 64f06b57ed..2d2d1d0e96 100644 --- a/components/switch2_pro/README.md +++ b/components/switch2_pro/README.md @@ -47,6 +47,20 @@ espp::Switch2Pro controller({.device_name = "Pro Controller"}); controller.init(); // verifies pairing crypto, builds GATT, advertises ``` +### Pairing with another console + +A bonded controller advertises for its console (reconnect / wake). To pair with +a different console there are two ways in: + +- `start_pairing()` — like a real controller's sync button: advertise for + discovery but **keep the current bond** until a new console completes the + pairing handshake, which replaces it. If none does, `cancel_pairing()` (e.g. + when your pairing window times out) goes back to the previous console, and so + does a reboot, since the stored bond is never touched. If the previous console + reconnects during the window, the window closes on its bond. +- `clear_bond()` — forget the stored console now (NVS + NimBLE key record) and + advertise for discovery; use it for a "forget" / factory-reset action. + ## The 5 ms connection interval (required for sustained input, reconnect & wake) The console chooses the connection interval **in its `CONNECT_IND`, based on diff --git a/components/switch2_pro/include/switch2_pro.hpp b/components/switch2_pro/include/switch2_pro.hpp index 298e3f5563..f0c829297b 100644 --- a/components/switch2_pro/include/switch2_pro.hpp +++ b/components/switch2_pro/include/switch2_pro.hpp @@ -164,6 +164,35 @@ class Switch2Pro : public BaseComponent { /// (or none was stored); false if the NVS erase/commit failed. bool clear_bond(); + /// Pair with a (new) console WITHOUT forgetting the current one first, the way + /// a real controller's sync button behaves: advertise for discovery (fresh + /// pairing) while the stored bond stays in NVS and in NimBLE's security store. + /// A console that completes the pairing handshake replaces it (the old + /// console's NimBLE key record is then dropped); if none does, cancel_pairing() + /// returns to the previous console - and so does a reboot, since NVS is never + /// touched. With no bond stored this is the same discovery mode clear_bond() + /// leaves. While pairing, is_paired() is false and bonded_console_address() + /// empty, exactly as after clear_bond(). Re-enables the automatic re-advertise + /// a prior stop_advertising() suppressed. A live console link is NOT dropped + /// (use disconnect() for that); discovery advertising starts once nothing is + /// connected. Calling it again while pairing restarts the advertisement and + /// keeps the original bond. @return true if discovery advertising is on the + /// air or will start on the next disconnect. + bool start_pairing(); + + /// End a start_pairing() window that no console completed: restore the bond + /// that was stored when it began (reconnect mode, its LTK re-injected) and, + /// unless advertising is suppressed by stop_advertising() or a console is + /// connected, advertise for that console again (passive reconnect variant). An + /// unfinished handshake on a live link is abandoned (its FINALISE is then + /// rejected). @return true if a previous bond was restored; false if not + /// pairing, or there was no bond to go back to (discovery mode stays). + bool cancel_pairing(); + + /// Whether a start_pairing() window is open (no console has completed pairing + /// since, and cancel_pairing() / clear_bond() has not been called). + bool is_pairing() const { return pairing_; } + /// Whether the console has subscribed to the input characteristic (0x000e) on an /// LL-encrypted connection, i.e. the stream loop is actually sending input /// reports. Goes true once the subscribed link is encrypted and false on @@ -482,6 +511,20 @@ class Switch2Pro : public BaseComponent { std::array host_addr_{}; ///< console BD_ADDR (from exchange-addresses) uint8_t bond_peer_type_{0}; ///< persisted console address type std::array bond_peer_val_{}; ///< persisted console address (wire/little-endian order) + /// The bond that was current when start_pairing() began (guarded by + /// bond_mutex_): what cancel_pairing() restores, and whose NimBLE key record a + /// completed pairing with a different console drops. + struct KeptBond { + bool valid{false}; + uint8_t peer_type{0}; + std::array peer_val{}; + std::array host_addr{}; + std::array ltk{}; + }; + KeptBond kept_bond_{}; + /// A start_pairing() window is open. Written from the app task and the FINALISE + /// handler (host task) - atomic. + std::atomic pairing_{false}; uint8_t feature_mask_{switch2::PRO2_FEATURE_MASK}; /// Features the console has actually enabled via FEATURE_SELECT (0x0c). The /// input report must reflect these: rumble (bit 5) sets report byte 0x0B to diff --git a/components/switch2_pro/src/switch2_pro.cpp b/components/switch2_pro/src/switch2_pro.cpp index 138a152a6a..91db4f25df 100644 --- a/components/switch2_pro/src/switch2_pro.cpp +++ b/components/switch2_pro/src/switch2_pro.cpp @@ -388,6 +388,13 @@ void Switch2Pro::configure_callbacks() { // so a peer that merely connects and subscribes without pairing never receives // button/stick data. encrypted_ = info.isEncrypted(); + // A link that encrypted during a start_pairing() window WITHOUT running the + // 0x15 handshake can only have used a stored key: the kept console came back + // instead of a new one pairing. Close the window on its bond. + if (info.isEncrypted() && pairing_ && pairing_stage_ == 0) { + logger_.info("pairing: the previous console reconnected during the pairing window"); + cancel_pairing(); + } // A usable (encrypted) session is now established, so any pending wake has // succeeded: drop the wake latches. Doing it here (not on the raw connect event) // means a transient connect/drop before encryption keeps the wake variant on the @@ -1231,13 +1238,27 @@ bool Switch2Pro::clear_bond() { // peer's LL encryption key is not usable for the rest of this boot (a persisted // NVS erase alone leaves the live key in place). Do this while the peer address is // still in RAM, before it is zeroed below. - if (paired_ || reconnect_mode_) { - ble_addr_t peer{}; - { - std::lock_guard lk(bond_mutex_); + // A start_pairing() window keeps the previous console's record aside (the + // live fields are already in discovery mode): forget that one too. + std::vector peers; + { + std::lock_guard lk(bond_mutex_); + if (paired_ || reconnect_mode_) { + ble_addr_t peer{}; peer.type = bond_peer_type_; std::copy(bond_peer_val_.begin(), bond_peer_val_.end(), peer.val); + peers.push_back(peer); } + if (kept_bond_.valid) { + ble_addr_t peer{}; + peer.type = kept_bond_.peer_type; + std::copy(kept_bond_.peer_val.begin(), kept_bond_.peer_val.end(), peer.val); + peers.push_back(peer); + } + kept_bond_ = {}; + pairing_ = false; + } + for (auto &peer : peers) { int rc = ble_gap_unpair(&peer); if (rc != 0 && rc != BLE_HS_ENOENT) { // ENOENT = nothing stored for this peer logger_.error("clear_bond: failed to delete the NimBLE security record (rc={})", rc); @@ -1266,6 +1287,81 @@ bool Switch2Pro::clear_bond() { return ok; } +bool Switch2Pro::start_pairing() { + // Keep the current bond aside (only the first call of a window: a repeat keeps + // the ORIGINAL console, not the cleared discovery state), then reset the + // in-memory identity to fresh-pairing mode exactly like clear_bond() does - but + // leave NVS and NimBLE's security record alone, so cancel_pairing() (or a + // reboot) can go back to that console. + bool kept = false; + { + std::lock_guard lk(bond_mutex_); + if (!pairing_) { + kept_bond_ = {}; + if (reconnect_mode_ && paired_) { + kept_bond_.valid = true; + kept_bond_.peer_type = bond_peer_type_; + kept_bond_.peer_val = bond_peer_val_; + kept_bond_.host_addr = host_addr_; + kept_bond_.ltk = ltk_; + } + } + pairing_ = true; + reconnect_mode_ = false; + paired_ = false; + wake_pending_ = false; + boot_wake_pending_ = false; + bond_peer_type_ = 0; + bond_peer_val_ = {}; + host_addr_ = {}; + ltk_ = {}; + kept = kept_bond_.valid; + } + logger_.info("pairing: advertising for a new console ({} bond kept until one pairs)", + kept ? "the current" : "no"); + // An explicit pairing request re-enables the automatic re-advertise a prior + // stop_advertising() had suppressed; a live link re-advertises (for discovery) + // when it drops. + readvertise_suppressed_ = false; + if (active_conn_handle_ != 0xffff) + return true; + return advertise(); // reconnect_mode_ is off: the discovery variant +} + +bool Switch2Pro::cancel_pairing() { + if (!pairing_) + return false; + KeptBond kept{}; + { + std::lock_guard lk(bond_mutex_); + pairing_ = false; + pairing_stage_ = 0; // abandon a half-done handshake: its FINALISE is rejected + kept = kept_bond_; + kept_bond_ = {}; + if (kept.valid) { + bond_peer_type_ = kept.peer_type; + bond_peer_val_ = kept.peer_val; + host_addr_ = kept.host_addr; + ltk_ = kept.ltk; + paired_ = true; + reconnect_mode_ = true; + } + } + if (!kept.valid) { + logger_.info("pairing: window ended with no new console and no previous bond"); + return false; + } + // The record was never deleted, but a handshake that reached FINALISE's LTK + // injection for another peer may have shared the store; re-inject to be sure + // the restored console can encrypt straight away. + if (!inject_ltk(kept.peer_type, kept.peer_val.data())) + logger_.error("pairing: re-injecting the previous console's LTK failed"); + logger_.info("pairing: window ended with no new console - back to the previous one"); + if (active_conn_handle_ == 0xffff && !readvertise_suppressed_) + advertise(); // reconnect_mode_ is back on: the reconnect variant + return true; +} + bool Switch2Pro::erase_stored_bond() { // Static: erase ONLY the NVS bond blob. With no instance there is no NimBLE // security record to remove and no advertising to restart. A missing bond is @@ -1463,6 +1559,29 @@ void Switch2Pro::handle_pairing(bool via_vibration_command, uint8_t transport, P // without re-running the pairing exchange. save_bond(); reconnect_mode_ = true; + // A start_pairing() window is complete: the new bond replaced the kept one. + // Drop the previous console's NimBLE key record unless it was this console + // pairing again (same address: the injection above already overwrote it). + if (pairing_.exchange(false)) { + ble_addr_t old_peer{}; + bool drop_old = false; + { + std::lock_guard lk(bond_mutex_); + if (kept_bond_.valid && + (kept_bond_.peer_type != bond_peer_type_ || kept_bond_.peer_val != bond_peer_val_)) { + drop_old = true; + old_peer.type = kept_bond_.peer_type; + std::copy(kept_bond_.peer_val.begin(), kept_bond_.peer_val.end(), old_peer.val); + } + kept_bond_ = {}; + } + if (drop_old) { + const int rc = ble_gap_unpair(&old_peer); + if (rc != 0 && rc != BLE_HS_ENOENT) + logger_.warn("pairing: dropping the previous console's key record failed (rc={})", rc); + } + logger_.info("pairing: the new console replaced the previous bond"); + } if (callbacks_.on_paired) callbacks_.on_paired(); break; From 6250b8a27d77702b582713f13a0a714044146966 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Fri, 20 Nov 2026 09:58:02 -0600 Subject: [PATCH 2/2] fix(switch2_pro): serialise the pairing window against the handshake - The 0x15 handshake now fills its own scratch (console identity + LTK); only an accepted FINALISE commits it into the bond. Each step checks and advances pairing_stage_ under bond_mutex_ in one hold, and FINALISE checks and commits (bond, paired, reconnect mode, window close, kept bond) in one hold. A repeat start_pairing() no longer zeroes a live handshake's LTK, and cancel_pairing() can no longer be overwritten by an in-flight step or mix two consoles' bonds in NVS. - cancel_pairing() rejects every further pairing step on the current link (until the console reconnects), so a still-connected console cannot restart the handshake over the restored bond. - clear_bond() / FINALISE stop advertising before deleting a NimBLE key record: ble_gap_unpair() returns BLE_HS_EBUSY while advertising, so the record was silently kept. - adv_mutex_ serialises choosing + starting an advertisement against the bond transitions, so a wake-timer tick holding the old bond cannot put its advertisement back on the air after start_pairing(). - start_pairing() rolls a window it opened back if advertising fails. - FINALISE drops the previous console's key record only once NVS holds the new bond (save_bond() now reports it); otherwise a reboot returns to the previous console, which must still be able to encrypt. - The "previous console reconnected" check matches the kept console's address and only the link's first encryption. - Bond struct + std::optional kept bond, reset_bond_locked() and unpair_peer() helpers replace the copied fields and reset blocks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../switch2_pro/include/switch2_pro.hpp | 112 +++-- components/switch2_pro/src/switch2_pro.cpp | 474 ++++++++++-------- 2 files changed, 338 insertions(+), 248 deletions(-) diff --git a/components/switch2_pro/include/switch2_pro.hpp b/components/switch2_pro/include/switch2_pro.hpp index f0c829297b..11e3d1d84f 100644 --- a/components/switch2_pro/include/switch2_pro.hpp +++ b/components/switch2_pro/include/switch2_pro.hpp @@ -175,17 +175,22 @@ class Switch2Pro : public BaseComponent { /// empty, exactly as after clear_bond(). Re-enables the automatic re-advertise /// a prior stop_advertising() suppressed. A live console link is NOT dropped /// (use disconnect() for that); discovery advertising starts once nothing is - /// connected. Calling it again while pairing restarts the advertisement and - /// keeps the original bond. @return true if discovery advertising is on the - /// air or will start on the next disconnect. + /// connected. Calling it again while pairing restarts the advertisement, keeps + /// the original bond and leaves a handshake already running on a live link + /// alone. @return true if discovery advertising is on the air or will start on + /// the next disconnect; false if advertising failed to start, in which case a + /// window this call opened is rolled back (the previous bond stays current). bool start_pairing(); /// End a start_pairing() window that no console completed: restore the bond /// that was stored when it began (reconnect mode, its LTK re-injected) and, /// unless advertising is suppressed by stop_advertising() or a console is /// connected, advertise for that console again (passive reconnect variant). An - /// unfinished handshake on a live link is abandoned (its FINALISE is then - /// rejected). @return true if a previous bond was restored; false if not + /// unfinished handshake on a live link is abandoned: every further pairing step + /// on that connection, FINALISE included, is rejected until the console + /// reconnects. The window also ends this way when the previous console itself + /// reconnects and encrypts during it. @return true if a previous bond was + /// restored; false if not /// pairing, or there was no bond to go back to (discovery mode stays). bool cancel_pairing(); @@ -272,9 +277,11 @@ class Switch2Pro : public BaseComponent { bool start_advertising(AdvMode mode, const std::array &host_addr_le = {}); /// Advertise in the mode appropriate to the current state: Wake (with the stored /// console address) if bonded and wake-on-boot is enabled, else Reconnect if - /// bonded, else Discovery. + /// bonded, else Discovery. Takes adv_mutex_. /// @return true if advertising actually started. bool advertise(); + /// advertise() for a caller that already holds adv_mutex_. + bool advertise_locked(); /// Start a periodic timer that re-issues the wake advertisement (via advertise()) /// every wake_interval_ while disconnected, so a sleeping console keeps getting /// nudged until it wakes and reconnects. No-op if already running. @@ -304,21 +311,36 @@ class Switch2Pro : public BaseComponent { /// Pro Controller 2's init-sequence ACKs. void send_ack(bool via_vibration_command, uint8_t cmd, uint8_t transport, uint8_t sub); - /// Inject the current LTK (ltk_) into NimBLE's security store for `peer` so the + /// A bond with one console: who it is and the key its link encrypts with. + struct Bond { + uint8_t peer_type{0}; ///< NimBLE peer identity address type + std::array peer_val{}; ///< NimBLE peer identity address (wire/little-endian) + std::array host_addr{}; ///< console identity from exchange-addresses (wire order) + std::array ltk{}; ///< derived during key exchange (A1 ^ B1) + bool same_peer(const Bond &other) const { + return peer_type == other.peer_type && peer_val == other.peer_val; + } + }; + + /// Inject `bond`'s LTK into NimBLE's security store for its peer so the /// controller can satisfy the console's link-layer encryption request (the /// Switch 2 uses standard LL encryption with the app-derived LTK, not SMP). /// @return true if the LTK was written to the store; false on failure (LL /// encryption will then fail and the console will drop the link). - bool inject_ltk(uint8_t peer_type, const uint8_t *peer_val_le); - /// Inject ltk_ for the currently-connected peer (used right after finalise). - /// @return true on success; false if there is no active connection or the - /// store write failed. - bool inject_pairing_ltk(); - /// Persist the bond {console address, LTK} to NVS so it survives reboots and - /// the controller can reconnect/wake without re-pairing. - void save_bond(); - /// Load a persisted bond into bond_peer_* / ltk_. Returns true if one exists. + bool inject_ltk(const Bond &bond); + /// Persist `bond` to NVS so it survives reboots and the controller can + /// reconnect/wake without re-pairing. @return true if it was written. + bool save_bond(const Bond &bond); + /// Load a persisted bond into bond_. Returns true if one exists. bool load_bond(); + /// Reset the live bond to fresh-pairing (discovery) mode: not paired, no + /// reconnect identity, no pending wake. Caller holds bond_mutex_. + void reset_bond_locked(); + /// Delete `peer`'s NimBLE security record. NimBLE refuses that (BLE_HS_EBUSY) + /// while advertising, so advertising is stopped first; the caller holds + /// adv_mutex_ so nothing restarts it before the caller re-advertises. + /// @return true if deleted or nothing was stored for the peer. + bool unpair_peer(uint8_t peer_type, const std::array &peer_val); /// Monotonic microseconds since boot (steady_clock), for the stream telemetry. static int64_t now_us(); /// Our own BT address (6 bytes) for the exchange-addresses reply. @@ -426,7 +448,9 @@ class Switch2Pro : public BaseComponent { /// Highest completed 0x15 pairing step this connection: 0=none, 1=exchange /// addresses, 2=exchange keys, 3=confirm LTK. FINALISE (step 4) is only accepted /// when this is 3, so an out-of-order/malformed peer cannot persist a bad bond. - /// Reset to 0 on each new connection. + /// Reset to 0 on each new connection. Guarded by bond_mutex_: each step checks + /// and advances it in one hold, so cancel_pairing() lands wholly before or + /// after a step. uint8_t pairing_stage_{0}; /// init() lifecycle: init_attempted_ latches on the first init() call so a retry /// after a partial failure is refused (it would rebuild GATT against a live @@ -499,31 +523,37 @@ class Switch2Pro : public BaseComponent { /// Current connection handle (0xffff = BLE_HS_CONN_HANDLE_NONE). Written from the /// NimBLE connect/disconnect callbacks, read by the streaming/timer threads — atomic. std::atomic active_conn_handle_{0xffff}; - /// Guards the bond / session identity below. It is written by the pairing - /// handler (NimBLE host task), load/save/clear_bond (init, host task, app - /// task) and read by advertise() / wake_console() / inject_ltk() (host task, - /// wake timer, app task). Readers copy what they need under the lock and call - /// NimBLE after releasing it; clear_bond() resets the fields together with - /// reconnect_mode_ under it, so an advertisement never embeds a half-cleared - /// address. + /// Serialises choosing and starting an advertisement against the bond-state + /// transitions that change which one is right. advertise() (disconnect + /// callback, wake timer), wake_console(), start/cancel_pairing() and + /// clear_bond() hold it, so a wake tick that snapshotted the old bond cannot put + /// that advertisement back on the air after a transition, and nothing restarts + /// advertising while a NimBLE key record is deleted. Lock order: adv_mutex_, + /// then bond_mutex_. Never held while joining the wake timer. + std::mutex adv_mutex_; + /// Guards the bond / session identity and the pairing window below. Written + /// by the pairing handler (NimBLE host task), load_bond / clear_bond / + /// start_pairing / cancel_pairing (init, host task, app task) and read by + /// advertise() / wake_console() (host task, wake timer, app task). Holders copy + /// what they need and call NimBLE after releasing it; a transition changes the + /// fields together with reconnect_mode_ / paired_ / pairing_ in one hold, so a + /// reader never sees a half-changed bond. mutable std::mutex bond_mutex_; - std::array ltk_{}; ///< derived during key exchange (A1 ^ B1) - std::array host_addr_{}; ///< console BD_ADDR (from exchange-addresses) - uint8_t bond_peer_type_{0}; ///< persisted console address type - std::array bond_peer_val_{}; ///< persisted console address (wire/little-endian order) - /// The bond that was current when start_pairing() began (guarded by - /// bond_mutex_): what cancel_pairing() restores, and whose NimBLE key record a - /// completed pairing with a different console drops. - struct KeptBond { - bool valid{false}; - uint8_t peer_type{0}; - std::array peer_val{}; - std::array host_addr{}; - std::array ltk{}; - }; - KeptBond kept_bond_{}; - /// A start_pairing() window is open. Written from the app task and the FINALISE - /// handler (host task) - atomic. + Bond bond_{}; ///< the current bond (all zero in discovery mode) + /// Handshake scratch: the console identity and LTK of a pairing in progress. + /// Committed into bond_ only by an accepted FINALISE, so start_pairing(), + /// cancel_pairing() and a restarted handshake never see or clobber each other. + std::array pending_host_addr_{}; + std::array pending_ltk_{}; + /// cancel_pairing() abandoned the handshake on the current link: reject every + /// further step on it. Cleared on each new connection. + bool handshake_closed_{false}; + /// The bond that was current when start_pairing() began: what cancel_pairing() + /// restores, and whose NimBLE key record a completed pairing with a different + /// console drops. + std::optional kept_bond_; + /// A start_pairing() window is open. Written under bond_mutex_; atomic so + /// is_pairing() can read it without the lock. std::atomic pairing_{false}; uint8_t feature_mask_{switch2::PRO2_FEATURE_MASK}; /// Features the console has actually enabled via FEATURE_SELECT (0x0c). The diff --git a/components/switch2_pro/src/switch2_pro.cpp b/components/switch2_pro/src/switch2_pro.cpp index 91db4f25df..3fb1fc8412 100644 --- a/components/switch2_pro/src/switch2_pro.cpp +++ b/components/switch2_pro/src/switch2_pro.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include "esp_mac.h" @@ -175,14 +176,12 @@ bool Switch2Pro::init() { // On reconnect the console skips the 0x15 pairing and jumps straight to LL // encryption, so the LTK must already be in NimBLE's store before it connects. if (reconnect_mode_) { - uint8_t peer_type = 0; - std::array peer_val{}; + Bond bond; { std::lock_guard lk(bond_mutex_); - peer_type = bond_peer_type_; - peer_val = bond_peer_val_; + bond = bond_; } - if (!inject_ltk(peer_type, peer_val.data())) + if (!inject_ltk(bond)) logger_.error("reconnect: pre-loading the stored LTK failed — a bonded reconnect/wake " "will not encrypt; call clear_bond() and re-pair to recover"); if (wake_console_on_boot_enabled_) { @@ -290,7 +289,12 @@ void Switch2Pro::configure_callbacks() { // over-the-air address the console connected to (see local_bt_address()). active_conn_handle_ = info.getConnHandle(); encrypted_ = false; // not yet encrypted — set on authentication_complete - pairing_stage_ = 0; // a fresh connection restarts the 0x15 handshake sequence + { + // a fresh connection restarts the 0x15 handshake sequence + std::lock_guard lk(bond_mutex_); + pairing_stage_ = 0; + handshake_closed_ = false; + } // NOTE: the wake latches (wake_pending_ / boot_wake_pending_) are deliberately // NOT cleared here. A console we just woke can connect and then drop again before // encryption/init completes; clearing on the raw connect event would make the @@ -387,13 +391,26 @@ void Switch2Pro::configure_callbacks() { // link (established by the console's LL encryption after the 0x15 handshake), // so a peer that merely connects and subscribes without pairing never receives // button/stick data. - encrypted_ = info.isEncrypted(); - // A link that encrypted during a start_pairing() window WITHOUT running the - // 0x15 handshake can only have used a stored key: the kept console came back - // instead of a new one pairing. Close the window on its bond. - if (info.isEncrypted() && pairing_ && pairing_stage_ == 0) { - logger_.info("pairing: the previous console reconnected during the pairing window"); - cancel_pairing(); + const bool was_encrypted = encrypted_.exchange(info.isEncrypted()); + // The kept console encrypting a link during a start_pairing() window WITHOUT + // running the 0x15 handshake means it came back instead of a new console + // pairing: close the window on its bond. Only the first encryption of the + // link counts (not a later key refresh), and only for that console's address. + if (info.isEncrypted() && !was_encrypted && pairing_) { + struct ble_gap_conn_desc desc; + bool kept_console = false; + if (ble_gap_conn_find(info.getConnHandle(), &desc) == 0) { + Bond peer; + peer.peer_type = desc.peer_id_addr.type; + std::copy(std::begin(desc.peer_id_addr.val), std::end(desc.peer_id_addr.val), + peer.peer_val.begin()); + std::lock_guard lk(bond_mutex_); + kept_console = pairing_stage_ == 0 && kept_bond_ && kept_bond_->same_peer(peer); + } + if (kept_console) { + logger_.info("pairing: the previous console reconnected during the pairing window"); + cancel_pairing(); + } } // A usable (encrypted) session is now established, so any pending wake has // succeeded: drop the wake latches. Doing it here (not on the raw connect event) @@ -592,10 +609,15 @@ bool Switch2Pro::start_advertising(AdvMode mode, const std::array &h } bool Switch2Pro::advertise() { + std::lock_guard lk(adv_mutex_); + return advertise_locked(); +} + +bool Switch2Pro::advertise_locked() { // Embed the console's STABLE IDENTITY address (from the 0x15 exchange, persisted // in the bond) — that is what the real controller advertises on reconnect, and // what the console matches to recognise us and grant the fast 5 ms interval. Do - // NOT use bond_peer_val_ (the NimBLE connection address), which can be a + // NOT use bond_.peer_val (the NimBLE connection address), which can be a // rotating private address we cannot resolve without an SMP bond. // // Use the WAKE variant (0x81 flag = "user pressed a button, connect to me") @@ -606,11 +628,11 @@ bool Switch2Pro::advertise() { bool reconnect = false; std::array host_addr{}; { - // snapshot the mode and the address together (clear_bond resets both under - // this lock), then advertise without holding it + // snapshot the mode and the address together (every transition changes both + // under this lock), then advertise without holding it std::lock_guard lk(bond_mutex_); reconnect = reconnect_mode_; - host_addr = host_addr_; + host_addr = bond_.host_addr; } if (reconnect && (boot_wake_pending_ || wake_pending_)) return start_advertising(AdvMode::Wake, host_addr); @@ -623,16 +645,15 @@ bool Switch2Pro::wake_console() { if (active_conn_handle_ != 0xffff) return false; // already connected — nothing to wake // Require a real persisted bond. reconnect_mode_ is set only after a completed - // pairing (FINALISE) or a bond loaded from NVS. host_addr_ alone is not enough: - // it becomes nonzero mid-pairing (EXCHANGE_ADDRESSES), before any bond exists, so - // a failed pairing would otherwise let this emit a wake advertisement. + // pairing (FINALISE) or a bond loaded from NVS. static constexpr std::array kZeroAddr{}; + std::lock_guard adv_lk(adv_mutex_); bool reconnect = false; std::array host_addr{}; { std::lock_guard lk(bond_mutex_); reconnect = reconnect_mode_; - host_addr = host_addr_; + host_addr = bond_.host_addr; } if (!reconnect || host_addr == kZeroAddr) return false; // no bonded console to wake @@ -786,7 +807,7 @@ struct StoredBond { uint8_t magic; uint8_t peer_type; uint8_t peer_val[6]; // NimBLE peer_id_addr (wire/little-endian order) - uint8_t ltk[16]; // ltk_ (= A1 ^ B1), natural order + uint8_t ltk[16]; // the LTK (= A1 ^ B1), natural order uint8_t host_addr[6]; // console identity addr from 0x15/01 (embedded in reconnect adv) }; } // namespace @@ -1107,21 +1128,18 @@ bool Switch2Pro::send_input_report( return sent; } -bool Switch2Pro::inject_ltk(uint8_t peer_type, const uint8_t *peer_val_le) { +bool Switch2Pro::inject_ltk(const Bond &bond) { struct ble_store_value_sec sec = {}; - sec.peer_addr.type = peer_type; - std::copy(peer_val_le, peer_val_le + 6, sec.peer_addr.val); + sec.peer_addr.type = bond.peer_type; + std::copy(bond.peer_val.begin(), bond.peer_val.end(), sec.peer_addr.val); sec.key_size = 16; sec.ediv = 0; // no SMP key distribution — the console uses the LTK directly sec.rand_num = 0; // NimBLE hands ltk[] straight to the controller with no byte-swap, so it must - // be in the same order the console's controller uses: ltk_ (= A1 ^ B1) as + // be in the same order the console's controller uses: the LTK (= A1 ^ B1) as // computed. (The 0x03/0x07 "send pairing info" blob is this value reversed, // but that is just the on-wire transmission form, not the key order.) - { - std::lock_guard lk(bond_mutex_); - std::copy(ltk_.begin(), ltk_.end(), sec.ltk); - } + std::copy(bond.ltk.begin(), bond.ltk.end(), sec.ltk); sec.ltk_present = 1; sec.authenticated = 1; int rc = ble_store_write_our_sec(&sec); @@ -1137,47 +1155,28 @@ bool Switch2Pro::inject_ltk(uint8_t peer_type, const uint8_t *peer_val_le) { return true; } -bool Switch2Pro::inject_pairing_ltk() { - struct ble_gap_conn_desc desc; - if (active_conn_handle_ == 0xffff || ble_gap_conn_find(active_conn_handle_, &desc) != 0) { - logger_.warn("cannot inject LTK: no active connection"); - return false; - } - return inject_ltk(desc.peer_id_addr.type, desc.peer_id_addr.val); -} - -void Switch2Pro::save_bond() { - struct ble_gap_conn_desc desc; - if (active_conn_handle_ == 0xffff || ble_gap_conn_find(active_conn_handle_, &desc) != 0) - return; +bool Switch2Pro::save_bond(const Bond &bond) { StoredBond b{}; b.magic = kBondMagic; - b.peer_type = desc.peer_id_addr.type; - std::copy(std::begin(desc.peer_id_addr.val), std::end(desc.peer_id_addr.val), b.peer_val); - { - std::lock_guard lk(bond_mutex_); - std::copy(ltk_.begin(), ltk_.end(), b.ltk); - std::copy(host_addr_.begin(), host_addr_.end(), b.host_addr); - } + b.peer_type = bond.peer_type; + std::copy(bond.peer_val.begin(), bond.peer_val.end(), b.peer_val); + std::copy(bond.ltk.begin(), bond.ltk.end(), b.ltk); + std::copy(bond.host_addr.begin(), bond.host_addr.end(), b.host_addr); // Persist via the espp NVS component (set_var writes the blob and commits). std::vector blob(sizeof(b)); std::memcpy(blob.data(), &b, sizeof(b)); espp::Nvs nvs; std::error_code ec; nvs.set_var(kNvsNamespace, kNvsBondKey, blob, ec); - // Keep the bond in RAM regardless so this session can still reconnect/wake; only - // persistence across a reboot is lost if the write failed. - { - std::lock_guard lk(bond_mutex_); - bond_peer_type_ = b.peer_type; - std::copy(std::begin(b.peer_val), std::end(b.peer_val), bond_peer_val_.begin()); - } - if (ec) - logger_.error("save_bond: NVS write failed ({}) — bond kept in RAM for this boot, but " - "reconnect/wake after a reboot will not work", + if (ec) { + // The bond stays in RAM, so this boot can still reconnect/wake; only the + // NVS copy is stale (a previously stored bond, if any, returns on reboot). + logger_.error("save_bond: NVS write failed ({}) — the new bond holds for this boot only", ec.message()); - else - logger_.info("saved bond to NVS (console addr + LTK)"); + return false; + } + logger_.info("saved bond to NVS (console addr + LTK)"); + return true; } bool Switch2Pro::load_bond() { @@ -1192,13 +1191,34 @@ bool Switch2Pro::load_bond() { if (b.magic != kBondMagic) return false; std::lock_guard lk(bond_mutex_); - bond_peer_type_ = b.peer_type; - std::copy(std::begin(b.peer_val), std::end(b.peer_val), bond_peer_val_.begin()); - std::copy(std::begin(b.ltk), std::end(b.ltk), ltk_.begin()); - std::copy(std::begin(b.host_addr), std::end(b.host_addr), host_addr_.begin()); + bond_.peer_type = b.peer_type; + std::copy(std::begin(b.peer_val), std::end(b.peer_val), bond_.peer_val.begin()); + std::copy(std::begin(b.ltk), std::end(b.ltk), bond_.ltk.begin()); + std::copy(std::begin(b.host_addr), std::end(b.host_addr), bond_.host_addr.begin()); return true; } +void Switch2Pro::reset_bond_locked() { + reconnect_mode_ = false; + paired_ = false; + wake_pending_ = false; + boot_wake_pending_ = false; + bond_ = {}; +} + +bool Switch2Pro::unpair_peer(uint8_t peer_type, const std::array &peer_val) { + if (ble_gap_adv_active()) + ble_gatt_server_.stop_advertising(); + ble_addr_t peer{}; + peer.type = peer_type; + std::copy(peer_val.begin(), peer_val.end(), peer.val); + const int rc = ble_gap_unpair(&peer); + if (rc == 0 || rc == BLE_HS_ENOENT) // ENOENT = nothing stored for this peer + return true; + logger_.error("deleting a console's NimBLE security record failed (rc={})", rc); + return false; +} + bool Switch2Pro::clear_bond() { // Erase the persisted bond via the espp NVS component. A missing bond is success // (nothing to forget); only a real erase failure is reported. Check existence @@ -1236,86 +1256,57 @@ bool Switch2Pro::clear_bond() { } // Also delete the NimBLE security-store record for the injected LTK, so the old // peer's LL encryption key is not usable for the rest of this boot (a persisted - // NVS erase alone leaves the live key in place). Do this while the peer address is - // still in RAM, before it is zeroed below. - // A start_pairing() window keeps the previous console's record aside (the - // live fields are already in discovery mode): forget that one too. - std::vector peers; + // NVS erase alone leaves the live key in place). A start_pairing() window keeps + // the previous console's bond aside (the live bond is already in discovery + // mode): forget that one too. adv_mutex_ is held from the reset to the + // re-advertise, so no advertisement of the old bond can start in between and + // nothing restarts advertising while the records are deleted. + std::lock_guard adv_lk(adv_mutex_); + std::array peers{}; + size_t peer_count = 0; { std::lock_guard lk(bond_mutex_); - if (paired_ || reconnect_mode_) { - ble_addr_t peer{}; - peer.type = bond_peer_type_; - std::copy(bond_peer_val_.begin(), bond_peer_val_.end(), peer.val); - peers.push_back(peer); - } - if (kept_bond_.valid) { - ble_addr_t peer{}; - peer.type = kept_bond_.peer_type; - std::copy(kept_bond_.peer_val.begin(), kept_bond_.peer_val.end(), peer.val); - peers.push_back(peer); - } - kept_bond_ = {}; + if (paired_ || reconnect_mode_) + peers[peer_count++] = bond_; + if (kept_bond_) + peers[peer_count++] = *kept_bond_; + kept_bond_.reset(); pairing_ = false; + reset_bond_locked(); } - for (auto &peer : peers) { - int rc = ble_gap_unpair(&peer); - if (rc != 0 && rc != BLE_HS_ENOENT) { // ENOENT = nothing stored for this peer - logger_.error("clear_bond: failed to delete the NimBLE security record (rc={})", rc); + for (size_t i = 0; i < peer_count; ++i) { + if (!unpair_peer(peers[i].peer_type, peers[i].peer_val)) ok = false; - } - } - // Reset in-memory bond state back to fresh-pairing (discovery) mode. The mode - // flag and the identity are reset under one lock, so a concurrent advertise() - // sees either the old bond or none -- never a half-cleared address. - { - std::lock_guard lk(bond_mutex_); - reconnect_mode_ = false; - paired_ = false; - wake_pending_ = false; - boot_wake_pending_ = false; - bond_peer_type_ = 0; - bond_peer_val_ = {}; - host_addr_ = {}; - ltk_ = {}; } logger_.info("bond cleared — returning to fresh-pairing (discovery) mode"); // If nothing is connected, re-advertise now so we are discoverable for a fresh // pairing immediately (advertise() picks Discovery since reconnect_mode_ is off). if (active_conn_handle_ == 0xffff) - advertise(); + advertise_locked(); return ok; } bool Switch2Pro::start_pairing() { // Keep the current bond aside (only the first call of a window: a repeat keeps - // the ORIGINAL console, not the cleared discovery state), then reset the - // in-memory identity to fresh-pairing mode exactly like clear_bond() does - but - // leave NVS and NimBLE's security record alone, so cancel_pairing() (or a - // reboot) can go back to that console. + // the ORIGINAL console, not the cleared discovery state), then reset the live + // bond to fresh-pairing mode exactly like clear_bond() does - but leave NVS and + // NimBLE's security record alone, so cancel_pairing() (or a reboot) can go back + // to that console. A handshake already running on a live link keeps its own + // scratch state, so a repeat call does not disturb it. + std::lock_guard adv_lk(adv_mutex_); + bool opened = false; bool kept = false; { std::lock_guard lk(bond_mutex_); - if (!pairing_) { - kept_bond_ = {}; - if (reconnect_mode_ && paired_) { - kept_bond_.valid = true; - kept_bond_.peer_type = bond_peer_type_; - kept_bond_.peer_val = bond_peer_val_; - kept_bond_.host_addr = host_addr_; - kept_bond_.ltk = ltk_; - } + opened = !pairing_; + if (opened) { + kept_bond_.reset(); + if (reconnect_mode_ && paired_) + kept_bond_ = bond_; } pairing_ = true; - reconnect_mode_ = false; - paired_ = false; - wake_pending_ = false; - boot_wake_pending_ = false; - bond_peer_type_ = 0; - bond_peer_val_ = {}; - host_addr_ = {}; - ltk_ = {}; - kept = kept_bond_.valid; + reset_bond_locked(); + kept = kept_bond_.has_value(); } logger_.info("pairing: advertising for a new console ({} bond kept until one pairs)", kept ? "the current" : "no"); @@ -1325,40 +1316,54 @@ bool Switch2Pro::start_pairing() { readvertise_suppressed_ = false; if (active_conn_handle_ != 0xffff) return true; - return advertise(); // reconnect_mode_ is off: the discovery variant + if (advertise_locked()) // reconnect_mode_ is off: the discovery variant + return true; + // Nothing is on the air: do not leave a window open that the caller will not + // know to cancel. Put the previous bond back if this call opened the window. + if (opened) { + std::lock_guard lk(bond_mutex_); + if (kept_bond_) { + bond_ = *kept_bond_; + paired_ = true; + reconnect_mode_ = true; + } + kept_bond_.reset(); + pairing_ = false; + } + logger_.error("pairing: discovery advertising failed to start - pairing window not opened"); + return false; } bool Switch2Pro::cancel_pairing() { - if (!pairing_) - return false; - KeptBond kept{}; + std::lock_guard adv_lk(adv_mutex_); + std::optional kept; { std::lock_guard lk(bond_mutex_); + if (!pairing_) + return false; pairing_ = false; - pairing_stage_ = 0; // abandon a half-done handshake: its FINALISE is rejected - kept = kept_bond_; - kept_bond_ = {}; - if (kept.valid) { - bond_peer_type_ = kept.peer_type; - bond_peer_val_ = kept.peer_val; - host_addr_ = kept.host_addr; - ltk_ = kept.ltk; + // Abandon a half-done handshake on a live link: its remaining steps and its + // FINALISE are rejected until the console reconnects. + pairing_stage_ = 0; + handshake_closed_ = true; + kept = std::exchange(kept_bond_, std::nullopt); + if (kept) { + bond_ = *kept; paired_ = true; reconnect_mode_ = true; } } - if (!kept.valid) { + if (!kept) { logger_.info("pairing: window ended with no new console and no previous bond"); return false; } - // The record was never deleted, but a handshake that reached FINALISE's LTK - // injection for another peer may have shared the store; re-inject to be sure - // the restored console can encrypt straight away. - if (!inject_ltk(kept.peer_type, kept.peer_val.data())) + // The record was never deleted, but re-inject it so the restored console can + // encrypt straight away whatever the store went through during the window. + if (!inject_ltk(*kept)) logger_.error("pairing: re-injecting the previous console's LTK failed"); logger_.info("pairing: window ended with no new console - back to the previous one"); if (active_conn_handle_ == 0xffff && !readvertise_suppressed_) - advertise(); // reconnect_mode_ is back on: the reconnect variant + advertise_locked(); // reconnect_mode_ is back on: the reconnect variant return true; } @@ -1407,6 +1412,9 @@ void Switch2Pro::stop_advertising() { boot_wake_pending_ = false; if (wake_timer_) wake_timer_->stop(); + // After the join (never hold adv_mutex_ while joining the wake timer, whose + // tick takes it): waits out an advertise() already choosing a variant. + std::lock_guard lk(adv_mutex_); ble_gatt_server_.stop_advertising(); } @@ -1428,16 +1436,16 @@ std::optional Switch2Pro::bonded_console_address() const { std::lock_guard lk(bond_mutex_); if (!paired_.load()) return std::nullopt; - // Return the console's STABLE IDENTITY (host_addr_, from the 0x15 exchange and - // persisted in the bond) — the value the component itself trusts for reconnect - // (see advertise()), set during the handshake before paired_ flips. NOT - // bond_peer_val_, which is the NimBLE connection address and can be a rotating - // private address (this component does no SMP resolution). The identity is - // matched at the application layer, so its address type is not tracked; report - // it as public. host_addr_ is little-endian wire order, as ble_addr_t.val wants. + // Return the console's STABLE IDENTITY (bond_.host_addr, from the 0x15 exchange + // and persisted in the bond) — the value the component itself trusts for + // reconnect (see advertise()). NOT bond_.peer_val, which is the NimBLE + // connection address and can be a rotating private address (this component + // does no SMP resolution). The identity is matched at the application layer, + // so its address type is not tracked; report it as public. It is little-endian + // wire order, as ble_addr_t.val wants. ble_addr_t a{}; a.type = BLE_ADDR_PUBLIC; - std::copy(host_addr_.begin(), host_addr_.end(), a.val); + std::copy(bond_.host_addr.begin(), bond_.host_addr.end(), a.val); return NimBLEAddress(a); } @@ -1458,18 +1466,29 @@ void Switch2Pro::handle_pairing(bool via_vibration_command, uint8_t transport, P // A malformed request cannot start a handshake that could ever complete: // reject it without the success reply (like FINALISE below) so the console // does not carry on, and restart the sequence. - if (len < 8) { - logger_.warn("pairing: exchange-addresses rejected — payload too short ({} bytes)", len); - pairing_stage_ = 0; - break; - } + // The identity goes into the handshake scratch; only FINALISE commits it. std::array host_addr{}; - std::copy(payload + 2, payload + 8, host_addr.begin()); + bool closed = false; { std::lock_guard lk(bond_mutex_); - host_addr_ = host_addr; + closed = handshake_closed_; + if (len >= 8 && !closed) { + std::copy(payload + 2, payload + 8, host_addr.begin()); + pending_host_addr_ = host_addr; + pairing_stage_ = 1; + } else { + pairing_stage_ = 0; + } + } + if (closed) { + logger_.warn("pairing: exchange-addresses rejected — the pairing window was cancelled on " + "this connection"); + break; + } + if (len < 8) { + logger_.warn("pairing: exchange-addresses rejected — payload too short ({} bytes)", len); + break; } - pairing_stage_ = 1; logger_.info("pairing: stored console identity addr {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", host_addr[5], host_addr[4], host_addr[3], host_addr[2], host_addr[1], host_addr[0]); @@ -1487,20 +1506,30 @@ void Switch2Pro::handle_pairing(bool via_vibration_command, uint8_t transport, P } case PairingSub::EXCHANGE_KEYS: { // Request data is [0x00][A1 (16 bytes)] — skip the leading 0x00. - if (pairing_stage_ < 1 || len < 17) { - logger_.warn("pairing: exchange-keys rejected — out of order or short (stage={}, len={})", - pairing_stage_, len); - pairing_stage_ = 0; - break; - } - { + std::array ltk{}; + if (len >= 17) { std::array a1{}; std::copy(payload + 1, payload + 17, a1.begin()); - const auto ltk = PairingCrypto::derive_ltk(a1); + ltk = PairingCrypto::derive_ltk(a1); + } + uint8_t stage = 0; + bool accepted = false; + { std::lock_guard lk(bond_mutex_); - ltk_ = ltk; + stage = pairing_stage_; + accepted = stage >= 1 && len >= 17 && !handshake_closed_; + if (accepted) { + pending_ltk_ = ltk; + pairing_stage_ = 2; + } else { + pairing_stage_ = 0; + } + } + if (!accepted) { + logger_.warn("pairing: exchange-keys rejected — out of order or short (stage={}, len={})", + stage, len); + break; } - pairing_stage_ = 2; // Reply: {0x01} + fixed controller key B1. std::array reply{0x01}; std::copy(CONTROLLER_KEY_B1.begin(), CONTROLLER_KEY_B1.end(), reply.begin() + 1); @@ -1511,21 +1540,28 @@ void Switch2Pro::handle_pairing(bool via_vibration_command, uint8_t transport, P } case PairingSub::CONFIRM_LTK: { // Request data is [0x00][A2 challenge (16 bytes)] — skip the leading 0x00. - if (pairing_stage_ < 2 || len < 17) { - logger_.warn("pairing: confirm rejected — out of order or short (stage={}, len={})", - pairing_stage_, len); - pairing_stage_ = 0; - break; - } - std::array a2{}; - std::copy(payload + 1, payload + 17, a2.begin()); std::array ltk{}; + uint8_t stage = 0; + bool accepted = false; { std::lock_guard lk(bond_mutex_); - ltk = ltk_; + stage = pairing_stage_; + accepted = stage >= 2 && len >= 17 && !handshake_closed_; + if (accepted) { + ltk = pending_ltk_; + pairing_stage_ = 3; + } else { + pairing_stage_ = 0; + } } + if (!accepted) { + logger_.warn("pairing: confirm rejected — out of order or short (stage={}, len={})", stage, + len); + break; + } + std::array a2{}; + std::copy(payload + 1, payload + 17, a2.begin()); const std::array b2 = PairingCrypto::confirm(ltk, a2); - pairing_stage_ = 3; // Reply: {0x01} + B2 = AES-128-ECB(rev(LTK), rev(A2)). std::array reply{0x01}; std::copy(b2.begin(), b2.end(), reply.begin() + 1); @@ -1539,48 +1575,72 @@ void Switch2Pro::handle_pairing(bool via_vibration_command, uint8_t transport, P // completed in order (stage 3). Otherwise an out-of-order/malformed peer could // mark us paired and persist an all-zero/partial bond, sending future boots // into reconnect mode with a useless bond. Reject without replying/persisting. - if (pairing_stage_ < 3) { - logger_.warn("pairing: FINALISE rejected — handshake incomplete (stage={})", pairing_stage_); + // The bond is keyed by the connected console's identity address, so there + // must be a live link to read it from. + struct ble_gap_conn_desc desc {}; + const bool have_link = + active_conn_handle_ != 0xffff && ble_gap_conn_find(active_conn_handle_, &desc) == 0; + // Check the handshake and commit its result in ONE hold of bond_mutex_, so a + // concurrent start_pairing() / cancel_pairing() / clear_bond() lands wholly + // before (and rejects or restarts it) or after (and sees the new bond). + Bond bond; + std::optional replaced; + bool closed_window = false; + uint8_t stage = 0; + bool closed = false; + { + std::lock_guard lk(bond_mutex_); + stage = pairing_stage_; + closed = handshake_closed_; + if (stage >= 3 && !closed && have_link) { + bond.peer_type = desc.peer_id_addr.type; + std::copy(std::begin(desc.peer_id_addr.val), std::end(desc.peer_id_addr.val), + bond.peer_val.begin()); + bond.host_addr = pending_host_addr_; + bond.ltk = pending_ltk_; + bond_ = bond; + paired_ = true; + reconnect_mode_ = true; + closed_window = pairing_.exchange(false); + replaced = std::exchange(kept_bond_, std::nullopt); + } + } + if (stage < 3 || closed || !have_link) { + logger_.warn("pairing: FINALISE rejected — handshake incomplete or abandoned (stage={}, " + "cancelled={}, link={})", + stage, closed, have_link); break; } static constexpr std::array reply{0x01}; send_response(via_vibration_command, 0x15, transport, 0x03, 0x10, 0x78, reply.data(), reply.size()); - paired_ = true; logger_.info("pairing: finalised — bonded"); // Right after finalise the console starts standard BLE link-layer encryption // using the LTK we just negotiated (there is no SMP key distribution). Inject // the LTK into NimBLE's security store so the controller can answer the // console's LTK request; without it encryption fails and the console drops us. - if (!inject_pairing_ltk()) + if (!inject_ltk(bond)) logger_.error("pairing: LTK injection failed — the console's encryption request will " "fail and it will drop the link; re-pair to retry"); // Persist {console address, LTK} so we can reconnect/wake after a reboot // without re-running the pairing exchange. - save_bond(); - reconnect_mode_ = true; - // A start_pairing() window is complete: the new bond replaced the kept one. - // Drop the previous console's NimBLE key record unless it was this console - // pairing again (same address: the injection above already overwrote it). - if (pairing_.exchange(false)) { - ble_addr_t old_peer{}; - bool drop_old = false; - { - std::lock_guard lk(bond_mutex_); - if (kept_bond_.valid && - (kept_bond_.peer_type != bond_peer_type_ || kept_bond_.peer_val != bond_peer_val_)) { - drop_old = true; - old_peer.type = kept_bond_.peer_type; - std::copy(kept_bond_.peer_val.begin(), kept_bond_.peer_val.end(), old_peer.val); - } - kept_bond_ = {}; - } - if (drop_old) { - const int rc = ble_gap_unpair(&old_peer); - if (rc != 0 && rc != BLE_HS_ENOENT) - logger_.warn("pairing: dropping the previous console's key record failed (rc={})", rc); + const bool persisted = save_bond(bond); + // A start_pairing() window is complete. If another console's bond was kept + // aside, drop its NimBLE key record - but only once NVS holds the new bond: + // otherwise NVS still holds the previous console and a reboot returns to it, + // so its key must stay. (The same console pairing again needs nothing: the + // injection above overwrote its record.) + if (replaced && !replaced->same_peer(bond)) { + if (persisted) { + std::lock_guard adv_lk(adv_mutex_); + if (unpair_peer(replaced->peer_type, replaced->peer_val)) + logger_.info("pairing: the new console replaced the previous one"); + } else { + logger_.warn("pairing: the new bond is not persisted; NVS still holds the previous " + "console, which a reboot returns to, so its key record is kept"); } - logger_.info("pairing: the new console replaced the previous bond"); + } else if (closed_window) { + logger_.info("pairing: window closed by a completed pairing"); } if (callbacks_.on_paired) callbacks_.on_paired();