webbluetooth_core/
blocklist.rs1use crate::filter::DataPrefix;
17use crate::uuid::BluetoothUuid;
18use std::collections::HashMap;
19use std::sync::OnceLock;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Blocked {
24 All,
26 Writes,
28 Reads,
30}
31
32const SOURCE: &str = include_str!("../spec/gatt-blocklist.txt");
34
35fn table() -> &'static HashMap<BluetoothUuid, Blocked> {
36 static TABLE: OnceLock<HashMap<BluetoothUuid, Blocked>> = OnceLock::new();
37 TABLE.get_or_init(|| parse(SOURCE))
38}
39
40fn parse(source: &str) -> HashMap<BluetoothUuid, Blocked> {
43 let mut out = HashMap::new();
44 for line in source.lines() {
45 let line = line.split('#').next().unwrap_or("").trim();
46 if line.is_empty() {
47 continue;
48 }
49 let mut parts = line.split_whitespace();
50 let Some(uuid) = parts.next() else { continue };
51 let Ok(uuid) = BluetoothUuid::parse(uuid) else {
52 continue;
53 };
54 let blocked = match parts.next() {
55 Some("exclude-writes") => Blocked::Writes,
56 Some("exclude-reads") => Blocked::Reads,
57 _ => Blocked::All,
58 };
59 out.insert(uuid, blocked);
60 }
61 out
62}
63
64pub fn lookup(uuid: &BluetoothUuid) -> Option<Blocked> {
66 table().get(uuid).copied()
67}
68
69pub fn is_blocked(uuid: &BluetoothUuid) -> bool {
71 matches!(lookup(uuid), Some(Blocked::All))
72}
73
74pub fn reads_blocked(uuid: &BluetoothUuid) -> bool {
76 matches!(lookup(uuid), Some(Blocked::All) | Some(Blocked::Reads))
77}
78
79pub fn writes_blocked(uuid: &BluetoothUuid) -> bool {
81 matches!(lookup(uuid), Some(Blocked::All) | Some(Blocked::Writes))
82}
83
84const MANUFACTURER_SOURCE: &str = include_str!("../spec/manufacturer-data-blocklist.txt");
108
109type ManufacturerTable = Option<HashMap<u16, Vec<DataPrefix>>>;
115
116fn manufacturer_table() -> &'static ManufacturerTable {
117 static TABLE: OnceLock<ManufacturerTable> = OnceLock::new();
118 TABLE.get_or_init(|| parse_manufacturer(MANUFACTURER_SOURCE))
119}
120
121fn parse_manufacturer(source: &str) -> ManufacturerTable {
122 fn hex(text: &str) -> Option<Vec<u8>> {
123 if text.is_empty() || !text.len().is_multiple_of(2) {
124 return None;
125 }
126 (0..text.len())
127 .step_by(2)
128 .map(|i| u8::from_str_radix(&text[i..i + 2], 16).ok())
129 .collect()
130 }
131
132 let mut out: HashMap<u16, Vec<DataPrefix>> = HashMap::new();
133 for line in source.lines() {
134 let line = line.split('#').next().unwrap_or("").trim();
135 if line.is_empty() {
136 continue;
137 }
138 let mut parts = line.split_whitespace();
139 if parts.next() != Some("manufacturer") {
140 return None;
141 }
142 let company = parts
144 .next()
145 .filter(|c| c.len() <= 4)
146 .and_then(|c| u16::from_str_radix(c, 16).ok())?;
147 let (data, mask) = parts.next()?.strip_prefix("advdata-")?.split_once('/')?;
148 let (data, mask) = (hex(data)?, hex(mask)?);
149 let prefix = DataPrefix::with_mask(data, mask).ok()?;
150 out.entry(company).or_default().push(prefix);
151 }
152 Some(out)
153}
154
155pub fn manufacturer_data_blocked(company: u16, data: &[u8]) -> bool {
159 let Some(table) = manufacturer_table() else {
160 return true; };
162 table
163 .get(&company)
164 .is_some_and(|prefixes| prefixes.iter().any(|p| p.matches(data)))
165}
166
167pub fn manufacturer_filter_blocked(company: u16, prefix: &DataPrefix) -> bool {
176 let Some(table) = manufacturer_table() else {
177 return true;
178 };
179 table
180 .get(&company)
181 .is_some_and(|blocked| blocked.iter().any(|b| prefix.strict_subset_of(b)))
182}
183
184pub fn entries() -> impl Iterator<Item = (&'static BluetoothUuid, Blocked)> {
186 table().iter().map(|(u, b)| (u, *b))
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use crate::uuid::{characteristics, descriptors, services};
193
194 const APPLE: u16 = 0x004C;
195
196 #[test]
199 fn ibeacon_data_is_blocked_because_it_is_a_location_fix() {
200 assert!(
201 manufacturer_data_blocked(APPLE, &[0x02, 0x15, 0xAB, 0xCD]),
202 "an iBeacon frame must not reach a caller"
203 );
204 assert!(
205 !manufacturer_data_blocked(APPLE, &[0x09, 0x06, 0x03]),
206 "Apple's other advertisements are not blocked wholesale"
207 );
208 assert!(
209 !manufacturer_data_blocked(0x00E0, &[0x02, 0x15]),
210 "another company's 0x02 frame is not an iBeacon"
211 );
212 }
213
214 #[test]
216 fn data_shorter_than_the_prefix_is_not_blocked() {
217 assert!(!manufacturer_data_blocked(APPLE, &[]));
218 }
219
220 #[test]
223 fn only_filters_wholly_inside_the_blocklist_are_refused() {
224 let ibeacon = DataPrefix::new(vec![0x02]);
225 assert!(manufacturer_filter_blocked(APPLE, &ibeacon));
226
227 let narrower = DataPrefix::new(vec![0x02, 0x15]);
228 assert!(
229 manufacturer_filter_blocked(APPLE, &narrower),
230 "narrowing a blocked filter must not get around it"
231 );
232
233 let other = DataPrefix::new(vec![0x09]);
234 assert!(
235 !manufacturer_filter_blocked(APPLE, &other),
236 "a filter for something else is fine"
237 );
238
239 let loose = DataPrefix::with_mask(vec![0x02], vec![0x01]).unwrap();
243 assert!(!manufacturer_filter_blocked(APPLE, &loose));
244 }
245
246 #[test]
250 fn an_unreadable_list_blocks_everything() {
251 for bad in [
252 "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", ] {
261 assert!(
262 parse_manufacturer(bad).is_none(),
263 "{bad:?} should have failed to parse"
264 );
265 }
266 }
267
268 #[test]
269 fn the_vendored_list_parses_and_is_not_empty() {
270 let table = manufacturer_table()
274 .as_ref()
275 .expect("the vendored manufacturer blocklist must parse");
276 assert!(!table.is_empty());
277 }
278
279 #[test]
281 fn prefix_and_mask_must_agree_in_length() {
282 assert!(parse_manufacturer("manufacturer 4c advdata-0215/ff").is_none());
283 }
284
285 #[test]
286 fn hid_service_is_fully_blocked() {
287 let hid = services::HUMAN_INTERFACE_DEVICE;
289 assert!(is_blocked(&hid));
290 assert!(reads_blocked(&hid) && writes_blocked(&hid));
291 }
292
293 #[test]
294 fn firmware_update_services_are_blocked() {
295 for uuid in [
296 "00001530-1212-efde-1523-785feabcd123", "f000ffc0-0451-4000-b000-000000000000", ] {
299 assert!(
300 is_blocked(&BluetoothUuid::parse(uuid).unwrap()),
301 "{uuid} not blocked"
302 );
303 }
304 }
305
306 #[test]
307 fn serial_number_is_blocked_because_it_identifies_the_user() {
308 let sn = characteristics::SERIAL_NUMBER_STRING;
309 assert!(is_blocked(&sn));
310 }
311
312 #[test]
313 fn cccd_is_write_blocked_not_read_blocked() {
314 let cccd = descriptors::CLIENT_CHARACTERISTIC_CONFIGURATION;
317 assert_eq!(lookup(&cccd), Some(Blocked::Writes));
318 assert!(writes_blocked(&cccd));
319 assert!(!reads_blocked(&cccd));
320 assert!(!is_blocked(&cccd));
321 }
322
323 #[test]
324 fn ordinary_services_are_not_blocked() {
325 for u in [
326 services::BATTERY_SERVICE,
327 services::HEART_RATE,
328 services::DEVICE_INFORMATION,
329 ] {
330 assert!(lookup(&u).is_none());
331 }
332 }
333
334 #[test]
335 fn snapshot_parsed_completely() {
336 let expected = SOURCE
339 .lines()
340 .filter(|l| {
341 let l = l.split('#').next().unwrap_or("").trim();
342 !l.is_empty()
343 })
344 .count();
345 assert_eq!(
346 table().len(),
347 expected,
348 "some blocklist lines failed to parse"
349 );
350 assert!(
351 expected >= 12,
352 "vendored blocklist looks truncated: {expected} entries"
353 );
354 }
355}