use crate::backend::attribute_uuid;
use crate::backend::Handle;
use crate::blocklist;
use crate::error::{Error, Result};
use crate::uuid::{BluetoothUuid, IntoUuid};
use futures_core::Stream;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
pub use webbluetooth_core::gatt::{CharacteristicProperties, WriteType};
const MAX_ATTRIBUTE_LENGTH: usize = 512;
fn descriptor_suffix(value: &[u8], offset: usize) -> Result<Vec<u8>> {
if offset > value.len() {
return Err(Error::InvalidModification(format!(
"descriptor offset {offset} exceeds its {}-byte value",
value.len()
)));
}
Ok(value[offset..].to_vec())
}
fn descriptor_patch(mut current: Vec<u8>, offset: usize, value: &[u8]) -> Result<Vec<u8>> {
if offset > current.len() {
return Err(Error::InvalidModification(format!(
"descriptor offset {offset} exceeds its {}-byte value",
current.len()
)));
}
let end = offset
.checked_add(value.len())
.ok_or_else(|| Error::InvalidModification("descriptor value is too large".into()))?;
if end > MAX_ATTRIBUTE_LENGTH {
return Err(Error::InvalidModification(format!(
"value is {end} bytes; a GATT attribute holds at most {MAX_ATTRIBUTE_LENGTH}"
)));
}
if current.len() < end {
current.resize(end, 0);
}
current[offset..end].copy_from_slice(value);
Ok(current)
}
#[derive(Clone)]
pub struct RemoteGattServer {
pub(crate) inner: Arc<crate::session::Session>,
pub(crate) id: String,
}
impl RemoteGattServer {
pub fn watch_services_changed(&self) -> crate::ServiceEvents {
crate::ServiceEvents {
rx: self.inner.watch_services_changed(&self.id),
}
}
pub fn device(&self) -> crate::BluetoothDevice {
crate::BluetoothDevice {
inner: self.inner.clone(),
id: self.id.clone(),
}
}
pub fn connected(&self) -> bool {
self.inner.is_connected(&self.id)
}
pub async fn connect(&self) -> Result<()> {
self.inner.backend().connect(&self.id).await
}
pub fn disconnect(&self) {
self.inner.disconnect(&self.id);
}
pub async fn disconnect_and_wait(&self) {
use futures_util::StreamExt;
let mut disconnects = self.inner.watch_disconnect(&self.id);
self.inner.disconnect(&self.id);
if self.connected() {
disconnects.next().await;
}
}
pub async fn get_characteristics(&self) -> Result<Vec<RemoteGattCharacteristic>> {
let mut out = Vec::new();
for service in self.get_primary_services(None).await? {
match service.get_characteristics(None).await {
Ok(found) => out.extend(found),
Err(Error::NotFound(_)) => {}
Err(e) => return Err(e),
}
}
Ok(out)
}
pub async fn get_primary_service(&self, uuid: impl IntoUuid) -> Result<RemoteGattService> {
let uuid = uuid.into_uuid()?;
self.guard_service(&uuid)?;
let found = self.inner.discover_services(&self.id, Some(&uuid)).await?;
let handle = found
.into_iter()
.next()
.ok_or_else(|| Error::NotFound(format!("no primary service {uuid} on this device")))?;
self.service_from(handle, uuid)
}
pub async fn get_primary_services(
&self,
uuid: impl webbluetooth_core::uuid::IntoOptionalUuid,
) -> Result<Vec<RemoteGattService>> {
let uuid = uuid.into_optional_uuid()?;
if let Some(u) = &uuid {
self.guard_service(u)?;
}
let allowed = self.inner.allowed_services(&self.id)?;
let found = self
.inner
.discover_services(&self.id, uuid.as_ref())
.await?;
let mut out = Vec::new();
for handle in found {
let Ok(u) = attribute_uuid(&handle) else {
continue;
};
if !allowed.contains(&u) || blocklist::is_blocked(&u) {
continue;
}
out.push(self.service_from(handle, u)?);
}
if out.is_empty() {
return Err(Error::NotFound(
"no accessible primary services on this device".into(),
));
}
Ok(out)
}
fn guard_service(&self, uuid: &BluetoothUuid) -> Result<()> {
if blocklist::is_blocked(uuid) {
return Err(Error::Security(format!(
"service {uuid} is on the GATT blocklist"
)));
}
self.inner.check_allowed(&self.id, uuid)
}
fn service_from(&self, handle: Handle, uuid: BluetoothUuid) -> Result<RemoteGattService> {
Ok(RemoteGattService {
is_primary: self.inner.service_is_primary(&handle),
inner: self.inner.clone(),
device_id: self.id.clone(),
generation: self.inner.generation(&self.id)?,
handle,
uuid,
})
}
}
#[derive(Clone)]
pub struct RemoteGattService {
inner: Arc<crate::session::Session>,
device_id: String,
handle: Handle,
uuid: BluetoothUuid,
generation: u64,
is_primary: bool,
}
impl RemoteGattService {
pub fn uuid(&self) -> &BluetoothUuid {
&self.uuid
}
pub fn device(&self) -> crate::BluetoothDevice {
crate::BluetoothDevice {
inner: self.inner.clone(),
id: self.device_id.clone(),
}
}
pub fn is_primary(&self) -> bool {
self.is_primary
}
pub async fn get_characteristic(
&self,
uuid: impl IntoUuid,
) -> Result<RemoteGattCharacteristic> {
let uuid = uuid.into_uuid()?;
self.inner
.check_generation(&self.device_id, self.generation)?;
if blocklist::is_blocked(&uuid) {
return Err(Error::Security(format!(
"characteristic {uuid} is on the GATT blocklist"
)));
}
let found = self
.inner
.discover_characteristics(&self.device_id, &self.handle, Some(&uuid))
.await?;
let handle = found.into_iter().next().ok_or_else(|| {
Error::NotFound(format!("no characteristic {uuid} in service {}", self.uuid))
})?;
self.characteristic_from(handle, uuid)
}
pub async fn get_characteristics(
&self,
uuid: impl webbluetooth_core::uuid::IntoOptionalUuid,
) -> Result<Vec<RemoteGattCharacteristic>> {
let uuid = uuid.into_optional_uuid()?;
self.inner
.check_generation(&self.device_id, self.generation)?;
let found = self
.inner
.discover_characteristics(&self.device_id, &self.handle, uuid.as_ref())
.await?;
let mut out = Vec::new();
for handle in found {
let Ok(u) = attribute_uuid(&handle) else {
continue;
};
if blocklist::is_blocked(&u) {
continue;
}
out.push(self.characteristic_from(handle, u)?);
}
if out.is_empty() {
return Err(Error::NotFound(format!(
"no accessible characteristics in service {}",
self.uuid
)));
}
Ok(out)
}
pub async fn get_included_service(&self, uuid: impl IntoUuid) -> Result<RemoteGattService> {
let uuid = uuid.into_uuid()?;
self.inner
.check_generation(&self.device_id, self.generation)?;
self.guard_included(&uuid)?;
let found = self
.inner
.discover_included_services(&self.device_id, &self.handle, Some(&uuid))
.await?;
let handle = found.into_iter().next().ok_or_else(|| {
Error::NotFound(format!(
"no included service {uuid} in service {}",
self.uuid
))
})?;
self.included_from(handle, uuid)
}
pub async fn get_included_services(
&self,
uuid: impl webbluetooth_core::uuid::IntoOptionalUuid,
) -> Result<Vec<RemoteGattService>> {
let uuid = uuid.into_optional_uuid()?;
self.inner
.check_generation(&self.device_id, self.generation)?;
if let Some(u) = &uuid {
self.guard_included(u)?;
}
let allowed = self.inner.allowed_services(&self.device_id)?;
let found = self
.inner
.discover_included_services(&self.device_id, &self.handle, uuid.as_ref())
.await?;
let mut out = Vec::new();
for handle in found {
let Ok(u) = attribute_uuid(&handle) else {
continue;
};
if !allowed.contains(&u) || blocklist::is_blocked(&u) {
continue;
}
out.push(self.included_from(handle, u)?);
}
if out.is_empty() {
return Err(Error::NotFound(format!(
"no accessible included services in service {}",
self.uuid
)));
}
Ok(out)
}
fn guard_included(&self, uuid: &BluetoothUuid) -> Result<()> {
if blocklist::is_blocked(uuid) {
return Err(Error::Security(format!(
"service {uuid} is on the GATT blocklist"
)));
}
self.inner.check_allowed(&self.device_id, uuid)
}
fn included_from(&self, handle: Handle, uuid: BluetoothUuid) -> Result<RemoteGattService> {
Ok(RemoteGattService {
is_primary: false,
inner: self.inner.clone(),
device_id: self.device_id.clone(),
generation: self.generation,
handle,
uuid,
})
}
fn characteristic_from(
&self,
handle: Handle,
uuid: BluetoothUuid,
) -> Result<RemoteGattCharacteristic> {
Ok(RemoteGattCharacteristic {
properties: self.inner.characteristic_properties(&handle),
inner: self.inner.clone(),
device_id: self.device_id.clone(),
service_uuid: self.uuid,
service_handle: self.handle.clone(),
generation: self.generation,
handle,
uuid,
})
}
}
impl std::fmt::Debug for RemoteGattService {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RemoteGattService")
.field("uuid", &self.uuid.as_str())
.field("is_primary", &self.is_primary)
.finish()
}
}
#[derive(Clone)]
pub struct RemoteGattCharacteristic {
inner: Arc<crate::session::Session>,
device_id: String,
service_uuid: BluetoothUuid,
service_handle: Handle,
handle: Handle,
uuid: BluetoothUuid,
generation: u64,
properties: CharacteristicProperties,
}
impl RemoteGattCharacteristic {
pub fn service(&self) -> RemoteGattService {
RemoteGattService {
is_primary: self.inner.service_is_primary(&self.service_handle),
inner: self.inner.clone(),
device_id: self.device_id.clone(),
generation: self.generation,
handle: self.service_handle.clone(),
uuid: self.service_uuid,
}
}
pub fn uuid(&self) -> &BluetoothUuid {
&self.uuid
}
pub fn service_uuid(&self) -> &BluetoothUuid {
&self.service_uuid
}
pub fn properties(&self) -> CharacteristicProperties {
self.properties
}
pub fn value(&self) -> Option<Vec<u8>> {
self.inner.cached_value(&self.handle)
}
pub async fn read_value(&self) -> Result<Vec<u8>> {
self.inner
.check_generation(&self.device_id, self.generation)?;
if blocklist::reads_blocked(&self.uuid) {
return Err(Error::Security(format!(
"reading {} is blocklisted",
self.uuid
)));
}
if !self.properties.read() {
return Err(Error::NotSupported(format!(
"characteristic {} does not support reading",
self.uuid
)));
}
self.inner
.read_characteristic(&self.device_id, &self.handle)
.await
}
pub async fn read_value_at_offset(&self, offset: usize) -> Result<Vec<u8>> {
descriptor_suffix(&self.read_value().await?, offset)
}
pub async fn write_value_with_response(&self, value: &[u8]) -> Result<()> {
self.guard_write(value)?;
if !self.properties.write() {
return Err(Error::NotSupported(format!(
"characteristic {} does not support acknowledged writes",
self.uuid
)));
}
self.inner
.write_characteristic(
&self.device_id,
&self.handle,
value,
WriteType::WithResponse,
)
.await
}
pub async fn write_value_without_response(&self, value: &[u8]) -> Result<()> {
self.guard_write(value)?;
if !self.properties.write_without_response() {
return Err(Error::NotSupported(format!(
"characteristic {} does not support unacknowledged writes",
self.uuid
)));
}
self.inner
.write_characteristic(
&self.device_id,
&self.handle,
value,
WriteType::WithoutResponse,
)
.await
}
pub fn max_write_length(&self, with_response: bool) -> Result<usize> {
let t = if with_response {
WriteType::WithResponse
} else {
WriteType::WithoutResponse
};
self.inner.max_write_len(&self.device_id, t)
}
pub async fn start_notifications(&self) -> Result<Notifications> {
self.inner
.check_generation(&self.device_id, self.generation)?;
if !self.properties.notify() && !self.properties.indicate() {
return Err(Error::NotSupported(format!(
"characteristic {} supports neither notifications nor indications",
self.uuid
)));
}
let rx = self.inner.subscribe(&self.handle);
let disconnects = self.inner.watch_disconnect(&self.device_id);
self.inner
.set_notify(&self.device_id, &self.handle, true)
.await?;
Ok(Notifications {
rx,
disconnects,
ended: false,
characteristic: self.clone(),
})
}
pub async fn stop_notifications(&self) -> Result<()> {
self.inner
.check_generation(&self.device_id, self.generation)?;
self.inner
.set_notify(&self.device_id, &self.handle, false)
.await?;
Ok(())
}
pub fn is_notifying(&self) -> bool {
self.inner.is_notifying(&self.handle)
}
pub async fn get_descriptor(&self, uuid: impl IntoUuid) -> Result<RemoteGattDescriptor> {
let uuid = uuid.into_uuid()?;
self.inner
.check_generation(&self.device_id, self.generation)?;
let found = self
.inner
.discover_descriptors(&self.device_id, &self.handle, Some(&uuid))
.await?;
let handle = found.into_iter().next().ok_or_else(|| {
Error::NotFound(format!(
"no descriptor {uuid} on characteristic {}",
self.uuid
))
})?;
Ok(self.descriptor_from(handle, uuid))
}
pub async fn get_descriptors(&self) -> Result<Vec<RemoteGattDescriptor>> {
self.inner
.check_generation(&self.device_id, self.generation)?;
let found = self
.inner
.discover_descriptors(&self.device_id, &self.handle, None)
.await?;
Ok(found
.into_iter()
.filter_map(|h| {
let u = attribute_uuid(&h).ok()?;
Some(self.descriptor_from(h, u))
})
.collect())
}
fn descriptor_from(&self, handle: Handle, uuid: BluetoothUuid) -> RemoteGattDescriptor {
RemoteGattDescriptor {
inner: self.inner.clone(),
device_id: self.device_id.clone(),
characteristic_uuid: self.uuid,
characteristic_handle: self.handle.clone(),
service_uuid: self.service_uuid,
service_handle: self.service_handle.clone(),
generation: self.generation,
handle,
uuid,
}
}
fn guard_write(&self, value: &[u8]) -> Result<()> {
self.inner
.check_generation(&self.device_id, self.generation)?;
if blocklist::writes_blocked(&self.uuid) {
return Err(Error::Security(format!(
"writing {} is blocklisted",
self.uuid
)));
}
if value.len() > MAX_ATTRIBUTE_LENGTH {
return Err(Error::InvalidModification(format!(
"value is {} bytes; a GATT attribute holds at most {MAX_ATTRIBUTE_LENGTH}",
value.len()
)));
}
Ok(())
}
}
impl std::fmt::Debug for RemoteGattCharacteristic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RemoteGattCharacteristic")
.field("uuid", &self.uuid.as_str())
.field("properties", &self.properties)
.finish()
}
}
#[derive(Clone)]
pub struct RemoteGattDescriptor {
inner: Arc<crate::session::Session>,
device_id: String,
characteristic_uuid: BluetoothUuid,
characteristic_handle: Handle,
service_uuid: BluetoothUuid,
service_handle: Handle,
handle: Handle,
uuid: BluetoothUuid,
generation: u64,
}
impl RemoteGattDescriptor {
pub fn characteristic(&self) -> RemoteGattCharacteristic {
RemoteGattCharacteristic {
properties: self
.inner
.characteristic_properties(&self.characteristic_handle),
inner: self.inner.clone(),
device_id: self.device_id.clone(),
service_uuid: self.service_uuid,
service_handle: self.service_handle.clone(),
generation: self.generation,
handle: self.characteristic_handle.clone(),
uuid: self.characteristic_uuid,
}
}
pub fn uuid(&self) -> &BluetoothUuid {
&self.uuid
}
pub fn characteristic_uuid(&self) -> &BluetoothUuid {
&self.characteristic_uuid
}
pub async fn read_value(&self) -> Result<Vec<u8>> {
self.inner
.check_generation(&self.device_id, self.generation)?;
if blocklist::reads_blocked(&self.uuid) {
return Err(Error::Security(format!(
"reading {} is blocklisted",
self.uuid
)));
}
self.inner
.read_descriptor(&self.device_id, &self.handle)
.await
}
pub async fn read_value_at_offset(&self, offset: usize) -> Result<Vec<u8>> {
let value = self.read_value().await?;
if offset > value.len() {
return Err(Error::InvalidModification(format!(
"descriptor offset {offset} exceeds its {}-byte value",
value.len()
)));
}
Ok(value[offset..].to_vec())
}
pub async fn write_value(&self, value: &[u8]) -> Result<()> {
self.inner
.check_generation(&self.device_id, self.generation)?;
if blocklist::writes_blocked(&self.uuid) {
return Err(Error::Security(format!(
"writing {} is blocklisted — use start_notifications() to subscribe",
self.uuid
)));
}
if value.len() > MAX_ATTRIBUTE_LENGTH {
return Err(Error::InvalidModification(format!(
"value is {} bytes; a GATT attribute holds at most {MAX_ATTRIBUTE_LENGTH}",
value.len()
)));
}
self.inner
.write_descriptor(&self.device_id, &self.handle, value)
.await
}
pub async fn write_value_at_offset(&self, offset: usize, value: &[u8]) -> Result<()> {
let current = descriptor_patch(self.read_value().await?, offset, value)?;
self.write_value(¤t).await
}
}
impl std::fmt::Debug for RemoteGattDescriptor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RemoteGattDescriptor")
.field("uuid", &self.uuid.as_str())
.finish()
}
}
pub struct Notifications {
rx: crate::backlog::Receiver<Vec<u8>>,
disconnects: futures_channel::mpsc::UnboundedReceiver<()>,
ended: bool,
characteristic: RemoteGattCharacteristic,
}
impl Notifications {
pub fn characteristic(&self) -> &RemoteGattCharacteristic {
&self.characteristic
}
pub fn uuid(&self) -> &BluetoothUuid {
self.characteristic.uuid()
}
pub fn tagged(self) -> Tagged {
Tagged { inner: self }
}
pub fn lost(&self) -> u64 {
self.rx.lost()
}
pub fn depth(&self) -> usize {
self.rx.depth()
}
}
pub struct Tagged {
inner: Notifications,
}
impl Tagged {
pub fn characteristic(&self) -> &RemoteGattCharacteristic {
self.inner.characteristic()
}
pub fn uuid(&self) -> &BluetoothUuid {
self.inner.uuid()
}
pub fn lost(&self) -> u64 {
self.inner.lost()
}
pub fn depth(&self) -> usize {
self.inner.depth()
}
}
impl Stream for Tagged {
type Item = (BluetoothUuid, Vec<u8>);
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let uuid = *self.inner.uuid();
Pin::new(&mut self.inner)
.poll_next(cx)
.map(|value| value.map(|value| (uuid, value)))
}
}
impl std::fmt::Debug for Tagged {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Tagged")
.field("uuid", &self.uuid().as_str())
.field("lost", &self.lost())
.finish_non_exhaustive()
}
}
impl Stream for Notifications {
type Item = Vec<u8>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Vec<u8>>> {
let this = &mut *self;
poll_until_disconnect(&mut this.rx, &mut this.disconnects, &mut this.ended, cx)
}
}
fn poll_until_disconnect<V, D>(
values: &mut V,
disconnects: &mut D,
ended: &mut bool,
cx: &mut Context<'_>,
) -> Poll<Option<Vec<u8>>>
where
V: Stream<Item = Vec<u8>> + Unpin,
D: Stream<Item = ()> + Unpin,
{
if *ended {
return Poll::Ready(None);
}
match Pin::new(values).poll_next(cx) {
Poll::Ready(Some(value)) => return Poll::Ready(Some(value)),
Poll::Ready(None) => {}
Poll::Pending => {
if Pin::new(disconnects).poll_next(cx).is_pending() {
return Poll::Pending;
}
}
}
*ended = true;
Poll::Ready(None)
}
impl std::fmt::Debug for RemoteGattServer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RemoteGattServer")
.field("device", &self.id)
.finish_non_exhaustive()
}
}
impl std::fmt::Debug for Notifications {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Notifications")
.field("uuid", &self.uuid().as_str())
.field("lost", &self.lost())
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn descriptor_suffix_validates_offsets() {
assert_eq!(descriptor_suffix(&[1, 2, 3], 1).unwrap(), vec![2, 3]);
assert_eq!(descriptor_suffix(&[1, 2, 3], 3).unwrap(), Vec::<u8>::new());
assert!(descriptor_suffix(&[1, 2, 3], 4).is_err());
}
#[test]
fn descriptor_patch_preserves_and_extends_values() {
assert_eq!(
descriptor_patch(vec![1, 2, 3], 1, &[9, 8]).unwrap(),
vec![1, 9, 8]
);
assert_eq!(
descriptor_patch(vec![1, 2], 2, &[3, 4]).unwrap(),
vec![1, 2, 3, 4]
);
assert!(descriptor_patch(vec![1], 2, &[3]).is_err());
assert!(descriptor_patch(vec![], 0, &vec![0; MAX_ATTRIBUTE_LENGTH + 1]).is_err());
}
struct Subscription {
values: futures_channel::mpsc::UnboundedReceiver<Vec<u8>>,
disconnects: futures_channel::mpsc::UnboundedReceiver<()>,
ended: bool,
}
impl Stream for Subscription {
type Item = Vec<u8>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Vec<u8>>> {
let this = &mut *self;
poll_until_disconnect(&mut this.values, &mut this.disconnects, &mut this.ended, cx)
}
}
#[test]
fn notifications_end_when_the_device_disconnects() {
use futures_util::StreamExt;
let (values_tx, values) = futures_channel::mpsc::unbounded();
let (disconnects_tx, disconnects) = futures_channel::mpsc::unbounded();
let mut subscription = Subscription {
values,
disconnects,
ended: false,
};
values_tx.unbounded_send(vec![1]).unwrap();
values_tx.unbounded_send(vec![2]).unwrap();
disconnects_tx.unbounded_send(()).unwrap();
futures_executor::block_on(async {
assert_eq!(subscription.next().await, Some(vec![1]));
assert_eq!(subscription.next().await, Some(vec![2]));
assert_eq!(subscription.next().await, None);
values_tx.unbounded_send(vec![3]).unwrap();
assert_eq!(subscription.next().await, None);
});
}
}