use crate::filter::DataPrefix;
use crate::uuid::BluetoothUuid;
use std::collections::HashMap;
use std::sync::OnceLock;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Blocked {
All,
Writes,
Reads,
}
const SOURCE: &str = include_str!("../spec/gatt-blocklist.txt");
fn table() -> &'static HashMap<BluetoothUuid, Blocked> {
static TABLE: OnceLock<HashMap<BluetoothUuid, Blocked>> = OnceLock::new();
TABLE.get_or_init(|| parse(SOURCE))
}
fn parse(source: &str) -> HashMap<BluetoothUuid, Blocked> {
let mut out = HashMap::new();
for line in source.lines() {
let line = line.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(uuid) = parts.next() else { continue };
let Ok(uuid) = BluetoothUuid::parse(uuid) else {
continue;
};
let blocked = match parts.next() {
Some("exclude-writes") => Blocked::Writes,
Some("exclude-reads") => Blocked::Reads,
_ => Blocked::All,
};
out.insert(uuid, blocked);
}
out
}
pub fn lookup(uuid: &BluetoothUuid) -> Option<Blocked> {
table().get(uuid).copied()
}
pub fn is_blocked(uuid: &BluetoothUuid) -> bool {
matches!(lookup(uuid), Some(Blocked::All))
}
pub fn reads_blocked(uuid: &BluetoothUuid) -> bool {
matches!(lookup(uuid), Some(Blocked::All) | Some(Blocked::Reads))
}
pub fn writes_blocked(uuid: &BluetoothUuid) -> bool {
matches!(lookup(uuid), Some(Blocked::All) | Some(Blocked::Writes))
}
const MANUFACTURER_SOURCE: &str = include_str!("../spec/manufacturer-data-blocklist.txt");
type ManufacturerTable = Option<HashMap<u16, Vec<DataPrefix>>>;
fn manufacturer_table() -> &'static ManufacturerTable {
static TABLE: OnceLock<ManufacturerTable> = OnceLock::new();
TABLE.get_or_init(|| parse_manufacturer(MANUFACTURER_SOURCE))
}
fn parse_manufacturer(source: &str) -> ManufacturerTable {
fn hex(text: &str) -> Option<Vec<u8>> {
if text.is_empty() || !text.len().is_multiple_of(2) {
return None;
}
(0..text.len())
.step_by(2)
.map(|i| u8::from_str_radix(&text[i..i + 2], 16).ok())
.collect()
}
let mut out: HashMap<u16, Vec<DataPrefix>> = HashMap::new();
for line in source.lines() {
let line = line.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
if parts.next() != Some("manufacturer") {
return None;
}
let company = parts
.next()
.filter(|c| c.len() <= 4)
.and_then(|c| u16::from_str_radix(c, 16).ok())?;
let (data, mask) = parts.next()?.strip_prefix("advdata-")?.split_once('/')?;
let (data, mask) = (hex(data)?, hex(mask)?);
let prefix = DataPrefix::with_mask(data, mask).ok()?;
out.entry(company).or_default().push(prefix);
}
Some(out)
}
pub fn manufacturer_data_blocked(company: u16, data: &[u8]) -> bool {
let Some(table) = manufacturer_table() else {
return true; };
table
.get(&company)
.is_some_and(|prefixes| prefixes.iter().any(|p| p.matches(data)))
}
pub fn manufacturer_filter_blocked(company: u16, prefix: &DataPrefix) -> bool {
let Some(table) = manufacturer_table() else {
return true;
};
table
.get(&company)
.is_some_and(|blocked| blocked.iter().any(|b| prefix.strict_subset_of(b)))
}
pub fn entries() -> impl Iterator<Item = (&'static BluetoothUuid, Blocked)> {
table().iter().map(|(u, b)| (u, *b))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::uuid::{characteristics, descriptors, services};
const APPLE: u16 = 0x004C;
#[test]
fn ibeacon_data_is_blocked_because_it_is_a_location_fix() {
assert!(
manufacturer_data_blocked(APPLE, &[0x02, 0x15, 0xAB, 0xCD]),
"an iBeacon frame must not reach a caller"
);
assert!(
!manufacturer_data_blocked(APPLE, &[0x09, 0x06, 0x03]),
"Apple's other advertisements are not blocked wholesale"
);
assert!(
!manufacturer_data_blocked(0x00E0, &[0x02, 0x15]),
"another company's 0x02 frame is not an iBeacon"
);
}
#[test]
fn data_shorter_than_the_prefix_is_not_blocked() {
assert!(!manufacturer_data_blocked(APPLE, &[]));
}
#[test]
fn only_filters_wholly_inside_the_blocklist_are_refused() {
let ibeacon = DataPrefix::new(vec![0x02]);
assert!(manufacturer_filter_blocked(APPLE, &ibeacon));
let narrower = DataPrefix::new(vec![0x02, 0x15]);
assert!(
manufacturer_filter_blocked(APPLE, &narrower),
"narrowing a blocked filter must not get around it"
);
let other = DataPrefix::new(vec![0x09]);
assert!(
!manufacturer_filter_blocked(APPLE, &other),
"a filter for something else is fine"
);
let loose = DataPrefix::with_mask(vec![0x02], vec![0x01]).unwrap();
assert!(!manufacturer_filter_blocked(APPLE, &loose));
}
#[test]
fn an_unreadable_list_blocks_everything() {
for bad in [
"manufacturer", "manufacturer 4c", "manufacturer 4c 02/ff", "manufacturer 4c advdata-02", "manufacturer 4c advdata-2/ff", "manufacturer 4c advdata-02/fg", "manufacturer 12345 advdata-02/ff", "uuid 00001812-0000-1000-8000-00805f9b34fb", ] {
assert!(
parse_manufacturer(bad).is_none(),
"{bad:?} should have failed to parse"
);
}
}
#[test]
fn the_vendored_list_parses_and_is_not_empty() {
let table = manufacturer_table()
.as_ref()
.expect("the vendored manufacturer blocklist must parse");
assert!(!table.is_empty());
}
#[test]
fn prefix_and_mask_must_agree_in_length() {
assert!(parse_manufacturer("manufacturer 4c advdata-0215/ff").is_none());
}
#[test]
fn hid_service_is_fully_blocked() {
let hid = services::HUMAN_INTERFACE_DEVICE;
assert!(is_blocked(&hid));
assert!(reads_blocked(&hid) && writes_blocked(&hid));
}
#[test]
fn firmware_update_services_are_blocked() {
for uuid in [
"00001530-1212-efde-1523-785feabcd123", "f000ffc0-0451-4000-b000-000000000000", ] {
assert!(
is_blocked(&BluetoothUuid::parse(uuid).unwrap()),
"{uuid} not blocked"
);
}
}
#[test]
fn serial_number_is_blocked_because_it_identifies_the_user() {
let sn = characteristics::SERIAL_NUMBER_STRING;
assert!(is_blocked(&sn));
}
#[test]
fn cccd_is_write_blocked_not_read_blocked() {
let cccd = descriptors::CLIENT_CHARACTERISTIC_CONFIGURATION;
assert_eq!(lookup(&cccd), Some(Blocked::Writes));
assert!(writes_blocked(&cccd));
assert!(!reads_blocked(&cccd));
assert!(!is_blocked(&cccd));
}
#[test]
fn ordinary_services_are_not_blocked() {
for u in [
services::BATTERY_SERVICE,
services::HEART_RATE,
services::DEVICE_INFORMATION,
] {
assert!(lookup(&u).is_none());
}
}
#[test]
fn snapshot_parsed_completely() {
let expected = SOURCE
.lines()
.filter(|l| {
let l = l.split('#').next().unwrap_or("").trim();
!l.is_empty()
})
.count();
assert_eq!(
table().len(),
expected,
"some blocklist lines failed to parse"
);
assert!(
expected >= 12,
"vendored blocklist looks truncated: {expected} entries"
);
}
}