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            service_uuids: uuids.iter().map(|u| BluetoothUuid::from_u16(*u)).collect(),
359            ..Default::default()
360        }
361    }
362
363    fn requesting(service: u16) -> Want {
364        Want::Request(
365            RequestDeviceOptions::new().filter(
366                DeviceFilter::new()
367                    .service(BluetoothUuid::from_u16(service))
368                    .unwrap(),
369            ),
370        )
371    }
372
373    #[test]
374    fn the_first_watcher_starts_the_radio_and_the_last_stops_it() {
375        let hub = ScanHub::new();
376        let (first, _a, start) = hub.add(requesting(0x180F));
377        assert!(start, "the first watcher has to start the scan");
378        let (second, _b, _) = hub.add(requesting(0x180F));
379
380        assert!(!hub.remove(first), "another watcher still wants the scan");
381        assert!(hub.remove(second), "the last one stops it");
382        assert!(!hub.is_watching());
383    }
384
385    /// The case that motivated reference counting: a `requestDevice` used to
386    /// stop the radio on its way out, which would cancel a scan someone else
387    /// was still reading.
388    #[test]
389    fn a_finished_request_does_not_stop_somebody_elses_scan() {
390        let hub = ScanHub::new();
391        let (scan, mut stream, _) = hub.add(Want::Scan {
392            options: RequestDeviceOptions::new().accept_all_devices(),
393            keep_repeated: true,
394        });
395        let (request, _r, _) = hub.add(requesting(0x180F));
396
397        assert!(!hub.remove(request));
398        hub.publish("aa", Some("Sensor"), &advertisement(&[0x180F]));
399        assert!(next(&mut stream).is_some(), "the scan still runs");
400        assert!(hub.contains(scan));
401    }
402
403    #[test]
404    fn one_unfiltered_watcher_widens_the_radio_scan_for_everyone() {
405        let hub = ScanHub::new();
406        let (_a, _s, _) = hub.add(requesting(0x180F));
407        assert_eq!(
408            hub.scan_services(),
409            vec![BluetoothUuid::from_u16(0x180F)],
410            "a single service filter narrows the scan"
411        );
412
413        // `watchAdvertisements` names a device, so the radio cannot be filtered
414        // by service without risking hiding it.
415        let (_b, _t, restart) = hub.add(Want::Device {
416            id: "aa".into(),
417            grant: Grant::default(),
418        });
419        assert!(restart, "widening the filter has to restart the radio");
420        assert!(hub.scan_services().is_empty());
421    }
422
423    #[test]
424    fn filters_are_combined_not_intersected() {
425        let hub = ScanHub::new();
426        hub.add(requesting(0x180F));
427        hub.add(requesting(0x180D));
428        assert_eq!(
429            hub.scan_services(),
430            vec![
431                BluetoothUuid::from_u16(0x180D),
432                BluetoothUuid::from_u16(0x180F)
433            ],
434            "the radio must be at least as wide as the widest watcher"
435        );
436    }
437
438    #[test]
439    fn a_watcher_only_sees_what_its_own_filter_accepts() {
440        let hub = ScanHub::new();
441        let (_a, mut battery, _) = hub.add(requesting(0x180F));
442        let (_b, mut heart, _) = hub.add(requesting(0x180D));
443
444        hub.publish("aa", None, &advertisement(&[0x180F]));
445        assert!(next(&mut battery).is_some());
446        assert!(next(&mut heart).is_none(), "not this watcher's device");
447    }
448
449    #[test]
450    fn a_device_knows_whether_it_is_being_watched() {
451        let hub = ScanHub::new();
452        assert!(!hub.is_watching_device("mine"));
453
454        let (id, _stream, _) = hub.add(Want::Device {
455            id: "mine".into(),
456            grant: Grant::default(),
457        });
458        assert!(hub.is_watching_device("mine"));
459        // A scan is not a watch on any particular device.
460        assert!(!hub.is_watching_device("theirs"));
461
462        hub.remove(id);
463        assert!(!hub.is_watching_device("mine"), "the watch ended");
464    }
465
466    #[test]
467    fn watching_a_device_ignores_every_other_device() {
468        let hub = ScanHub::new();
469        let (_id, mut stream, _) = hub.add(Want::Device {
470            id: "mine".into(),
471            grant: Grant::default(),
472        });
473
474        hub.publish("theirs", Some("Someone Else"), &advertisement(&[]));
475        assert!(next(&mut stream).is_none());
476
477        hub.publish("mine", Some("Mine"), &advertisement(&[]));
478        let event = next(&mut stream).expect("the watched device");
479        assert_eq!(event.id, "mine");
480    }
481
482    #[test]
483    fn a_scan_without_keep_repeated_reports_each_device_once() {
484        let hub = ScanHub::new();
485        let (_id, mut stream, _) = hub.add(Want::Scan {
486            options: RequestDeviceOptions::new().accept_all_devices(),
487            keep_repeated: false,
488        });
489        assert!(!hub.wants_duplicates());
490
491        hub.publish("aa", None, &advertisement(&[]));
492        hub.publish("aa", None, &advertisement(&[]));
493        assert!(next(&mut stream).is_some());
494        assert!(next(&mut stream).is_none(), "the repeat is suppressed");
495
496        // A different device is still new.
497        hub.publish("bb", None, &advertisement(&[]));
498        assert!(next(&mut stream).is_some());
499    }
500
501    #[test]
502    fn a_chooser_gets_duplicates_so_its_rssi_stays_live() {
503        let hub = ScanHub::new();
504        let (_id, mut stream, _) = hub.add(requesting(0x180F));
505        assert!(hub.wants_duplicates());
506        hub.publish("aa", None, &advertisement(&[0x180F]));
507        hub.publish("aa", None, &advertisement(&[0x180F]));
508        assert!(next(&mut stream).is_some());
509        assert!(next(&mut stream).is_some(), "repeats are wanted");
510    }
511
512    /// A failed scan has to end the streams, or a chooser waits out its whole
513    /// window for traffic that will never arrive.
514    #[test]
515    fn closing_the_hub_ends_every_stream() {
516        let hub = ScanHub::new();
517        let (id, mut stream, _) = hub.add(requesting(0x180F));
518        hub.close_all();
519
520        assert!(!hub.is_watching());
521        assert!(!hub.contains(id));
522        // The sender is gone, so the stream is finished rather than merely idle.
523        assert!(stream.try_recv().is_none());
524    }
525
526    /// `optionalManufacturerData` is a permission, not a preference.
527    ///
528    /// The specification filters an advertisement event down to the companies
529    /// the caller asked for, so a site cannot learn what else a device is
530    /// broadcasting. This crate accepted the option and ignored it, which is
531    /// worse than not offering it: a caller could reasonably believe the data
532    /// they were handed had been filtered.
533    #[test]
534    fn manufacturer_data_is_filtered_to_what_was_granted() {
535        const APPLE: u16 = 0x004C;
536        const OTHER: u16 = 0x00E0;
537
538        let hub = ScanHub::new();
539        let (_id, mut stream, _) = hub.add(Want::Scan {
540            options: RequestDeviceOptions::new()
541                .accept_all_devices()
542                .optional_manufacturer_data([APPLE]),
543            keep_repeated: true,
544        });
545
546        let mut advertisement = advertisement(&[]);
547        advertisement.manufacturer_data.insert(APPLE, vec![1, 2, 3]);
548        advertisement.manufacturer_data.insert(OTHER, vec![9, 9]);
549        hub.publish("aa", None, &advertisement);
550
551        let seen = next(&mut stream).expect("the device matches");
552        assert_eq!(
553            seen.advertisement.manufacturer_data.get(&APPLE),
554            Some(&vec![1, 2, 3]),
555            "what was asked for comes through"
556        );
557        assert!(
558            !seen.advertisement.manufacturer_data.contains_key(&OTHER),
559            "a company that was not asked for must not be reported"
560        );
561    }
562
563    /// The event carries three grant-filtered fields, not one: service UUIDs
564    /// and service data are narrowed the same way manufacturer data is.
565    #[test]
566    fn services_and_service_data_are_filtered_to_the_grant() {
567        const GRANTED: u16 = 0x180D; // heart rate
568        const PRIVATE: u16 = 0x180F; // battery, not asked for
569
570        let (granted, private) = (
571            BluetoothUuid::from_u16(GRANTED),
572            BluetoothUuid::from_u16(PRIVATE),
573        );
574
575        let hub = ScanHub::new();
576        let (_id, mut stream, _) = hub.add(Want::Scan {
577            options: RequestDeviceOptions::new()
578                .filter(DeviceFilter::new().service(granted).unwrap()),
579            keep_repeated: true,
580        });
581
582        let mut advertisement = advertisement(&[GRANTED, PRIVATE]);
583        advertisement.service_data.insert(granted, vec![0x50]);
584        advertisement.service_data.insert(private, vec![0x63]);
585        advertisement.solicited_service_uuids.push(private);
586        hub.publish("aa", None, &advertisement);
587
588        let seen = next(&mut stream).expect("the device matches on the granted service");
589        assert_eq!(
590            seen.advertisement.service_uuids,
591            vec![granted],
592            "an ungranted service must not be reported"
593        );
594        assert!(
595            seen.advertisement.solicited_service_uuids.is_empty(),
596            "nor solicited under one"
597        );
598        assert_eq!(seen.advertisement.service_data.len(), 1);
599        assert!(seen.advertisement.service_data.contains_key(&granted));
600    }
601
602    /// The chooser is the exception, and deliberately: it is what the user is
603    /// looking at while deciding, so it has to show what is on the air. There
604    /// is also no grant to filter by yet — granting is the thing in progress.
605    #[test]
606    fn the_chooser_sees_the_advertisement_whole() {
607        const APPLE: u16 = 0x004C;
608        let battery = BluetoothUuid::from_u16(0x180F);
609
610        let hub = ScanHub::new();
611        let (_id, mut stream, _) = hub.add(Want::Request(
612            RequestDeviceOptions::new().accept_all_devices(),
613        ));
614
615        let mut advertisement = advertisement(&[0x180F]);
616        advertisement.service_data.insert(battery, vec![0x63]);
617        advertisement.manufacturer_data.insert(APPLE, vec![0x09]);
618        advertisement
619            .manufacturer_data
620            .insert(0x00E0, vec![0x02, 0x15]);
621        hub.publish("aa", None, &advertisement);
622
623        let seen = next(&mut stream).expect("accept_all_devices matches");
624        assert_eq!(seen.advertisement.service_uuids, vec![battery]);
625        assert_eq!(seen.advertisement.service_data.len(), 1);
626        assert_eq!(
627            seen.advertisement.manufacturer_data.len(),
628            2,
629            "the picker needs to show what is actually being broadcast"
630        );
631    }
632
633    /// The blocklist is not part of any grant, so the chooser does not escape
634    /// it either. No permission makes reading a stranger's beacon acceptable.
635    #[test]
636    fn the_chooser_does_not_escape_the_manufacturer_blocklist() {
637        let hub = ScanHub::new();
638        let (_id, mut stream, _) = hub.add(Want::Request(
639            RequestDeviceOptions::new().accept_all_devices(),
640        ));
641
642        let mut advertisement = advertisement(&[]);
643        advertisement
644            .manufacturer_data
645            .insert(0x004C, vec![0x02, 0x15, 0xAB]);
646        hub.publish("aa", None, &advertisement);
647
648        let seen = next(&mut stream).expect("accept_all_devices matches");
649        assert!(seen.advertisement.manufacturer_data.is_empty());
650    }
651
652    /// Filtering happens after matching: a caller may find a device by a
653    /// service it is then not told about. Narrowing the match too would make
654    /// `optionalServices` a precondition for its own filter.
655    #[test]
656    fn a_device_still_matches_on_what_the_grant_hides() {
657        const SECRET: u16 = 0x180F;
658        let hub = ScanHub::new();
659        // Granted nothing, because an exclusion filter grants nothing.
660        let (_id, mut stream, _) = hub.add(Want::Scan {
661            options: RequestDeviceOptions::new().accept_all_devices(),
662            keep_repeated: true,
663        });
664
665        hub.publish("aa", None, &advertisement(&[SECRET]));
666        let seen = next(&mut stream).expect("the device is still reported");
667        assert!(
668            seen.advertisement.service_uuids.is_empty(),
669            "but without the service it was found by"
670        );
671    }
672
673    /// Granting a company does not grant its blocklisted data: the two filters
674    /// are independent, and the stricter one wins.
675    #[test]
676    fn a_grant_does_not_override_the_manufacturer_blocklist() {
677        const APPLE: u16 = 0x004C;
678
679        let hub = ScanHub::new();
680        let (_id, mut stream, _) = hub.add(Want::Scan {
681            options: RequestDeviceOptions::new()
682                .accept_all_devices()
683                .optional_manufacturer_data([APPLE]),
684            keep_repeated: true,
685        });
686
687        let mut advertisement = advertisement(&[]);
688        advertisement
689            .manufacturer_data
690            .insert(APPLE, vec![0x02, 0x15, 0xAB]); // an iBeacon frame
691        hub.publish("aa", None, &advertisement);
692
693        let seen = next(&mut stream).expect("the device still matches");
694        assert!(
695            seen.advertisement.manufacturer_data.is_empty(),
696            "asking for Apple's data must not yield a proximity beacon"
697        );
698    }
699
700    /// Asking for none means seeing none, rather than seeing everything.
701    #[test]
702    fn manufacturer_data_is_withheld_when_none_was_asked_for() {
703        let hub = ScanHub::new();
704        let (_id, mut stream, _) = hub.add(Want::Scan {
705            options: RequestDeviceOptions::new().accept_all_devices(),
706            keep_repeated: true,
707        });
708
709        let mut advertisement = advertisement(&[]);
710        advertisement.manufacturer_data.insert(0x004C, vec![1]);
711        hub.publish("aa", None, &advertisement);
712
713        let seen = next(&mut stream).expect("the device matches");
714        assert!(seen.advertisement.manufacturer_data.is_empty());
715    }
716
717    /// Two watchers of the same device can hold different grants, so the same
718    /// packet is reported differently to each.
719    #[test]
720    fn each_watcher_sees_only_its_own_grant() {
721        const APPLE: u16 = 0x004C;
722        const OTHER: u16 = 0x00E0;
723
724        let hub = ScanHub::new();
725        let (_a, mut permissive, _) = hub.add(Want::Scan {
726            options: RequestDeviceOptions::new()
727                .accept_all_devices()
728                .optional_manufacturer_data([APPLE, OTHER]),
729            keep_repeated: true,
730        });
731        let (_b, mut narrow, _) = hub.add(Want::Scan {
732            options: RequestDeviceOptions::new()
733                .accept_all_devices()
734                .optional_manufacturer_data([OTHER]),
735            keep_repeated: true,
736        });
737
738        let mut advertisement = advertisement(&[]);
739        advertisement.manufacturer_data.insert(APPLE, vec![1]);
740        advertisement.manufacturer_data.insert(OTHER, vec![2]);
741        hub.publish("aa", None, &advertisement);
742
743        assert_eq!(
744            next(&mut permissive)
745                .unwrap()
746                .advertisement
747                .manufacturer_data
748                .len(),
749            2
750        );
751        let narrow = next(&mut narrow).unwrap().advertisement.manufacturer_data;
752        assert_eq!(narrow.len(), 1);
753        assert!(narrow.contains_key(&OTHER));
754    }
755
756    #[test]
757    fn the_allowlist_still_decides_what_a_scan_may_see() {
758        // A scan is not a grant: `requestLEScan` filters do not widen access to
759        // services, they only choose which advertisements are reported.
760        let hub = ScanHub::new();
761        let (_id, mut stream, _) = hub.add(Want::Scan {
762            options: RequestDeviceOptions::new()
763                .filter(DeviceFilter::new().name("Sensor"))
764                .optional_service(services::BATTERY_SERVICE)
765                .unwrap(),
766            keep_repeated: true,
767        });
768        hub.publish("aa", Some("Sensor"), &advertisement(&[]));
769        assert!(next(&mut stream).is_some());
770        hub.publish("bb", Some("Other"), &advertisement(&[]));
771        assert!(next(&mut stream).is_none());
772    }
773}