use crate::error::{Error, Result};
use crate::uuid::BluetoothUuid;
use futures_channel::mpsc;
use std::collections::{BTreeSet, HashMap};
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Grant {
pub services: BTreeSet<BluetoothUuid>,
#[cfg(feature = "unrestricted")]
pub all_services: bool,
pub manufacturer_data: Vec<u16>,
#[cfg(feature = "unrestricted")]
pub all_manufacturer_data: bool,
}
impl Grant {
pub fn new() -> Self {
Self::default()
}
#[cfg(feature = "unrestricted")]
pub fn all_services() -> Self {
Self {
all_services: true,
..Self::default()
}
}
#[cfg(feature = "unrestricted")]
pub fn all_manufacturer_data(mut self) -> Self {
self.all_manufacturer_data = true;
self
}
#[cfg(feature = "unrestricted")]
pub fn unrestricted() -> Self {
Self::all_services().all_manufacturer_data()
}
pub fn permits_all_services(&self) -> bool {
#[cfg(feature = "unrestricted")]
{
self.all_services
}
#[cfg(not(feature = "unrestricted"))]
{
false
}
}
pub fn permits_all_manufacturer_data(&self) -> bool {
#[cfg(feature = "unrestricted")]
{
self.all_manufacturer_data
}
#[cfg(not(feature = "unrestricted"))]
{
false
}
}
pub fn permits(&self, uuid: &BluetoothUuid) -> bool {
self.permits_all_services() || self.services.contains(uuid)
}
pub fn permits_company(&self, company: u16) -> bool {
self.permits_all_manufacturer_data() || self.manufacturer_data.contains(&company)
}
pub fn service(mut self, uuid: impl crate::uuid::IntoUuid) -> crate::error::Result<Self> {
let uuid = uuid.into_uuid()?;
if crate::blocklist::is_blocked(&uuid) {
return Err(crate::error::Error::Security(format!(
"service {uuid} is on the GATT blocklist"
)));
}
self.services.insert(uuid);
Ok(self)
}
pub fn services<U: crate::uuid::IntoUuid>(
mut self,
uuids: impl IntoIterator<Item = U>,
) -> crate::error::Result<Self> {
for uuid in uuids {
self = self.service(uuid)?;
}
Ok(self)
}
pub fn manufacturer_data(mut self, ids: impl IntoIterator<Item = u16>) -> Self {
for company in ids {
if !self.manufacturer_data.contains(&company) {
self.manufacturer_data.push(company);
}
}
self
}
pub fn validate(&self) -> crate::error::Result<()> {
for uuid in &self.services {
if crate::blocklist::is_blocked(uuid) {
return Err(crate::error::Error::Security(format!(
"service {uuid} is on the GATT blocklist"
)));
}
}
Ok(())
}
pub fn union(&self, other: &Self) -> Self {
let mut manufacturer_data = self.manufacturer_data.clone();
for company in &other.manufacturer_data {
if !manufacturer_data.contains(company) {
manufacturer_data.push(*company);
}
}
Self {
services: self.services.union(&other.services).cloned().collect(),
#[cfg(feature = "unrestricted")]
all_services: self.all_services || other.all_services,
manufacturer_data,
#[cfg(feature = "unrestricted")]
all_manufacturer_data: self.all_manufacturer_data || other.all_manufacturer_data,
}
}
}
impl From<BTreeSet<BluetoothUuid>> for Grant {
fn from(services: BTreeSet<BluetoothUuid>) -> Self {
let mut grant = Self::new();
grant.services = services;
grant
}
}
#[cfg_attr(feature = "unrestricted", doc = "[`Grant::all_services`],")]
#[cfg_attr(not(feature = "unrestricted"), doc = "`Grant::all_services`,")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AllowedServices {
All,
Only(BTreeSet<BluetoothUuid>),
}
impl AllowedServices {
pub fn contains(&self, uuid: &BluetoothUuid) -> bool {
match self {
Self::All => true,
Self::Only(set) => set.contains(uuid),
}
}
pub fn is_all(&self) -> bool {
matches!(self, Self::All)
}
pub fn named(&self) -> Option<&BTreeSet<BluetoothUuid>> {
match self {
Self::All => None,
Self::Only(set) => Some(set),
}
}
}
pub struct Device<T> {
pub name: Option<String>,
pub allowed: Grant,
pub connected: bool,
pub generation: u64,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub gatt: Arc<futures_util::lock::Mutex<()>>,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub inner: T,
}
pub struct DeviceRegistry<T> {
devices: Mutex<HashMap<String, Device<T>>>,
listeners: Mutex<HashMap<String, Vec<mpsc::UnboundedSender<()>>>>,
service_listeners: Mutex<HashMap<String, Vec<mpsc::UnboundedSender<()>>>>,
}
impl<T> Default for DeviceRegistry<T> {
fn default() -> Self {
Self {
devices: Mutex::new(HashMap::new()),
listeners: Mutex::new(HashMap::new()),
service_listeners: Mutex::new(HashMap::new()),
}
}
}
impl<T> DeviceRegistry<T> {
pub fn insert(
&self,
id: &str,
name: Option<String>,
allowed: Grant,
connected: bool,
inner: T,
) {
let mut devices = self.devices.lock().unwrap();
let previous = devices.get(id);
let generation = previous.map(|d| d.generation).unwrap_or(0);
let gatt = previous
.map(|d| d.gatt.clone())
.unwrap_or_else(|| Arc::new(futures_util::lock::Mutex::new(())));
let allowed = match previous {
Some(d) => d.allowed.union(&allowed),
None => allowed,
};
devices.insert(
id.to_owned(),
Device {
name,
allowed,
connected,
generation,
gatt,
inner,
},
);
}
pub fn get<R>(&self, id: &str, f: impl FnOnce(&Device<T>) -> R) -> Result<R> {
let devices = self.devices.lock().unwrap();
let device = devices
.get(id)
.ok_or_else(|| Error::InvalidState(format!("device {id} is no longer known")))?;
Ok(f(device))
}
pub fn update(&self, id: &str, f: impl FnOnce(&mut Device<T>)) {
if let Some(device) = self.devices.lock().unwrap().get_mut(id) {
f(device);
}
}
#[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
pub fn update_where(
&self,
matches: impl Fn(&Device<T>) -> bool,
f: impl FnOnce(&mut Device<T>),
) -> Option<String> {
let mut devices = self.devices.lock().unwrap();
let found = devices.iter_mut().find(|(_, d)| matches(d));
let (id, device) = found?;
let id = id.clone();
f(device);
Some(id)
}
#[cfg_attr(
any(
all(target_os = "linux", feature = "linux-hci"),
target_os = "windows",
target_arch = "wasm32",
),
allow(dead_code)
)]
pub fn find(&self, matches: impl Fn(&Device<T>) -> bool) -> Option<String> {
self.devices
.lock()
.unwrap()
.iter()
.find(|(_, d)| matches(d))
.map(|(id, _)| id.clone())
}
pub fn name(&self, id: &str) -> Option<String> {
self.get(id, |d| d.name.clone()).ok().flatten()
}
pub fn is_connected(&self, id: &str) -> bool {
self.get(id, |d| d.connected).unwrap_or(false)
}
pub fn generation(&self, id: &str) -> Result<u64> {
self.get(id, |d| d.generation)
}
pub fn ids(&self) -> Vec<String> {
self.devices.lock().unwrap().keys().cloned().collect()
}
pub fn remove(&self, id: &str) -> Option<Device<T>> {
self.listeners.lock().unwrap().remove(id);
self.devices.lock().unwrap().remove(id)
}
pub fn check_allowed(&self, id: &str, uuid: &BluetoothUuid) -> Result<()> {
if self.get(id, |d| d.allowed.permits(uuid))? {
Ok(())
} else {
Err(Error::Security(format!(
"service {uuid} was not requested — list it in filters or optional_services"
)))
}
}
pub fn allowed_services(&self, id: &str) -> Result<AllowedServices> {
self.get(id, |d| {
if d.allowed.permits_all_services() {
AllowedServices::All
} else {
AllowedServices::Only(d.allowed.services.clone())
}
})
}
pub fn grant(&self, id: &str) -> Grant {
self.get(id, |d| d.allowed.clone()).unwrap_or_default()
}
pub fn check_generation(&self, id: &str, generation: u64) -> Result<()> {
let current = self.generation(id)?;
if !self.is_connected(id) {
return Err(Error::Network("the device is not connected".into()));
}
if current != generation {
return Err(Error::InvalidState(
"this GATT object is stale — the device disconnected or changed its services"
.into(),
));
}
Ok(())
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub async fn gatt_lock(&self, id: &str) -> Result<futures_util::lock::OwnedMutexGuard<()>> {
Ok(self.get(id, |d| d.gatt.clone())?.lock_owned().await)
}
pub fn watch_services_changed(&self, id: &str) -> mpsc::UnboundedReceiver<()> {
let (tx, rx) = mpsc::unbounded();
self.service_listeners
.lock()
.unwrap()
.entry(id.to_owned())
.or_default()
.push(tx);
rx
}
pub fn mark_services_changed(&self, id: &str) {
self.update(id, |d| d.generation += 1);
let mut listeners = self.service_listeners.lock().unwrap();
if let Some(subscribers) = listeners.get_mut(id) {
subscribers.retain(|tx| tx.unbounded_send(()).is_ok());
}
}
pub fn watch_disconnect(&self, id: &str) -> mpsc::UnboundedReceiver<()> {
let (tx, rx) = mpsc::unbounded();
self.listeners
.lock()
.unwrap()
.entry(id.to_owned())
.or_default()
.push(tx);
rx
}
pub fn mark_disconnected(&self, id: &str) {
self.update(id, |d| {
d.connected = false;
d.generation += 1;
});
let mut listeners = self.listeners.lock().unwrap();
if let Some(subscribers) = listeners.get_mut(id) {
subscribers.retain(|tx| tx.unbounded_send(()).is_ok());
if subscribers.is_empty() {
listeners.remove(id);
}
}
}
}
#[macro_export]
macro_rules! forward_to_registry {
() => {
pub fn device_name(&self, id: &str) -> Option<String> {
self.devices.name(id)
}
pub fn is_connected(&self, id: &str) -> bool {
self.devices.is_connected(id)
}
pub fn generation(&self, id: &str) -> $crate::error::Result<u64> {
self.devices.generation(id)
}
pub fn granted_devices(&self) -> Vec<String> {
self.devices.ids()
}
pub fn check_allowed(
&self,
id: &str,
uuid: &$crate::uuid::BluetoothUuid,
) -> $crate::error::Result<()> {
self.devices.check_allowed(id, uuid)
}
pub fn allowed_services(
&self,
id: &str,
) -> $crate::error::Result<$crate::registry::AllowedServices> {
self.devices.allowed_services(id)
}
pub fn check_generation(&self, id: &str, generation: u64) -> $crate::error::Result<()> {
self.devices.check_generation(id, generation)
}
pub fn watch_disconnect(
&self,
id: &str,
) -> $crate::futures_channel::mpsc::UnboundedReceiver<()> {
self.devices.watch_disconnect(id)
}
pub fn watch_services_changed(
&self,
id: &str,
) -> $crate::futures_channel::mpsc::UnboundedReceiver<()> {
self.devices.watch_services_changed(id)
}
pub fn grant(&self, id: &str) -> $crate::registry::Grant {
self.devices.grant(id)
}
};
}
pub use crate::forward_to_registry;
#[cfg(test)]
mod tests {
use super::*;
use crate::uuid::services;
use futures_executor::block_on;
fn grant_of(services: &[BluetoothUuid], companies: &[u16]) -> Grant {
let mut grant = Grant::new();
grant.services = services.iter().copied().collect();
grant.manufacturer_data = companies.to_vec();
grant
}
fn registry() -> DeviceRegistry<u32> {
let registry = DeviceRegistry::default();
registry.insert(
"AA:BB",
Some("Sensor".into()),
BTreeSet::from([services::HEART_RATE]).into(),
true,
7u32,
);
registry
}
#[test]
fn an_unrequested_service_is_a_security_error() {
let registry = registry();
assert!(registry
.check_allowed("AA:BB", &services::HEART_RATE)
.is_ok());
let refused = registry.check_allowed("AA:BB", &services::BATTERY_SERVICE);
assert!(
matches!(refused, Err(Error::Security(_))),
"got {refused:?}"
);
}
#[test]
fn handles_go_stale_when_the_generation_moves() {
let registry = registry();
assert!(registry.check_generation("AA:BB", 0).is_ok());
registry.mark_disconnected("AA:BB");
assert!(matches!(
registry.check_generation("AA:BB", 0),
Err(Error::Network(_))
));
assert!(matches!(
registry.check_generation("AA:BB", 1),
Err(Error::Network(_))
));
assert!(!registry.is_connected("AA:BB"));
}
#[test]
fn a_handle_from_before_a_reconnect_is_stale_not_disconnected() {
let registry = registry();
let before = registry.generation("AA:BB").unwrap();
registry.mark_disconnected("AA:BB");
registry.update("AA:BB", |d| d.connected = true);
assert!(matches!(
registry.check_generation("AA:BB", before),
Err(Error::InvalidState(_))
));
let now = registry.generation("AA:BB").unwrap();
assert!(registry.check_generation("AA:BB", now).is_ok());
}
#[test]
fn disconnecting_notifies_watchers() {
let registry = registry();
let mut watcher = registry.watch_disconnect("AA:BB");
registry.mark_disconnected("AA:BB");
assert!(block_on(futures_util::StreamExt::next(&mut watcher)).is_some());
}
#[test]
fn an_unknown_device_is_an_invalid_state_not_a_panic() {
let registry: DeviceRegistry<u32> = DeviceRegistry::default();
assert!(matches!(
registry.generation("nope"),
Err(Error::InvalidState(_))
));
assert!(matches!(
registry.check_generation("nope", 0),
Err(Error::InvalidState(_))
));
assert!(registry.name("nope").is_none());
assert!(!registry.is_connected("nope"));
}
#[test]
fn the_gatt_lock_serialises_operations() {
let registry = registry();
block_on(async {
let first = registry.gatt_lock("AA:BB").await.unwrap();
let second = registry.gatt_lock("AA:BB");
let pending = futures_util::poll!(std::pin::pin!(second));
assert!(pending.is_pending(), "the lock let two operations through");
drop(first);
});
}
#[test]
fn devices_can_be_found_by_backend_specific_identity() {
let registry = registry();
assert_eq!(registry.find(|d| d.inner == 7), Some("AA:BB".into()));
assert_eq!(registry.find(|d| d.inner == 99), None);
registry.update_where(|d| d.inner == 7, |d| d.name = Some("Renamed".into()));
assert_eq!(registry.name("AA:BB").as_deref(), Some("Renamed"));
}
#[test]
fn a_narrower_second_grant_does_not_revoke_the_first() {
let registry = DeviceRegistry::<()>::default();
let battery = BluetoothUuid::from_u16(0x180F);
let info = BluetoothUuid::from_u16(0x180A);
registry.insert(
"dev",
None,
grant_of(&[battery, info], &[0x004C]),
false,
(),
);
registry.insert("dev", None, grant_of(&[battery], &[]), false, ());
assert!(
registry.check_allowed("dev", &info).is_ok(),
"the first grant's service is still allowed"
);
assert!(registry.check_allowed("dev", &battery).is_ok());
assert_eq!(
registry.grant("dev").manufacturer_data,
vec![0x004C],
"and so is the company it was granted"
);
}
#[test]
fn a_re_grant_does_not_revive_stale_handles() {
let registry = DeviceRegistry::<()>::default();
let grant = || grant_of(&[BluetoothUuid::from_u16(0x180F)], &[]);
registry.insert("dev", None, grant(), true, ());
let captured = registry.generation("dev").unwrap();
assert!(registry.check_generation("dev", captured).is_ok());
registry.mark_disconnected("dev");
registry.insert("dev", None, grant(), true, ());
assert_eq!(
registry
.check_generation("dev", captured)
.unwrap_err()
.to_string(),
Error::InvalidState(
"this GATT object is stale — the device disconnected or changed its services"
.into()
)
.to_string(),
"the handle from before the disconnect must stay stale"
);
let fresh = registry.generation("dev").unwrap();
assert!(registry.check_generation("dev", fresh).is_ok());
}
#[test]
fn forgetting_removes_the_grant_and_its_watchers() {
let registry = registry();
let _watcher = registry.watch_disconnect("AA:BB");
assert!(registry.remove("AA:BB").is_some());
assert!(registry.ids().is_empty());
assert!(registry.remove("AA:BB").is_none());
}
#[cfg(feature = "unrestricted")]
#[test]
fn an_unrestricted_grant_reaches_a_service_nobody_named() {
let registry = DeviceRegistry::<()>::default();
let vendor = BluetoothUuid::parse("f000aa00-0451-4000-b000-000000000000").unwrap();
registry.insert("dev", None, Grant::unrestricted(), false, ());
assert!(registry.check_allowed("dev", &vendor).is_ok());
assert!(registry.allowed_services("dev").unwrap().is_all());
assert!(registry.allowed_services("dev").unwrap().contains(&vendor));
assert!(registry.allowed_services("dev").unwrap().named().is_none());
}
#[cfg(feature = "unrestricted")]
#[test]
fn a_wildcard_survives_a_narrower_re_grant() {
let narrow = Grant::new()
.service(BluetoothUuid::from_u16(0x180F))
.unwrap();
assert!(Grant::unrestricted().union(&narrow).permits_all_services());
assert!(narrow.union(&Grant::unrestricted()).permits_all_services());
assert!(!narrow.union(&narrow).permits_all_services());
}
#[cfg(feature = "unrestricted")]
#[test]
fn an_unrestricted_grant_is_still_subject_to_the_blocklist() {
let hid = BluetoothUuid::from_u16(0x1812);
assert!(
crate::blocklist::is_blocked(&hid),
"the vendored blocklist must still block HID"
);
assert!(Grant::unrestricted().permits(&hid));
assert!(crate::blocklist::is_blocked(&hid));
}
#[test]
fn a_plain_grant_permits_only_what_it_names() {
let battery = BluetoothUuid::from_u16(0x180F);
let grant = Grant::new().service(battery).unwrap();
assert!(grant.permits(&battery));
assert!(!grant.permits(&BluetoothUuid::from_u16(0x180A)));
assert!(!grant.permits_all_services());
assert!(!grant.permits_all_manufacturer_data());
assert!(!Grant::default().permits(&battery));
}
}