diff --git a/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs b/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs index 28dd219..4257a00 100644 --- a/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs +++ b/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs @@ -69,7 +69,7 @@ protected async Task ReadNativeAsync(CancellationToken cancellationToken if (args.Status != GattStatus.Success) { - reject(new CharacteristicReadException($"Read characteristic {Id} failed with GATT status {args.Status}.", Id, Service.Id, (int)args.Status)); + reject(new CharacteristicReadException($"Read characteristic {Id} failed with GATT status {args.Status}.", Id, Service.Id, (int)args.Status, (int)args.Status)); return; } @@ -113,7 +113,7 @@ await TaskBuilder.FromEvent> GetDescriptorsNativeAsync(Cancellation if (args.Error != null) { - reject(new CharacteristicReadException($"Discover descriptors error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code)); + reject(new CharacteristicReadException($"Discover descriptors error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus())); } else { @@ -140,7 +140,7 @@ protected Task ReadNativeAsync(CancellationToken cancellationToken) if (args.Error != null) { - reject(new CharacteristicReadException($"Read async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code)); + reject(new CharacteristicReadException($"Read async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus())); } else { @@ -190,7 +190,7 @@ await TaskBuilder.FromEvent, Event return; if (args.Error != null) - reject(new CharacteristicWriteException($"Write async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code)); + reject(new CharacteristicWriteException($"Write async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus())); else complete(true); }, @@ -295,7 +295,7 @@ protected Task StartUpdatesNativeAsync(CharacteristicUpdateMode mode, Cancellati if (args.Error != null) { - reject(new CharacteristicReadException($"Start Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code)); + reject(new CharacteristicReadException($"Start Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus())); } else { @@ -338,7 +338,7 @@ protected Task StopUpdatesNativeAsync(CancellationToken cancellationToken) if (args.Error != null) { - reject(new CharacteristicReadException($"Stop Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code)); + reject(new CharacteristicReadException($"Stop Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus())); } else { diff --git a/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs index c8065db..4a901d1 100644 --- a/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs @@ -122,6 +122,7 @@ private void ThrowIfWriteFailed(GattWriteResult result) $"Write characteristic {Id} failed with status {result.Status}{detail}.", Id, Service.Id, + result.ProtocolError, result.ProtocolError); } diff --git a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj index 463afd9..ed4d996 100644 --- a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj +++ b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj @@ -58,6 +58,10 @@ Device.CreateBondAsync and Device.RemoveBondAsync request and remove a bond on Android; removal is best effort, through a hidden platform method, and reports false where Android refuses it. Both return false on Apple platforms and Windows. + CharacteristicReadException, CharacteristicWriteException, DescriptorReadException and + DescriptorWriteException carry the GATT status in GattStatus, classified as GattFailure, so an app can + recognise Insufficient Authentication (0x05) and Insufficient Encryption (0x0F) on Android, Apple + platforms and Windows. All four implement IGattStatusException. NativeStatus and messages are unchanged. 4.0.1 - restores the stand-in seam that 4.0 removed. Device and Service can again be derived outside the library: protected Device(Guid id, string name, int rssi = 0) replaces the parameterless diff --git a/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs b/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs index 7fda782..d43a758 100644 --- a/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs +++ b/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs @@ -36,7 +36,7 @@ protected Task WriteNativeAsync(byte[] data, CancellationToken cancellationToken return; if (args.Exception != null) - reject(new DescriptorWriteException($"Write descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status)); + reject(new DescriptorWriteException($"Write descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status, (int)args.Status)); else complete(true); }), @@ -71,7 +71,7 @@ protected async Task ReadNativeAsync(CancellationToken cancellationToken if (args.Exception != null) { - reject(new DescriptorReadException($"Read descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status)); + reject(new DescriptorReadException($"Read descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status, (int)args.Status)); return; } diff --git a/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs b/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs index c9bfe84..92a1cfe 100644 --- a/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs +++ b/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs @@ -1,9 +1,10 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; using CoreBluetooth; using System.BluetoothLe; using Foundation; +using System.BluetoothLe.Extensions; using System.BluetoothLe.Utils; namespace System.BluetoothLe @@ -66,7 +67,7 @@ protected Task ReadNativeAsync(CancellationToken cancellationToken) return; if (args.Error != null) - reject(new DescriptorReadException($"Read descriptor async error: {args.Error.Description}", Id, (int)args.Error.Code)); + reject(new DescriptorReadException($"Read descriptor async error: {args.Error.Description}", Id, (int)args.Error.Code, args.Error.GetAttStatus())); else complete(Value); }, @@ -102,7 +103,7 @@ protected Task WriteNativeAsync(byte[] data, CancellationToken cancellationToken return; if (args.Error != null) - reject(new DescriptorWriteException(args.Error.Description, Id, (int)args.Error.Code)); + reject(new DescriptorWriteException(args.Error.Description, Id, (int)args.Error.Code, args.Error.GetAttStatus())); else complete(true); }, diff --git a/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs index a89460d..ed1a64e 100644 --- a/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs @@ -38,6 +38,7 @@ protected async Task ReadNativeAsync(CancellationToken cancellationToken throw new DescriptorReadException( $"Read descriptor {Id} failed with status {readResult.Status}{ProtocolErrorDetail(readResult.ProtocolError)}.", Id, + readResult.ProtocolError, readResult.ProtocolError); } @@ -55,6 +56,7 @@ protected async Task WriteNativeAsync(byte[] data, CancellationToken cancellatio throw new DescriptorWriteException( $"Write descriptor {Id} failed with status {result.Status}{ProtocolErrorDetail(result.ProtocolError)}.", Id, + result.ProtocolError, result.ProtocolError); } } diff --git a/DSoft.System.BluetoothLe/Enums/GattFailure.shared.cs b/DSoft.System.BluetoothLe/Enums/GattFailure.shared.cs new file mode 100644 index 0000000..8be1bc7 --- /dev/null +++ b/DSoft.System.BluetoothLe/Enums/GattFailure.shared.cs @@ -0,0 +1,80 @@ +namespace System.BluetoothLe +{ + /// + /// What a failed GATT operation's status says went wrong, for the statuses an app needs to act on. + /// + /// + /// The raw code is on . The security failures matter most: a + /// peripheral that requires a bonded, encrypted link answers an unbonded central with one of them, and the + /// app should ask the user to pair - or to forget the device and pair again, if the peripheral has lost its + /// keys - rather than report a generic fault. + /// + public enum GattFailure + { + /// + /// No GATT status was reported: the operation could not be started, the device disconnected, or the + /// platform failed it for a reason of its own. + /// + None, + + /// A GATT status that is none of the others. Inspect . + Other, + + /// ATT error 0x05, Insufficient Authentication: the link must be authenticated (bonded) first. + InsufficientAuthentication, + + /// ATT error 0x08, Insufficient Authorization: the peripheral refuses this central the operation. + InsufficientAuthorization, + + /// ATT error 0x0F, Insufficient Encryption: the link must be encrypted first. + InsufficientEncryption + } + + /// + /// A failed read or write that can carry the GATT status the peripheral or the platform's GATT layer + /// reported. Implemented by , , + /// and , so one catch can recognise a + /// security failure from any of them. + /// + /// + /// + /// catch (BleException ex) when (ex is IGattStatusException { GattFailure: GattFailure.InsufficientAuthentication or GattFailure.InsufficientEncryption }) + /// { + /// // Ask the user to pair. + /// } + /// + /// + public interface IGattStatusException + { + /// + /// The GATT status code, where one was reported: on Android the GattStatus from the callback, on + /// Apple platforms the CBATTError code when the error is in CBATTErrorDomain, and on Windows + /// the protocol error. ATT error codes have the same value on every platform; Android can also report + /// codes of its own GATT layer, such as 0x85. when no status was reported. + /// + int? GattStatus { get; } + + /// , classified. + GattFailure GattFailure { get; } + } + + internal static class GattStatusCodes + { + public static GattFailure Classify(int? gattStatus) + { + switch (gattStatus) + { + case null: + return GattFailure.None; + case 0x05: + return GattFailure.InsufficientAuthentication; + case 0x08: + return GattFailure.InsufficientAuthorization; + case 0x0F: + return GattFailure.InsufficientEncryption; + default: + return GattFailure.Other; + } + } + } +} diff --git a/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs index 9e38400..a7fb399 100644 --- a/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs @@ -5,7 +5,7 @@ namespace System.BluetoothLe /// /// Thrown when reading a characteristic, or enabling notifications on one, fails. /// - public class CharacteristicReadException : BleException + public class CharacteristicReadException : BleException, IGattStatusException { /// The characteristic the operation was attempted on, where it is known. public Guid CharacteristicId { get; } @@ -19,6 +19,14 @@ public class CharacteristicReadException : BleException /// public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public CharacteristicReadException(string message) : base(message) { @@ -35,5 +43,19 @@ public CharacteristicReadException(string message, Guid characteristicId, Guid s ServiceId = serviceId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The characteristic, as . + /// The owning service, as . + /// The raw platform status, as . + /// The GATT status, as . + public CharacteristicReadException(string message, Guid characteristicId, Guid serviceId, int? nativeStatus, int? gattStatus) + : this(message, characteristicId, serviceId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs index 5b5caea..d545005 100644 --- a/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs @@ -10,7 +10,7 @@ namespace System.BluetoothLe /// WriteAsync with no reason attached, while Android threw /// from the write path. Both are now this type on every platform. /// - public class CharacteristicWriteException : BleException + public class CharacteristicWriteException : BleException, IGattStatusException { /// The characteristic the write was attempted on, where it is known. public Guid CharacteristicId { get; } @@ -24,6 +24,14 @@ public class CharacteristicWriteException : BleException /// public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public CharacteristicWriteException(string message) : base(message) { @@ -40,5 +48,19 @@ public CharacteristicWriteException(string message, Guid characteristicId, Guid ServiceId = serviceId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The characteristic, as . + /// The owning service, as . + /// The raw platform status, as . + /// The GATT status, as . + public CharacteristicWriteException(string message, Guid characteristicId, Guid serviceId, int? nativeStatus, int? gattStatus) + : this(message, characteristicId, serviceId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs index d05ab3d..139ecbb 100644 --- a/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs @@ -5,7 +5,7 @@ namespace System.BluetoothLe /// /// Thrown when reading a descriptor fails. /// - public class DescriptorReadException : BleException + public class DescriptorReadException : BleException, IGattStatusException { /// The descriptor the read was attempted on, where it is known. public Guid DescriptorId { get; } @@ -13,6 +13,14 @@ public class DescriptorReadException : BleException /// The raw platform status code, where the platform supplied one. public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public DescriptorReadException(string message) : base(message) { @@ -24,5 +32,18 @@ public DescriptorReadException(string message, Guid descriptorId, int? nativeSta DescriptorId = descriptorId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The descriptor, as . + /// The raw platform status, as . + /// The GATT status, as . + public DescriptorReadException(string message, Guid descriptorId, int? nativeStatus, int? gattStatus) + : this(message, descriptorId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs index 4c2fb7e..1a738f7 100644 --- a/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs @@ -7,7 +7,7 @@ namespace System.BluetoothLe /// characteristic configuration descriptor, so this is the failure a consumer sees when a subscription /// cannot be established. /// - public class DescriptorWriteException : BleException + public class DescriptorWriteException : BleException, IGattStatusException { /// The descriptor the write was attempted on, where it is known. public Guid DescriptorId { get; } @@ -15,6 +15,14 @@ public class DescriptorWriteException : BleException /// The raw platform status code, where the platform supplied one. public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public DescriptorWriteException(string message) : base(message) { @@ -26,5 +34,18 @@ public DescriptorWriteException(string message, Guid descriptorId, int? nativeSt DescriptorId = descriptorId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The descriptor, as . + /// The raw platform status, as . + /// The GATT status, as . + public DescriptorWriteException(string message, Guid descriptorId, int? nativeStatus, int? gattStatus) + : this(message, descriptorId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs index 49d626e..71f7983 100644 --- a/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs @@ -26,7 +26,8 @@ public static byte[] GetValueOrThrowIfError(this GattReadResult result, [CallerM var errorMessage = result.Status.GetErrorMessage(tag, result.ProtocolError); if (!string.IsNullOrEmpty(errorMessage)) { - throw new CharacteristicReadException(errorMessage); + // The message is unchanged; the ATT protocol error, where Windows reported one, is now attached. + throw new CharacteristicReadException(errorMessage, Guid.Empty, Guid.Empty, result.ProtocolError, result.ProtocolError); } return result.Value?.ToArray() ?? Array.Empty(); diff --git a/DSoft.System.BluetoothLe/Extensions/NSErrorExtensions.ios.mac.tvos.watchos.cs b/DSoft.System.BluetoothLe/Extensions/NSErrorExtensions.ios.mac.tvos.watchos.cs new file mode 100644 index 0000000..6ba2414 --- /dev/null +++ b/DSoft.System.BluetoothLe/Extensions/NSErrorExtensions.ios.mac.tvos.watchos.cs @@ -0,0 +1,26 @@ +using Foundation; + +namespace System.BluetoothLe.Extensions +{ + internal static class NSErrorExtensions + { + // The value of CoreBluetooth's CBATTErrorDomain constant. Compared as a string so this does not depend on + // how the binding surfaces the constant. + private const string AttErrorDomain = "CBATTErrorDomain"; + + /// + /// The ATT error code carried by when it is a CBATTError, which shares its + /// values with the ATT specification; for an error in any other domain, such as a + /// CBError, whose codes mean something else. + /// + public static int? GetAttStatus(this NSError error) + { + if (error == null || error.Domain != AttErrorDomain) + { + return null; + } + + return (int)error.Code; + } + } +} diff --git a/README.md b/README.md index d9e2cb3..dc3894e 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,7 @@ await adapter.DisconnectDeviceAsync(device); - `Descriptor.ReadAsync`, `WriteAsync`: interact with descriptors. - `Device.BondState`: the device's bond (pairing) state, as the platform reports it. - `Adapter.DeviceBondStateChanged`: raised on Android when a device's bond state changes. +- `IGattStatusException.GattStatus`, `GattFailure`: the GATT status on a failed read or write. - `Device.CreateBondAsync`, `RemoveBondAsync`: request or remove a bond on Android. ## Bonding @@ -247,6 +248,21 @@ if (device.BondState != DeviceBondState.Bonded && !await device.CreateBondAsync( } ``` +**Recognising a security failure.** A peripheral that requires a bonded, encrypted link refuses an unbonded central with ATT error Insufficient Authentication (0x05) or Insufficient Encryption (0x0F). The read and write exceptions (`CharacteristicReadException`, `CharacteristicWriteException`, `DescriptorReadException` and `DescriptorWriteException`) carry that status in `GattStatus`, classified in `GattFailure`, on Android, Apple platforms and Windows. All four implement `IGattStatusException`, so one catch covers them: + +```csharp +try +{ + await characteristic.WriteAsync(data, cancellationToken); +} +catch (BleException ex) when (ex is IGattStatusException { GattFailure: GattFailure.InsufficientAuthentication or GattFailure.InsufficientEncryption }) +{ + // Ask the user to pair, or to forget the device in Settings and pair again. +} +``` + +Subscribing with `StartUpdatesAsync` fails as a `DescriptorWriteException` on Android, where it writes the configuration descriptor itself, and as a `CharacteristicReadException` on Apple platforms. `GattStatus` is `null`, and `GattFailure` is `None`, when no GATT status was reported: the operation could not start, the device disconnected, or on Apple platforms the error was not an ATT error. `NativeStatus` and the exception messages are unchanged. + `BondState` never throws: it reports `Unknown` wherever the state cannot be read, including for a stand-in device and after the device has been disposed. ## Notes