diff --git a/CHANGELOG.md b/CHANGELOG.md index 777bfbaf..67ba8838 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## Unreleased +* Windows: connecting to a device whose GATT database holds a service Windows reserves for itself — HID over GATT, `0x1812` — no longer fails. Windows answers `GetCharacteristicsAsync` with `AccessDenied` for it whether or not the device is paired, and since 2.2.0 that error ended the connection attempt during discovery. A denied service is now left out: its characteristics are not reported by `discoverServices`, the rest of the database connects normally, and a GATT service refresh skips it instead of keeping the previous map. A denied service that discovery already reported is the exception — the refresh keeps the previous services then, so reads and subscriptions on it do not silently disappear. A device whose every service was denied still connects, reports no services, and logs a warning. `Unreachable` and `ProtocolError` still fail the connection, so a discovery cut short by a link drop is still reported (#400). + ## 3.4.1 * Android: a `setNotifiable` call whose CCCD write throws now fails with a classified error instead of being left pending. The old code withdrew the pending result twice — once in the inner handler and again in the outer one — so the second withdrawal found nothing to fail and the Dart call hung until its timeout. The CCCD write is now one helper, and the request is withdrawn once before its single reply. * Linux: a read, write, descriptor read/write or subscription submitted while the device is disconnected now fails with `deviceDisconnected` instead of `characteristicNotFound` or a generic `readFailed`/`writeFailed`. BlueZ drops the GATT object tree together with the link, so the lookup used to report the characteristic as unknown — as if the device had changed its services — and a request that reached D-Bus failed with `NotConnected` under a generic code (#394). diff --git a/README.md b/README.md index 6ca71364..7568280b 100644 --- a/README.md +++ b/README.md @@ -458,6 +458,8 @@ If you don't call this method then it will be automatically called when you try Discovers the services offered by the device. Returns a `Future>`. After discovery services are cached and each call of this method updates the cache. +On Windows, a service Windows denies access to is left out of discovery. The OS reserves some services for itself — HID over GATT, `00001812-0000-1000-8000-00805f9b34fb`, is the common one — and answers `AccessDenied` when an app asks for their characteristics, paired or not, so those services are skipped instead of failing the connection. Their characteristics cannot be reached through this plugin. A service an earlier discovery reported stays reported if a later GATT refresh is denied access to it, rather than disappearing from the connection. + ```dart List services = await bleDevice.discoverServices(); for (var service in services) { diff --git a/hil/COVERAGE.md b/hil/COVERAGE.md index 030548ef..0b7e31d3 100644 --- a/hil/COVERAGE.md +++ b/hil/COVERAGE.md @@ -1,7 +1,7 @@ # Hardware-in-the-loop coverage -The Windows HIL suite implements 85 tests against a physical nRF52 peripheral: -25 baseline tests and 60 fault injection tests (FIT). Skipped scenarios are not +The Windows HIL suite implements 86 tests against a physical nRF52 peripheral: +26 baseline tests and 60 fault injection tests (FIT). Skipped scenarios are not included in these counts. Firmware contract revision 2 (v2) is required. The calls start at the public Dart API and go through the operation queue, @@ -43,13 +43,19 @@ and finally the Zephyr GATT server on the fixture. - This catches incomplete cleanup, bad replacement ownership, missing events, and GATT state that no longer works after reconnecting. -### 1.5. Concurrency, refresh, and platform results (6 tests) +### 1.5. Concurrency, refresh, and platform results (7 tests) - Verifies recovery from overlapping subscriptions, a valid MTU result, and `notImplemented` for Windows RSSI without disconnecting. It also verifies that system-device enumeration, client capability queries, connection priority handling, and ordinary service changes leave the active connection readable and writable. +- Verifies that a database holding a service Windows reserves for itself (HID + over GATT, `0x1812`) still connects, that discovery leaves the reserved + service out, and that a later service change is still installed on top of it. + This catches an `AccessDenied` answer being treated as a fatal discovery + error, and a service refresh that keeps the old map when it meets a denied + service that discovery never reported (#400). - This catches subscription races, invalid MTU completion, incorrect error mapping, and operations that damage an otherwise usable connection. diff --git a/hil/README.md b/hil/README.md index 466946b3..1ed11af8 100644 --- a/hil/README.md +++ b/hil/README.md @@ -9,9 +9,9 @@ repository. Test commands go over BLE. USB serial is only used for Zephyr logs. ## 1. Current coverage -The Windows suite contains 85 implemented hardware tests: +The Windows suite contains 86 implemented hardware tests: -- 25 baseline tests for ordinary BLE behavior; +- 26 baseline tests for ordinary BLE behavior; - 60 fault injection tests for hostile peripheral behavior, timing, and lifecycle races. diff --git a/hil/integration_test/baseline_hil_test.dart b/hil/integration_test/baseline_hil_test.dart index d4d2d081..73b94403 100644 --- a/hil/integration_test/baseline_hil_test.dart +++ b/hil/integration_test/baseline_hil_test.dart @@ -555,6 +555,94 @@ void main() { }, ); + testWidgets( + 'connects and refreshes while the database holds an OS-reserved service', + (_) async { + // Windows reserves HID over GATT (0x1812) for its own driver and + // answers GetCharacteristicsAsync with AccessDenied for it whether or + // not the device is paired, so the fixture adds that service on + // request. Discovery must skip it instead of failing the connection + // (#400). + await peripheral.setHidService(enabled: true); + try { + // The fixture registers the service 25 ms after the write, which + // raises Service Changed. Give that refresh time to run against the + // reserved service before the connection is replaced. + await Future.delayed(const Duration(seconds: 1)); + + // Connect-time discovery meets AccessDenied on the reserved service. + // Before the fix the connect failed with "Failed to get + // characteristics for service 00001812-...". + await UniversalBle.disconnect( + peripheral.deviceId, + timeout: HilPeripheral.operationTimeout, + ); + await peripheral.reconnect(); + + expect( + await UniversalBle.getConnectionState(peripheral.deviceId), + BleConnectionState.connected, + ); + final services = await peripheral.discover(withDescriptors: false); + // A fixture that failed to register the HID service would also leave + // 0x1812 absent here, and it reports that only on its own UART. This + // assertion therefore says the OS denies the service, not that the + // fixture registered it. + expect( + services.map((service) => service.uuid), + isNot(contains(BleUuidParser.string('1812'))), + reason: 'Windows denies app access to the reserved HID service; ' + 'if it is listed, the OS no longer reserves 0x1812 and the ' + 'fixture no longer reproduces #400', + ); + expect( + services.map((service) => service.uuid), + contains(BleUuidParser.string(HilUuid.service)), + ); + expect( + utf8.decode(await peripheral.read(HilUuid.read)), 'HIL-READ-V1'); + + // A later, ordinary change must still be installed while the + // reserved service is in the database: that proves the refresh + // walked past it instead of keeping the old map. + await peripheral.setAuxiliaryService(enabled: true); + await _eventually( + () async => (await peripheral.discover()).any( + (service) => BleUuidParser.compareStrings( + service.uuid, + HilUuid.auxiliaryService, + ), + ), + ); + expect( + (await peripheral.discover(withDescriptors: false)) + .map((service) => service.uuid), + isNot(contains(BleUuidParser.string('1812'))), + ); + expect( + utf8.decode(await peripheral.read(HilUuid.read)), 'HIL-READ-V1'); + } finally { + // The fixture's reset clears the request flags without unregistering + // either service, so remove them while the link is still up. Each + // disable stands alone: a failed reconnect above leaves no link, and + // the first failure must not skip the other service. + try { + await peripheral.setAuxiliaryService(enabled: false); + } catch (_) { + // Without a link the auxiliary service stays registered; reset() + // only clears the flag that asked for it. + } + try { + await peripheral.setHidService(enabled: false); + } catch (_) { + // Same as above for the HID service. + } + } + }, + skip: defaultTargetPlatform != TargetPlatform.windows, + timeout: const Timeout(Duration(minutes: 2)), + ); + testWidgets( 'reports that connected RSSI reads are unsupported on Windows', (_) async { diff --git a/hil/lib/src/hil_peripheral.dart b/hil/lib/src/hil_peripheral.dart index c4b97cad..7c4cd54b 100644 --- a/hil/lib/src/hil_peripheral.dart +++ b/hil/lib/src/hil_peripheral.dart @@ -45,6 +45,7 @@ abstract final class HilCommand { static const notifyPressure = 0x14; static const armConnectFault = 0x15; static const armDiscoveryFault = 0x16; + static const setHidService = 0x17; } final class HilTelemetry { @@ -352,6 +353,13 @@ final class HilPeripheral { Future setAuxiliaryService({required bool enabled}) => command(HilCommand.setAuxiliaryService, [enabled ? 1 : 0]); + /// Adds or removes the fixture's minimal HID over GATT service (0x1812). + /// Windows reserves that service for its own driver and denies app access to + /// its characteristics, so it exercises how a host treats a restricted + /// service. + Future setHidService({required bool enabled}) => + command(HilCommand.setHidService, [enabled ? 1 : 0]); + Future scheduleAuxiliaryService({ required bool enabled, required Duration delay, diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index 0bbc675b..0d1f88d4 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -56,6 +56,7 @@ list(APPEND PLUGIN_SOURCES "src/universal_ble_filter_util.h" "src/universal_ble_thread_safe.h" "src/enum_parser.h" + "src/gatt_discovery_policy.h" "src/helper/universal_ble_logger.cpp" "src/helper/universal_ble_logger.h" ) diff --git a/windows/src/gatt_discovery_policy.h b/windows/src/gatt_discovery_policy.h new file mode 100644 index 00000000..4c1ef221 --- /dev/null +++ b/windows/src/gatt_discovery_policy.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace universal_ble { + +// What discovery does with one service once GetCharacteristicsAsync returned. +enum class GattDiscoveryAction { + // The characteristics came back; add the service and its characteristics to + // the service map. + kInclude, + // Windows denies app access to a few GATT services it reserves for itself - + // HID over GATT (0x1812) is the common one - and answers + // GetCharacteristicsAsync with AccessDenied for them whether or not the + // device is paired. The service is unusable to an app, but the rest of the + // database is not, so it is left out instead of failing the connection + // (#400). + kSkipDenied, + // Any other failure ends discovery, so a query a dropped link cut short is + // still reported (#284). + kFail, +}; + +inline GattDiscoveryAction classify_discovery_status( + const winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: + GattCommunicationStatus status) noexcept { + using winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: + GattCommunicationStatus; + if (status == GattCommunicationStatus::Success) { + return GattDiscoveryAction::kInclude; + } + if (status == GattCommunicationStatus::AccessDenied) { + return GattDiscoveryAction::kSkipDenied; + } + return GattDiscoveryAction::kFail; +} + +} // namespace universal_ble diff --git a/windows/src/universal_ble_plugin.cpp b/windows/src/universal_ble_plugin.cpp index 3d07b95a..aaa8d4a5 100644 --- a/windows/src/universal_ble_plugin.cpp +++ b/windows/src/universal_ble_plugin.cpp @@ -18,6 +18,7 @@ #include "advertisement_uuid.h" #include "enum_parser.h" #include "callback_drain.h" +#include "gatt_discovery_policy.h" #include "generated/universal_ble.g.h" #include "helper/universal_ble_logger.h" #include "helper/universal_enum.h" @@ -2141,6 +2142,7 @@ fire_and_forget UniversalBlePlugin::ConnectAsync(uint64_t bluetooth_address, UniversalBleLogger::LogInfo("ConnectionLog: Services discovered"); std::optional gatt_discovery_error; + size_t denied_service_count = 0; auto gatt_services = services_result.Services(); for (GattDeviceService &&service : gatt_services) { try { @@ -2149,6 +2151,13 @@ fire_and_forget UniversalBlePlugin::ConnectAsync(uint64_t bluetooth_address, std::string service_uuid = guid_to_uuid(service.Uuid()); auto characteristics_result = co_await service.GetCharacteristicsAsync( BluetoothCacheMode::Uncached); + if (classify_discovery_status(characteristics_result.Status()) == + GattDiscoveryAction::kSkipDenied) { + ++denied_service_count; + UniversalBleLogger::LogInfo("Skipping denied service " + + service_uuid); + continue; + } auto characteristics_result_error = gatt_communication_status_to_error(characteristics_result.Status()); @@ -2196,6 +2205,16 @@ fire_and_forget UniversalBlePlugin::ConnectAsync(uint64_t bluetooth_address, co_return; } + if (denied_service_count > 0 && gatt_map.empty()) { + // AccessDenied is not exclusive to OS-reserved services. If the whole + // database was denied, the connection is up but exposes nothing, and the + // per-service info lines are the only trace of why. + UniversalBleLogger::LogWarning( + "All " + std::to_string(denied_service_count) + + " discovered services were denied access; the connection exposes no " + "services"); + } + const auto connection_callback_operations = callback_operations_; connection_status_changed_token = device.ConnectionStatusChanged( [this, connection_callback_operations](const BluetoothLEDevice &sender, @@ -2315,6 +2334,23 @@ fire_and_forget UniversalBlePlugin::RefreshGattServicesAsync( const auto characteristics_result = co_await service.GetCharacteristicsAsync( BluetoothCacheMode::Cached); + if (classify_discovery_status(characteristics_result.Status()) == + GattDiscoveryAction::kSkipDenied) { + // A denied service the map already exposes is in use: its + // characteristics, reads and subscriptions are live. Dropping it + // would silently break them, so the previous map is kept instead of + // installing a partial one. A service discovery never reported is + // skipped the same way as at connect time. + if (device_agent->HasService(service_uuid)) { + discovery_error = + "Failed to refresh characteristics for service " + + service_uuid + ": AccessDenied"; + break; + } + UniversalBleLogger::LogInfo("Skipping denied service " + + service_uuid); + continue; + } const auto characteristics_error = gatt_communication_status_to_error( characteristics_result.Status()); if (characteristics_error.has_value()) { diff --git a/windows/src/universal_ble_plugin.h b/windows/src/universal_ble_plugin.h index c916ded8..ab42924d 100644 --- a/windows/src/universal_ble_plugin.h +++ b/windows/src/universal_ble_plugin.h @@ -179,6 +179,14 @@ struct BluetoothDeviceAgent { return services; } + // Whether the current service map exposes a service. A GATT refresh uses this + // to keep a denied service the connection was already using instead of + // dropping it from the replacement map. + bool HasService(const std::string &service_uuid) const { + std::lock_guard lock(gatt_mutex); + return gatt_map.find(service_uuid) != gatt_map.end(); + } + GattMapLease SnapshotGattMapForOperation() { std::lock_guard lock(gatt_mutex); if (!IsActive()) { diff --git a/windows/test/CMakeLists.txt b/windows/test/CMakeLists.txt index 0fc4a219..1ac4ad41 100644 --- a/windows/test/CMakeLists.txt +++ b/windows/test/CMakeLists.txt @@ -94,4 +94,13 @@ if(WIN32) endif() add_test(NAME initialization_lifetime_test COMMAND initialization_lifetime_test) set_tests_properties(initialization_lifetime_test PROPERTIES TIMEOUT 10) + + # Covers the GATT status policy discovery uses: Windows denies access to some + # services (it reserves HID over GATT, 0x1812, for itself), so AccessDenied is + # skipped while every other status still ends discovery (#400). + add_executable(gatt_discovery_policy_test gatt_discovery_policy_test.cpp) + target_compile_features(gatt_discovery_policy_test PRIVATE cxx_std_20) + target_include_directories(gatt_discovery_policy_test PRIVATE ../src) + target_link_libraries(gatt_discovery_policy_test PRIVATE windowsapp) + add_test(NAME gatt_discovery_policy_test COMMAND gatt_discovery_policy_test) endif() diff --git a/windows/test/gatt_discovery_policy_test.cpp b/windows/test/gatt_discovery_policy_test.cpp new file mode 100644 index 00000000..460b6f68 --- /dev/null +++ b/windows/test/gatt_discovery_policy_test.cpp @@ -0,0 +1,56 @@ +// Covers the GATT status policy discovery uses. Windows denies app access to a +// few services it reserves for itself (HID over GATT, 0x1812, is the common +// one) and answers GetCharacteristicsAsync with AccessDenied for them, so that +// single status is skipped. Every other status, including one this policy has +// never seen, still ends discovery. The loops that consume the classification +// are covered by the Windows HIL suite, which needs a physical device and does +// not run in CI: see windows/src/gatt_discovery_policy.h and +// hil/integration_test/baseline_hil_test.dart. +#include +#include + +#include "gatt_discovery_policy.h" + +namespace { + +using Status = + winrt::Windows::Devices::Bluetooth::GenericAttributeProfile:: + GattCommunicationStatus; +using universal_ble::classify_discovery_status; +using universal_ble::GattDiscoveryAction; + +int Failures = 0; + +void Expect(bool condition, const std::string &what) { + if (!condition) { + std::cerr << "FAILED: " << what << "\n"; + Failures++; + } +} + +} // namespace + +int main() { + Expect(classify_discovery_status(Status::Success) == + GattDiscoveryAction::kInclude, + "Success includes the service"); + Expect(classify_discovery_status(Status::AccessDenied) == + GattDiscoveryAction::kSkipDenied, + "AccessDenied names a service the OS denies to apps"); + Expect(classify_discovery_status(Status::Unreachable) == + GattDiscoveryAction::kFail, + "Unreachable still fails discovery"); + Expect(classify_discovery_status(Status::ProtocolError) == + GattDiscoveryAction::kFail, + "ProtocolError still fails discovery"); + Expect(classify_discovery_status(static_cast(99)) == + GattDiscoveryAction::kFail, + "An unknown status fails discovery instead of being skipped"); + + if (Failures != 0) { + std::cerr << Failures << " check(s) failed\n"; + return 1; + } + std::cout << "gatt_discovery_policy_test passed\n"; + return 0; +}