Skip to main content

webbluetooth_core/
scan.rs

1//! Fan-out for the one radio scan a controller can run.
2//!
3//! Every platform here scans globally: CoreBluetooth has one
4//! `scanForPeripheralsWithServices:` per central, BlueZ one `StartDiscovery`
5//! per adapter, WinRT one watcher, Android one `BluetoothLeScanner`. The radio
6//! is single, but the *interest* in it is not — the specification has three
7//! things that all want advertisements at once:
8//!
9//! * `requestDevice()`, while the chooser deliberates,
10//! * `requestLEScan()`, for as long as the caller keeps it,
11//! * `watchAdvertisements()`, on a device that is already granted.
12//!
13//! So the scan is reference-counted and its sightings are published to every
14//! interested party. The first watcher starts the radio and the last one stops
15//! it, which means a `requestDevice` no longer cancels a scan somebody else is
16//! relying on.
17//!
18//! Filters are combined rather than intersected: the radio scan has to be at
19//! least as wide as the widest watcher, and each watcher then applies its own
20//! filter to what arrives. A watcher with no service filter therefore forces an
21//! unfiltered scan, which is the only way it can see what it asked for.
22
23use crate::chooser::Candidate;
24use crate::filter::{Advertisement, RequestDeviceOptions};
25use crate::registry::Grant;
26use crate::uuid::BluetoothUuid;
27use std::collections::HashSet;
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::sync::Mutex;
30
31/// What one watcher is interested in.
32// `Request` and `choose` are unused on the web: `requestDevice` there opens
33// the browser's own picker, so there is no scan to run and no candidate list
34// for a chooser to be offered.
35#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
36/// How many advertisements a watcher queues before the oldest are dropped.
37///
38/// Smaller than a notification backlog on purpose. Advertisements arrive far
39/// faster and age far worse: by the time a consumer is 256 behind, the early
40/// ones describe a room that has moved on. Keeping more would cost memory to
41/// deliver information that is already wrong.
42const ADVERTISEMENT_BACKLOG: usize = 256;
43
44/// Why something is watching the radio.
45///
46/// The hub keeps one scan for all of them and hands each watcher only what it
47/// asked for, so a `request_device` finishing cannot stop somebody else's
48/// `watchAdvertisements`.
49pub enum Want {
50    /// A `requestDevice` chooser. Duplicates are wanted: they keep RSSI live
51    /// while the chooser is deciding.
52    Request(RequestDeviceOptions),
53    /// `requestLEScan`.
54    Scan {
55        /// What the caller asked for, which is also what it may be told.
56        options: RequestDeviceOptions,
57        /// Whether repeated sightings of the same device are wanted.
58        keep_repeated: bool,
59    },
60    /// `watchAdvertisements` on one granted device — every packet from it, but
61    /// reported through the grant that device was given.
62    /// One device's advertisements — `watchAdvertisements`.
63    Device {
64        /// Which device.
65        id: String,
66        /// What the holder may be told about it.
67        grant: Grant,
68    },
69}
70
71impl Want {
72    fn options(&self) -> Option<&RequestDeviceOptions> {
73        match self {
74            Self::Request(options) => Some(options),
75            Self::Scan { options, .. } => Some(options),
76            Self::Device { .. } => None,
77        }
78    }
79
80    /// The grant that advertisements reported to this watcher pass through,
81    /// or `None` if they are reported whole.
82    ///
83    /// A grant is a permission, not a preference. The specification's
84    /// *fire an advertisementreceived event* narrows the event to the services
85    /// and company identifiers the caller was granted, so a site cannot learn
86    /// what else a device is broadcasting; asking for none means seeing none.
87    ///
88    /// It applies to the two paths that fire that event — `watchAdvertisements`
89    /// and `requestLEScan` — and not to the chooser. The chooser is the picker
90    /// the user is looking at while deciding, which is the one place the
91    /// unfiltered view is the point: it has to show what is on the air, and
92    /// there is no grant yet to filter by, because granting is what the user
93    /// is in the middle of doing.
94    fn grant(&self) -> Option<Grant> {
95        match self {
96            Self::Request(_) => None,
97            Self::Scan { options, .. } => Some(options.grant()),
98            Self::Device { grant, .. } => Some(grant.clone()),
99        }
100    }
101
102    fn wants_duplicates(&self) -> bool {
103        match self {
104            Self::Request(_) | Self::Device { .. } => true,
105            Self::Scan { keep_repeated, .. } => *keep_repeated,
106        }
107    }
108
109    /// Does this sighting belong to this watcher?
110    fn accepts(&self, id: &str, name: Option<&str>, advertisement: &Advertisement) -> bool {
111        match self {
112            Self::Device { id: wanted, .. } => wanted == id,
113            Self::Request(options) | Self::Scan { options, .. } => {
114                options.matches(name, advertisement)
115            }
116        }
117    }
118}
119
120struct Watcher {
121    id: u64,
122    want: Want,
123    /// Resolved once here rather than per packet, since it cannot change.
124    grant: Option<Grant>,
125    tx: crate::backlog::Sender<Candidate>,
126    /// Devices already delivered, for a watcher that does not want repeats.
127    delivered: HashSet<String>,
128}
129
130/// The registry of everyone watching the scan.
131pub struct ScanHub {
132    watchers: Mutex<Vec<Watcher>>,
133    next_id: AtomicU64,
134}
135
136impl Default for ScanHub {
137    fn default() -> Self {
138        Self::new()
139    }
140}
141
142impl ScanHub {
143    /// A hub with no watchers and the radio off.
144    pub fn new() -> Self {
145        Self {
146            watchers: Mutex::new(Vec::new()),
147            next_id: AtomicU64::new(1),
148        }
149    }
150
151    /// Register a watcher.
152    ///
153    /// The `bool` is whether the radio scan has to be (re)started: either
154    /// because this is the first watcher, or because it widened the filter.
155    pub fn add(&self, want: Want) -> (u64, crate::backlog::Receiver<Candidate>, bool) {
156        // The busiest stream in the crate: a radio in a crowded room reports
157        // hundreds of advertisements a second, from a callback thread that
158        // cannot be made to wait. Bounded, keeping the newest, because an
159        // advertisement is a statement about *now* — one from four seconds ago
160        // is not worth the memory it is sitting in, and the device that sent
161        // it will say so again shortly if it is still there.
162        let (tx, rx) =
163            crate::backlog::bounded(ADVERTISEMENT_BACKLOG, crate::backlog::Overflow::KeepNewest);
164        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
165        let mut watchers = self.watchers.lock().unwrap();
166        let before = Self::radio_filter(&watchers);
167        watchers.push(Watcher {
168            id,
169            grant: want.grant(),
170            want,
171            tx,
172            delivered: HashSet::new(),
173        });
174        let after = Self::radio_filter(&watchers);
175        (id, rx, before != after || watchers.len() == 1)
176    }
177
178    /// Remove a watcher, returning whether the radio scan should now stop.
179    pub fn remove(&self, id: u64) -> bool {
180        let mut watchers = self.watchers.lock().unwrap();
181        watchers.retain(|w| w.id != id);
182        watchers.is_empty()
183    }
184
185    /// Drop every watcher, ending their streams.
186    ///
187    /// For when the platform says the scan has failed: nothing further will
188    /// arrive, so a chooser waiting on the stream should see it end rather than
189    /// wait out its whole window for traffic that is not coming.
190    ///
191    /// Not every platform has such a signal — CoreBluetooth has no
192    /// scan-failed callback at all — so this is unused on some targets.
193    #[allow(dead_code)]
194    pub fn close_all(&self) {
195        self.watchers.lock().unwrap().clear();
196    }
197
198    /// Whether `watchAdvertisements` is running for this device —
199    /// `BluetoothDevice.watchingAdvertisements`.
200    pub fn is_watching_device(&self, id: &str) -> bool {
201        self.watchers
202            .lock()
203            .unwrap()
204            .iter()
205            .any(|w| matches!(&w.want, Want::Device { id: watched, .. } if watched == id))
206    }
207
208    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
209    /// Whether anything still wants the radio scanning.
210    pub fn is_watching(&self) -> bool {
211        !self.watchers.lock().unwrap().is_empty()
212    }
213
214    /// Whether a given watcher is still registered — how a handed-out scan
215    /// reports whether it is still live.
216    pub fn contains(&self, id: u64) -> bool {
217        self.watchers.lock().unwrap().iter().any(|w| w.id == id)
218    }
219
220    /// The service UUIDs the radio scan should ask for.
221    ///
222    /// Unused on a transport whose scan cannot be filtered at all — a raw HCI
223    /// socket reports whatever the radio hears.
224    ///
225    /// Empty means "everything", and one watcher that needs everything makes it
226    /// empty for all of them — a narrower scan would hide what that watcher
227    /// asked for. The per-watcher filter still applies on the way out, so a
228    /// wider radio scan costs traffic, never correctness.
229    #[allow(dead_code)]
230    pub fn scan_services(&self) -> Vec<BluetoothUuid> {
231        Self::radio_filter(&self.watchers.lock().unwrap())
232    }
233
234    fn radio_filter(watchers: &[Watcher]) -> Vec<BluetoothUuid> {
235        let mut union: Vec<BluetoothUuid> = Vec::new();
236        for watcher in watchers {
237            let Some(options) = watcher.want.options() else {
238                // `watchAdvertisements` names a device, not a service.
239                return Vec::new();
240            };
241            let services = options.scan_services();
242            if services.is_empty() {
243                return Vec::new();
244            }
245            for uuid in services {
246                if !union.contains(&uuid) {
247                    union.push(uuid);
248                }
249            }
250        }
251        union.sort_by(|a, b| a.as_str().cmp(b.as_str()));
252        union
253    }
254
255    /// Whether the radio scan should report repeat sightings.
256    ///
257    /// Also unused where the scan cannot be told either way.
258    #[allow(dead_code)]
259    pub fn wants_duplicates(&self) -> bool {
260        self.watchers
261            .lock()
262            .unwrap()
263            .iter()
264            .any(|w| w.want.wants_duplicates())
265    }
266
267    /// Offer one sighting to every watcher that wants it.
268    ///
269    /// A watcher whose receiver has been dropped is left in place; `remove` is
270    /// what deregisters, so that a caller who stops polling briefly does not
271    /// silently lose its subscription.
272    pub fn publish(&self, id: &str, name: Option<&str>, advertisement: &Advertisement) {
273        let mut watchers = self.watchers.lock().unwrap();
274        for watcher in watchers.iter_mut() {
275            if !watcher.want.accepts(id, name, advertisement) {
276                continue;
277            }
278            if !watcher.want.wants_duplicates() && !watcher.delivered.insert(id.to_owned()) {
279                continue;
280            }
281            // Filtering happens after matching, deliberately: what a watcher
282            // may be *told* is narrower than what it may be matched on. A
283            // filter for a service the caller then cannot see is still a
284            // legitimate way to find a device.
285            //
286            // Two watchers of the same device can hold different grants, so
287            // the same packet is legitimately reported differently to each.
288            let mut advertisement = advertisement.clone();
289            advertisement.restrict_to(watcher.grant.as_ref());
290
291            let _ = watcher.tx.send(Candidate {
292                id: id.to_owned(),
293                name: name.map(str::to_owned),
294                advertisement,
295            });
296        }
297    }
298}
299
300/// Run a `requestDevice` against the hub.
301///
302/// Every backend used to carry its own copy of this: register a watcher, start
303/// the radio if this watcher needs it, let the chooser decide, then stop the
304/// radio only if nobody else is still watching. The copies drifted — two said
305/// "restarting" where the others said "stopping", and one named the variable
306/// differently — and each was a place the reference counting could be got
307/// wrong independently. What is genuinely per-platform is only what happens
308/// *after* a device is chosen, which stays in the backend.
309///
310/// `set_scanning` starts or stops the platform's scan. `on_joined` runs
311/// instead, when an existing scan is already wide enough to serve this
312/// watcher — BlueZ replays its device cache there, because `bluetoothd` does
313/// not re-announce devices it already knows.
314#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
315pub async fn choose(
316    hub: &ScanHub,
317    options: RequestDeviceOptions,
318    chooser: &dyn crate::chooser::DeviceChooser,
319    set_scanning: impl Fn(bool) -> crate::error::Result<()>,
320    on_joined: impl Fn(),
321) -> crate::error::Result<String> {
322    options.validate()?;
323    let (watcher, from_scan, restart) = hub.add(Want::Request(options));
324
325    if restart {
326        if let Err(e) = set_scanning(true) {
327            hub.remove(watcher);
328            return Err(e);
329        }
330    } else {
331        on_joined();
332    }
333
334    let chosen = chooser
335        .choose(crate::chooser::Candidates { inner: from_scan })
336        .await;
337
338    if hub.remove(watcher) {
339        let _ = set_scanning(false);
340    }
341
342    chosen.ok_or_else(|| crate::error::Error::NotFound("no device was chosen".into()))
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use crate::filter::DeviceFilter;
349    use crate::uuid::services;
350
351    /// The next sighting a watcher has been offered, if any.
352    fn next(rx: &mut crate::backlog::Receiver<Candidate>) -> Option<Candidate> {
353        rx.try_recv()
354    }
355
356    fn advertisement(uuids: &[u16]) -> Advertisement {
357        Advertisement {
358            #[cfg(feature = "classic")]
359            class_of_device: None,
360            service_uuids: uuids.iter().map(|u| BluetoothUuid::from_u16(*u)).collect(),
361            ..Default::default()
362        }
363    }
364
365    fn requesting(service: u16) -> Want {
366        Want::Request(
367            RequestDeviceOptions::new().filter(
368                DeviceFilter::new()
369                    .service(BluetoothUuid::from_u16(service))
370                    .unwrap(),
371            ),
372        )
373    }
374
375    #[test]
376    fn the_first_watcher_starts_the_radio_and_the_last_stops_it() {
377        let hub = ScanHub::new();
378        let (first, _a, start) = hub.add(requesting(0x180F));
379        assert!(start, "the first watcher has to start the scan");
380        let (second, _b, _) = hub.add(requesting(0x180F));
381
382        assert!(!hub.remove(first), "another watcher still wants the scan");
383        assert!(hub.remove(second), "the last one stops it");
384        assert!(!hub.is_watching());
385    }
386
387    /// The case that motivated reference counting: a `requestDevice` used to
388    /// stop the radio on its way out, which would cancel a scan someone else
389    /// was still reading.
390    #[test]
391    fn a_finished_request_does_not_stop_somebody_elses_scan() {
392        let hub = ScanHub::new();
393        let (scan, mut stream, _) = hub.add(Want::Scan {
394            options: RequestDeviceOptions::new().accept_all_devices(),
395            keep_repeated: true,
396        });
397        let (request, _r, _) = hub.add(requesting(0x180F));
398
399        assert!(!hub.remove(request));
400        hub.publish("aa", Some("Sensor"), &advertisement(&[0x180F]));
401        assert!(next(&mut stream).is_some(), "the scan still runs");
402        assert!(hub.contains(scan));
403    }
404
405    #[test]
406    fn one_unfiltered_watcher_widens_the_radio_scan_for_everyone() {
407        let hub = ScanHub::new();
408        let (_a, _s, _) = hub.add(requesting(0x180F));
409        assert_eq!(
410            hub.scan_services(),
411            vec![BluetoothUuid::from_u16(0x180F)],
412            "a single service filter narrows the scan"
413        );
414
415        // `watchAdvertisements` names a device, so the radio cannot be filtered
416        // by service without risking hiding it.
417        let (_b, _t, restart) = hub.add(Want::Device {
418            id: "aa".into(),
419            grant: Grant::default(),
420        });
421        assert!(restart, "widening the filter has to restart the radio");
422        assert!(hub.scan_services().is_empty());
423    }
424
425    #[test]
426    fn filters_are_combined_not_intersected() {
427        let hub = ScanHub::new();
428        hub.add(requesting(0x180F));
429        hub.add(requesting(0x180D));
430        assert_eq!(
431            hub.scan_services(),
432            vec![
433                BluetoothUuid::from_u16(0x180D),
434                BluetoothUuid::from_u16(0x180F)
435            ],
436            "the radio must be at least as wide as the widest watcher"
437        );
438    }
439
440    #[test]
441    fn a_watcher_only_sees_what_its_own_filter_accepts() {
442        let hub = ScanHub::new();
443        let (_a, mut battery, _) = hub.add(requesting(0x180F));
444        let (_b, mut heart, _) = hub.add(requesting(0x180D));
445
446        hub.publish("aa", None, &advertisement(&[0x180F]));
447        assert!(next(&mut battery).is_some());
448        assert!(next(&mut heart).is_none(), "not this watcher's device");
449    }
450
451    #[test]
452    fn a_device_knows_whether_it_is_being_watched() {
453        let hub = ScanHub::new();
454        assert!(!hub.is_watching_device("mine"));
455
456        let (id, _stream, _) = hub.add(Want::Device {
457            id: "mine".into(),
458            grant: Grant::default(),
459        });
460        assert!(hub.is_watching_device("mine"));
461        // A scan is not a watch on any particular device.
462        assert!(!hub.is_watching_device("theirs"));
463
464        hub.remove(id);
465        assert!(!hub.is_watching_device("mine"), "the watch ended");
466    }
467
468    #[test]
469    fn watching_a_device_ignores_every_other_device() {
470        let hub = ScanHub::new();
471        let (_id, mut stream, _) = hub.add(Want::Device {
472            id: "mine".into(),
473            grant: Grant::default(),
474        });
475
476        hub.publish("theirs", Some("Someone Else"), &advertisement(&[]));
477        assert!(next(&mut stream).is_none());
478
479        hub.publish("mine", Some("Mine"), &advertisement(&[]));
480        let event = next(&mut stream).expect("the watched device");
481        assert_eq!(event.id, "mine");
482    }
483
484    #[test]
485    fn a_scan_without_keep_repeated_reports_each_device_once() {
486        let hub = ScanHub::new();
487        let (_id, mut stream, _) = hub.add(Want::Scan {
488            options: RequestDeviceOptions::new().accept_all_devices(),
489            keep_repeated: false,
490        });
491        assert!(!hub.wants_duplicates());
492
493        hub.publish("aa", None, &advertisement(&[]));
494        hub.publish("aa", None, &advertisement(&[]));
495        assert!(next(&mut stream).is_some());
496        assert!(next(&mut stream).is_none(), "the repeat is suppressed");
497
498        // A different device is still new.
499        hub.publish("bb", None, &advertisement(&[]));
500        assert!(next(&mut stream).is_some());
501    }
502
503    #[test]
504    fn a_chooser_gets_duplicates_so_its_rssi_stays_live() {
505        let hub = ScanHub::new();
506        let (_id, mut stream, _) = hub.add(requesting(0x180F));
507        assert!(hub.wants_duplicates());
508        hub.publish("aa", None, &advertisement(&[0x180F]));
509        hub.publish("aa", None, &advertisement(&[0x180F]));
510        assert!(next(&mut stream).is_some());
511        assert!(next(&mut stream).is_some(), "repeats are wanted");
512    }
513
514    /// A failed scan has to end the streams, or a chooser waits out its whole
515    /// window for traffic that will never arrive.
516    #[test]
517    fn closing_the_hub_ends_every_stream() {
518        let hub = ScanHub::new();
519        let (id, mut stream, _) = hub.add(requesting(0x180F));
520        hub.close_all();
521
522        assert!(!hub.is_watching());
523        assert!(!hub.contains(id));
524        // The sender is gone, so the stream is finished rather than merely idle.
525        assert!(stream.try_recv().is_none());
526    }
527
528    /// `optionalManufacturerData` is a permission, not a preference.
529    ///
530    /// The specification filters an advertisement event down to the companies
531    /// the caller asked for, so a site cannot learn what else a device is
532    /// broadcasting. This crate accepted the option and ignored it, which is
533    /// worse than not offering it: a caller could reasonably believe the data
534    /// they were handed had been filtered.
535    #[test]
536    fn manufacturer_data_is_filtered_to_what_was_granted() {
537        const APPLE: u16 = 0x004C;
538        const OTHER: u16 = 0x00E0;
539
540        let hub = ScanHub::new();
541        let (_id, mut stream, _) = hub.add(Want::Scan {
542            options: RequestDeviceOptions::new()
543                .accept_all_devices()
544                .optional_manufacturer_data([APPLE]),
545            keep_repeated: true,
546        });
547
548        let mut advertisement = advertisement(&[]);
549        advertisement.manufacturer_data.insert(APPLE, vec![1, 2, 3]);
550        advertisement.manufacturer_data.insert(OTHER, vec![9, 9]);
551        hub.publish("aa", None, &advertisement);
552
553        let seen = next(&mut stream).expect("the device matches");
554        assert_eq!(
555            seen.advertisement.manufacturer_data.get(&APPLE),
556            Some(&vec![1, 2, 3]),
557            "what was asked for comes through"
558        );
559        assert!(
560            !seen.advertisement.manufacturer_data.contains_key(&OTHER),
561            "a company that was not asked for must not be reported"
562        );
563    }
564
565    /// The event carries three grant-filtered fields, not one: service UUIDs
566    /// and service data are narrowed the same way manufacturer data is.
567    #[test]
568    fn services_and_service_data_are_filtered_to_the_grant() {
569        const GRANTED: u16 = 0x180D; // heart rate
570        const PRIVATE: u16 = 0x180F; // battery, not asked for
571
572        let (granted, private) = (
573            BluetoothUuid::from_u16(GRANTED),
574            BluetoothUuid::from_u16(PRIVATE),
575        );
576
577        let hub = ScanHub::new();
578        let (_id, mut stream, _) = hub.add(Want::Scan {
579            options: RequestDeviceOptions::new()
580                .filter(DeviceFilter::new().service(granted).unwrap()),
581            keep_repeated: true,
582        });
583
584        let mut advertisement = advertisement(&[GRANTED, PRIVATE]);
585        advertisement.service_data.insert(granted, vec![0x50]);
586        advertisement.service_data.insert(private, vec![0x63]);
587        advertisement.solicited_service_uuids.push(private);
588        hub.publish("aa", None, &advertisement);
589
590        let seen = next(&mut stream).expect("the device matches on the granted service");
591        assert_eq!(
592            seen.advertisement.service_uuids,
593            vec![granted],
594            "an ungranted service must not be reported"
595        );
596        assert!(
597            seen.advertisement.solicited_service_uuids.is_empty(),
598            "nor solicited under one"
599        );
600        assert_eq!(seen.advertisement.service_data.len(), 1);
601        assert!(seen.advertisement.service_data.contains_key(&granted));
602    }
603
604    /// The chooser is the exception, and deliberately: it is what the user is
605    /// looking at while deciding, so it has to show what is on the air. There
606    /// is also no grant to filter by yet — granting is the thing in progress.
607    #[test]
608    fn the_chooser_sees_the_advertisement_whole() {
609        const APPLE: u16 = 0x004C;
610        let battery = BluetoothUuid::from_u16(0x180F);
611
612        let hub = ScanHub::new();
613        let (_id, mut stream, _) = hub.add(Want::Request(
614            RequestDeviceOptions::new().accept_all_devices(),
615        ));
616
617        let mut advertisement = advertisement(&[0x180F]);
618        advertisement.service_data.insert(battery, vec![0x63]);
619        advertisement.manufacturer_data.insert(APPLE, vec![0x09]);
620        advertisement
621            .manufacturer_data
622            .insert(0x00E0, vec![0x02, 0x15]);
623        hub.publish("aa", None, &advertisement);
624
625        let seen = next(&mut stream).expect("accept_all_devices matches");
626        assert_eq!(seen.advertisement.service_uuids, vec![battery]);
627        assert_eq!(seen.advertisement.service_data.len(), 1);
628        assert_eq!(
629            seen.advertisement.manufacturer_data.len(),
630            2,
631            "the picker needs to show what is actually being broadcast"
632        );
633    }
634
635    /// The blocklist is not part of any grant, so the chooser does not escape
636    /// it either. No permission makes reading a stranger's beacon acceptable.
637    #[test]
638    fn the_chooser_does_not_escape_the_manufacturer_blocklist() {
639        let hub = ScanHub::new();
640        let (_id, mut stream, _) = hub.add(Want::Request(
641            RequestDeviceOptions::new().accept_all_devices(),
642        ));
643
644        let mut advertisement = advertisement(&[]);
645        advertisement
646            .manufacturer_data
647            .insert(0x004C, vec![0x02, 0x15, 0xAB]);
648        hub.publish("aa", None, &advertisement);
649
650        let seen = next(&mut stream).expect("accept_all_devices matches");
651        assert!(seen.advertisement.manufacturer_data.is_empty());
652    }
653
654    /// Filtering happens after matching: a caller may find a device by a
655    /// service it is then not told about. Narrowing the match too would make
656    /// `optionalServices` a precondition for its own filter.
657    #[test]
658    fn a_device_still_matches_on_what_the_grant_hides() {
659        const SECRET: u16 = 0x180F;
660        let hub = ScanHub::new();
661        // Granted nothing, because an exclusion filter grants nothing.
662        let (_id, mut stream, _) = hub.add(Want::Scan {
663            options: RequestDeviceOptions::new().accept_all_devices(),
664            keep_repeated: true,
665        });
666
667        hub.publish("aa", None, &advertisement(&[SECRET]));
668        let seen = next(&mut stream).expect("the device is still reported");
669        assert!(
670            seen.advertisement.service_uuids.is_empty(),
671            "but without the service it was found by"
672        );
673    }
674
675    /// Granting a company does not grant its blocklisted data: the two filters
676    /// are independent, and the stricter one wins.
677    #[test]
678    fn a_grant_does_not_override_the_manufacturer_blocklist() {
679        const APPLE: u16 = 0x004C;
680
681        let hub = ScanHub::new();
682        let (_id, mut stream, _) = hub.add(Want::Scan {
683            options: RequestDeviceOptions::new()
684                .accept_all_devices()
685                .optional_manufacturer_data([APPLE]),
686            keep_repeated: true,
687        });
688
689        let mut advertisement = advertisement(&[]);
690        advertisement
691            .manufacturer_data
692            .insert(APPLE, vec![0x02, 0x15, 0xAB]); // an iBeacon frame
693        hub.publish("aa", None, &advertisement);
694
695        let seen = next(&mut stream).expect("the device still matches");
696        assert!(
697            seen.advertisement.manufacturer_data.is_empty(),
698            "asking for Apple's data must not yield a proximity beacon"
699        );
700    }
701
702    /// Asking for none means seeing none, rather than seeing everything.
703    #[test]
704    fn manufacturer_data_is_withheld_when_none_was_asked_for() {
705        let hub = ScanHub::new();
706        let (_id, mut stream, _) = hub.add(Want::Scan {
707            options: RequestDeviceOptions::new().accept_all_devices(),
708            keep_repeated: true,
709        });
710
711        let mut advertisement = advertisement(&[]);
712        advertisement.manufacturer_data.insert(0x004C, vec![1]);
713        hub.publish("aa", None, &advertisement);
714
715        let seen = next(&mut stream).expect("the device matches");
716        assert!(seen.advertisement.manufacturer_data.is_empty());
717    }
718
719    /// Two watchers of the same device can hold different grants, so the same
720    /// packet is reported differently to each.
721    #[test]
722    fn each_watcher_sees_only_its_own_grant() {
723        const APPLE: u16 = 0x004C;
724        const OTHER: u16 = 0x00E0;
725
726        let hub = ScanHub::new();
727        let (_a, mut permissive, _) = hub.add(Want::Scan {
728            options: RequestDeviceOptions::new()
729                .accept_all_devices()
730                .optional_manufacturer_data([APPLE, OTHER]),
731            keep_repeated: true,
732        });
733        let (_b, mut narrow, _) = hub.add(Want::Scan {
734            options: RequestDeviceOptions::new()
735                .accept_all_devices()
736                .optional_manufacturer_data([OTHER]),
737            keep_repeated: true,
738        });
739
740        let mut advertisement = advertisement(&[]);
741        advertisement.manufacturer_data.insert(APPLE, vec![1]);
742        advertisement.manufacturer_data.insert(OTHER, vec![2]);
743        hub.publish("aa", None, &advertisement);
744
745        assert_eq!(
746            next(&mut permissive)
747                .unwrap()
748                .advertisement
749                .manufacturer_data
750                .len(),
751            2
752        );
753        let narrow = next(&mut narrow).unwrap().advertisement.manufacturer_data;
754        assert_eq!(narrow.len(), 1);
755        assert!(narrow.contains_key(&OTHER));
756    }
757
758    #[test]
759    fn the_allowlist_still_decides_what_a_scan_may_see() {
760        // A scan is not a grant: `requestLEScan` filters do not widen access to
761        // services, they only choose which advertisements are reported.
762        let hub = ScanHub::new();
763        let (_id, mut stream, _) = hub.add(Want::Scan {
764            options: RequestDeviceOptions::new()
765                .filter(DeviceFilter::new().name("Sensor"))
766                .optional_service(services::BATTERY_SERVICE)
767                .unwrap(),
768            keep_repeated: true,
769        });
770        hub.publish("aa", Some("Sensor"), &advertisement(&[]));
771        assert!(next(&mut stream).is_some());
772        hub.publish("bb", Some("Other"), &advertisement(&[]));
773        assert!(next(&mut stream).is_none());
774    }
775}