script/dom/bluetooth/
bluetooth.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use bluetooth_traits::{BluetoothError, BluetoothRequest, GATTType};
6use bluetooth_traits::{BluetoothResponse, BluetoothResponseResult};
7use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted};
8use bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence};
9use bluetooth_traits::scanfilter::{RequestDeviceoptions, ServiceUUIDSequence};
10use crate::realms::{AlreadyInRealm, InRealm};
11use crate::conversions::Convert;
12use crate::dom::bindings::cell::{DomRefCell, Ref};
13use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothDataFilterInit;
14use crate::dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions};
15use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothLEScanFilterInit;
16use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor;
17use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServer_Binding::
18BluetoothRemoteGATTServerMethods;
19use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState};
20use crate::dom::bindings::codegen::UnionTypes::{ArrayBufferViewOrArrayBuffer, StringOrUnsignedLong};
21use crate::dom::bindings::error::Error::{self, Network, Security, Type};
22use crate::dom::bindings::error::Fallible;
23use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
24use crate::dom::bindings::reflector::{DomGlobal, DomObject, reflect_dom_object};
25use crate::dom::bindings::root::{Dom, DomRoot};
26use crate::dom::bindings::str::DOMString;
27use crate::dom::bluetoothdevice::BluetoothDevice;
28use crate::dom::bluetoothpermissionresult::BluetoothPermissionResult;
29use crate::dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID, UUID};
30use crate::dom::eventtarget::EventTarget;
31use crate::dom::globalscope::GlobalScope;
32use crate::dom::permissions::{descriptor_permission_state, PermissionAlgorithm};
33use crate::dom::promise::Promise;
34use crate::script_runtime::{CanGc, JSContext};
35use crate::task::TaskOnce;
36use dom_struct::dom_struct;
37use ipc_channel::ipc::{self, IpcSender};
38use ipc_channel::router::ROUTER;
39use js::conversions::ConversionResult;
40use js::jsapi::JSObject;
41use js::jsval::{ObjectValue, UndefinedValue};
42use profile_traits::ipc as ProfiledIpc;
43use std::collections::HashMap;
44use std::rc::Rc;
45use std::sync::{Arc, Mutex};
46
47const KEY_CONVERSION_ERROR: &str =
48    "This `manufacturerData` key can not be parsed as unsigned short:";
49const FILTER_EMPTY_ERROR: &str =
50    "'filters' member, if present, must be nonempty to find any devices.";
51const FILTER_ERROR: &str = "A filter must restrict the devices in some way.";
52const MANUFACTURER_DATA_ERROR: &str =
53    "'manufacturerData', if present, must be non-empty to filter devices.";
54const MASK_LENGTH_ERROR: &str = "`mask`, if present, must have the same length as `dataPrefix`.";
55// 248 is the maximum number of UTF-8 code units in a Bluetooth Device Name.
56const MAX_DEVICE_NAME_LENGTH: usize = 248;
57const NAME_PREFIX_ERROR: &str = "'namePrefix', if present, must be nonempty.";
58const NAME_TOO_LONG_ERROR: &str = "A device name can't be longer than 248 bytes.";
59const SERVICE_DATA_ERROR: &str = "'serviceData', if present, must be non-empty to filter devices.";
60const SERVICE_ERROR: &str = "'services', if present, must contain at least one service.";
61const OPTIONS_ERROR: &str = "Fields of 'options' conflict with each other.
62 Either 'acceptAllDevices' member must be true, or 'filters' member must be set to a value.";
63const BT_DESC_CONVERSION_ERROR: &str =
64    "Can't convert to an IDL value of type BluetoothPermissionDescriptor";
65
66#[derive(JSTraceable, MallocSizeOf)]
67#[allow(non_snake_case)]
68pub(crate) struct AllowedBluetoothDevice {
69    pub(crate) deviceId: DOMString,
70    pub(crate) mayUseGATT: bool,
71}
72
73#[derive(JSTraceable, MallocSizeOf)]
74pub(crate) struct BluetoothExtraPermissionData {
75    allowed_devices: DomRefCell<Vec<AllowedBluetoothDevice>>,
76}
77
78impl BluetoothExtraPermissionData {
79    pub(crate) fn new() -> BluetoothExtraPermissionData {
80        BluetoothExtraPermissionData {
81            allowed_devices: DomRefCell::new(Vec::new()),
82        }
83    }
84
85    pub(crate) fn add_new_allowed_device(&self, allowed_device: AllowedBluetoothDevice) {
86        self.allowed_devices.borrow_mut().push(allowed_device);
87    }
88
89    fn get_allowed_devices(&self) -> Ref<'_, Vec<AllowedBluetoothDevice>> {
90        self.allowed_devices.borrow()
91    }
92
93    pub(crate) fn allowed_devices_contains_id(&self, id: DOMString) -> bool {
94        self.allowed_devices
95            .borrow()
96            .iter()
97            .any(|d| d.deviceId == id)
98    }
99}
100
101impl Default for BluetoothExtraPermissionData {
102    fn default() -> Self {
103        Self::new()
104    }
105}
106
107struct BluetoothContext<T: AsyncBluetoothListener + DomObject> {
108    promise: Option<TrustedPromise>,
109    receiver: Trusted<T>,
110}
111
112pub(crate) trait AsyncBluetoothListener {
113    fn handle_response(&self, result: BluetoothResponse, promise: &Rc<Promise>, can_gc: CanGc);
114}
115
116impl<T> BluetoothContext<T>
117where
118    T: AsyncBluetoothListener + DomObject,
119{
120    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
121    fn response(&mut self, response: BluetoothResponseResult, can_gc: CanGc) {
122        let promise = self.promise.take().expect("bt promise is missing").root();
123
124        // JSAutoRealm needs to be manually made.
125        // Otherwise, Servo will crash.
126        match response {
127            Ok(response) => self
128                .receiver
129                .root()
130                .handle_response(response, &promise, can_gc),
131            // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
132            // Step 3 - 4.
133            Err(error) => promise.reject_error(error.convert(), can_gc),
134        }
135    }
136}
137
138// https://webbluetoothcg.github.io/web-bluetooth/#bluetooth
139#[dom_struct]
140pub(crate) struct Bluetooth {
141    eventtarget: EventTarget,
142    device_instance_map: DomRefCell<HashMap<String, Dom<BluetoothDevice>>>,
143}
144
145impl Bluetooth {
146    pub(crate) fn new_inherited() -> Bluetooth {
147        Bluetooth {
148            eventtarget: EventTarget::new_inherited(),
149            device_instance_map: DomRefCell::new(HashMap::new()),
150        }
151    }
152
153    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> DomRoot<Bluetooth> {
154        reflect_dom_object(Box::new(Bluetooth::new_inherited()), global, can_gc)
155    }
156
157    fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
158        self.global().as_window().bluetooth_thread()
159    }
160
161    pub(crate) fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
162        &self.device_instance_map
163    }
164
165    // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices
166    fn request_bluetooth_devices(
167        &self,
168        p: &Rc<Promise>,
169        filters: &Option<Vec<BluetoothLEScanFilterInit>>,
170        optional_services: &[BluetoothServiceUUID],
171        sender: IpcSender<BluetoothResponseResult>,
172        can_gc: CanGc,
173    ) {
174        // TODO: Step 1: Triggered by user activation.
175
176        // Step 2.2: There are no requiredServiceUUIDS, we scan for all devices.
177        let mut uuid_filters = vec![];
178
179        if let Some(filters) = filters {
180            // Step 2.1.
181            if filters.is_empty() {
182                p.reject_error(Type(FILTER_EMPTY_ERROR.to_owned()), can_gc);
183                return;
184            }
185
186            // Step 2.3: There are no requiredServiceUUIDS, we scan for all devices.
187
188            // Step 2.4.
189            for filter in filters {
190                // Step 2.4.1.
191                match canonicalize_filter(filter) {
192                    // Step 2.4.2.
193                    Ok(f) => uuid_filters.push(f),
194                    Err(e) => {
195                        p.reject_error(e, can_gc);
196                        return;
197                    },
198                }
199                // Step 2.4.3: There are no requiredServiceUUIDS, we scan for all devices.
200            }
201        }
202
203        let mut optional_services_uuids = vec![];
204        for opt_service in optional_services {
205            // Step 2.5 - 2.6.
206            let uuid = match BluetoothUUID::service(opt_service.clone()) {
207                Ok(u) => u.to_string(),
208                Err(e) => {
209                    p.reject_error(e, can_gc);
210                    return;
211                },
212            };
213
214            // Step 2.7.
215            // Note: What we are doing here, is adding the not blocklisted UUIDs to the result vector,
216            // instead of removing them from an already filled vector.
217            if !uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
218                optional_services_uuids.push(uuid);
219            }
220        }
221
222        let option = RequestDeviceoptions::new(
223            self.global().as_window().webview_id(),
224            BluetoothScanfilterSequence::new(uuid_filters),
225            ServiceUUIDSequence::new(optional_services_uuids),
226        );
227
228        // Step 4 - 5.
229        if let PermissionState::Denied =
230            descriptor_permission_state(PermissionName::Bluetooth, None)
231        {
232            return p.reject_error(Error::NotFound(None), can_gc);
233        }
234
235        // Note: Step 3, 6 - 8 are implemented in
236        // components/net/bluetooth_thread.rs in request_device function.
237        self.get_bluetooth_thread()
238            .send(BluetoothRequest::RequestDevice(option, sender))
239            .unwrap();
240    }
241}
242
243pub(crate) fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
244    promise: &Rc<Promise>,
245    receiver: &T,
246) -> IpcSender<BluetoothResponseResult> {
247    let (action_sender, action_receiver) = ipc::channel().unwrap();
248    let task_source = receiver
249        .global()
250        .task_manager()
251        .networking_task_source()
252        .to_sendable();
253    let context = Arc::new(Mutex::new(BluetoothContext {
254        promise: Some(TrustedPromise::new(promise.clone())),
255        receiver: Trusted::new(receiver),
256    }));
257    ROUTER.add_typed_route(
258        action_receiver,
259        Box::new(move |message| {
260            struct ListenerTask<T: AsyncBluetoothListener + DomObject> {
261                context: Arc<Mutex<BluetoothContext<T>>>,
262                action: BluetoothResponseResult,
263            }
264
265            impl<T> TaskOnce for ListenerTask<T>
266            where
267                T: AsyncBluetoothListener + DomObject,
268            {
269                fn run_once(self) {
270                    let mut context = self.context.lock().unwrap();
271                    context.response(self.action, CanGc::note());
272                }
273            }
274
275            let task = ListenerTask {
276                context: context.clone(),
277                action: message.unwrap(),
278            };
279
280            task_source.queue_unconditionally(task);
281        }),
282    );
283    action_sender
284}
285
286// https://webbluetoothcg.github.io/web-bluetooth/#getgattchildren
287#[allow(clippy::too_many_arguments)]
288pub(crate) fn get_gatt_children<T, F>(
289    attribute: &T,
290    single: bool,
291    uuid_canonicalizer: F,
292    uuid: Option<StringOrUnsignedLong>,
293    instance_id: String,
294    connected: bool,
295    child_type: GATTType,
296    can_gc: CanGc,
297) -> Rc<Promise>
298where
299    T: AsyncBluetoothListener + DomObject + 'static,
300    F: FnOnce(StringOrUnsignedLong) -> Fallible<UUID>,
301{
302    let in_realm_proof = AlreadyInRealm::assert::<crate::DomTypeHolder>();
303    let p = Promise::new_in_current_realm(InRealm::Already(&in_realm_proof), can_gc);
304
305    let result_uuid = if let Some(u) = uuid {
306        // Step 1.
307        let canonicalized = match uuid_canonicalizer(u) {
308            Ok(canonicalized_uuid) => canonicalized_uuid.to_string(),
309            Err(e) => {
310                p.reject_error(e, can_gc);
311                return p;
312            },
313        };
314        // Step 2.
315        if uuid_is_blocklisted(canonicalized.as_ref(), Blocklist::All) {
316            p.reject_error(Security, can_gc);
317            return p;
318        }
319        Some(canonicalized)
320    } else {
321        None
322    };
323
324    // Step 3 - 4.
325    if !connected {
326        p.reject_error(Network, can_gc);
327        return p;
328    }
329
330    // TODO: Step 5: Implement representedDevice internal slot for BluetoothDevice.
331
332    // Note: Steps 6 - 7 are implemented in components/bluetooth/lib.rs in get_descriptor function
333    // and in handle_response function.
334    let sender = response_async(&p, attribute);
335    attribute
336        .global()
337        .as_window()
338        .bluetooth_thread()
339        .send(BluetoothRequest::GetGATTChildren(
340            instance_id,
341            result_uuid,
342            single,
343            child_type,
344            sender,
345        ))
346        .unwrap();
347    p
348}
349
350// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothlescanfilterinit-canonicalizing
351fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<BluetoothScanfilter> {
352    // Step 1.
353    if filter.services.is_none() &&
354        filter.name.is_none() &&
355        filter.namePrefix.is_none() &&
356        filter.manufacturerData.is_none() &&
357        filter.serviceData.is_none()
358    {
359        return Err(Type(FILTER_ERROR.to_owned()));
360    }
361
362    // Step 2: There is no empty canonicalizedFilter member,
363    // we create a BluetoothScanfilter instance at the end of the function.
364
365    // Step 3.
366    let services_vec = match filter.services {
367        Some(ref services) => {
368            // Step 3.1.
369            if services.is_empty() {
370                return Err(Type(SERVICE_ERROR.to_owned()));
371            }
372
373            let mut services_vec = vec![];
374
375            for service in services {
376                // Step 3.2 - 3.3.
377                let uuid = BluetoothUUID::service(service.clone())?.to_string();
378
379                // Step 3.4.
380                if uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
381                    return Err(Security);
382                }
383
384                services_vec.push(uuid);
385            }
386            // Step 3.5.
387            services_vec
388        },
389        None => vec![],
390    };
391
392    // Step 4.
393    let name = match filter.name {
394        Some(ref name) => {
395            // Step 4.1.
396            // Note: DOMString::len() gives back the size in bytes.
397            if name.len() > MAX_DEVICE_NAME_LENGTH {
398                return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
399            }
400
401            // Step 4.2.
402            Some(name.to_string())
403        },
404        None => None,
405    };
406
407    // Step 5.
408    let name_prefix = match filter.namePrefix {
409        Some(ref name_prefix) => {
410            // Step 5.1.
411            if name_prefix.is_empty() {
412                return Err(Type(NAME_PREFIX_ERROR.to_owned()));
413            }
414            if name_prefix.len() > MAX_DEVICE_NAME_LENGTH {
415                return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
416            }
417
418            // Step 5.2.
419            name_prefix.to_string()
420        },
421        None => String::new(),
422    };
423
424    // Step 6 - 7.
425    let manufacturer_data = match filter.manufacturerData {
426        Some(ref manufacturer_data_map) => {
427            // Note: If manufacturer_data_map is empty, that means there are no key values in it.
428            if manufacturer_data_map.is_empty() {
429                return Err(Type(MANUFACTURER_DATA_ERROR.to_owned()));
430            }
431            let mut map = HashMap::new();
432            for (key, bdfi) in manufacturer_data_map.iter() {
433                // Step 7.1 - 7.2.
434                let manufacturer_id = match key.str().parse::<u16>() {
435                    Ok(id) => id,
436                    Err(err) => {
437                        return Err(Type(format!("{} {} {}", KEY_CONVERSION_ERROR, key, err)));
438                    },
439                };
440
441                // Step 7.3: No need to convert to IDL values since this is only used by native code.
442
443                // Step 7.4 - 7.5.
444                map.insert(
445                    manufacturer_id,
446                    canonicalize_bluetooth_data_filter_init(bdfi)?,
447                );
448            }
449            Some(map)
450        },
451        None => None,
452    };
453
454    // Step 8 - 9.
455    let service_data = match filter.serviceData {
456        Some(ref service_data_map) => {
457            // Note: If service_data_map is empty, that means there are no key values in it.
458            if service_data_map.is_empty() {
459                return Err(Type(SERVICE_DATA_ERROR.to_owned()));
460            }
461            let mut map = HashMap::new();
462            for (key, bdfi) in service_data_map.iter() {
463                let service_name = match key.str().parse::<u32>() {
464                    // Step 9.1.
465                    Ok(number) => StringOrUnsignedLong::UnsignedLong(number),
466                    // Step 9.2.
467                    _ => StringOrUnsignedLong::String(key.clone()),
468                };
469
470                // Step 9.3 - 9.4.
471                let service = BluetoothUUID::service(service_name)?.to_string();
472
473                // Step 9.5.
474                if uuid_is_blocklisted(service.as_ref(), Blocklist::All) {
475                    return Err(Security);
476                }
477
478                // Step 9.6: No need to convert to IDL values since this is only used by native code.
479
480                // Step 9.7 - 9.8.
481                map.insert(service, canonicalize_bluetooth_data_filter_init(bdfi)?);
482            }
483            Some(map)
484        },
485        None => None,
486    };
487
488    // Step 10.
489    Ok(BluetoothScanfilter::new(
490        name,
491        name_prefix,
492        services_vec,
493        manufacturer_data,
494        service_data,
495    ))
496}
497
498// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdatafilterinit-canonicalizing
499fn canonicalize_bluetooth_data_filter_init(
500    bdfi: &BluetoothDataFilterInit,
501) -> Fallible<(Vec<u8>, Vec<u8>)> {
502    // Step 1.
503    let data_prefix = match bdfi.dataPrefix {
504        Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref avb)) => avb.to_vec(),
505        Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref ab)) => ab.to_vec(),
506        None => vec![],
507    };
508
509    // Step 2.
510    // If no mask present, mask will be a sequence of 0xFF bytes the same length as dataPrefix.
511    // Masking dataPrefix with this, leaves dataPrefix untouched.
512    let mask = match bdfi.mask {
513        Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref avb)) => avb.to_vec(),
514        Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref ab)) => ab.to_vec(),
515        None => vec![0xFF; data_prefix.len()],
516    };
517
518    // Step 3.
519    if mask.len() != data_prefix.len() {
520        return Err(Type(MASK_LENGTH_ERROR.to_owned()));
521    }
522
523    // Step 4.
524    Ok((data_prefix, mask))
525}
526
527impl Convert<Error> for BluetoothError {
528    fn convert(self) -> Error {
529        match self {
530            BluetoothError::Type(message) => Error::Type(message),
531            BluetoothError::Network => Error::Network,
532            BluetoothError::NotFound => Error::NotFound(None),
533            BluetoothError::NotSupported => Error::NotSupported,
534            BluetoothError::Security => Error::Security,
535            BluetoothError::InvalidState => Error::InvalidState(None),
536        }
537    }
538}
539
540impl BluetoothMethods<crate::DomTypeHolder> for Bluetooth {
541    // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
542    fn RequestDevice(
543        &self,
544        option: &RequestDeviceOptions,
545        comp: InRealm,
546        can_gc: CanGc,
547    ) -> Rc<Promise> {
548        let p = Promise::new_in_current_realm(comp, can_gc);
549        // Step 1.
550        if (option.filters.is_some() && option.acceptAllDevices) ||
551            (option.filters.is_none() && !option.acceptAllDevices)
552        {
553            p.reject_error(Error::Type(OPTIONS_ERROR.to_owned()), can_gc);
554            return p;
555        }
556
557        // Step 2.
558        let sender = response_async(&p, self);
559        self.request_bluetooth_devices(
560            &p,
561            &option.filters,
562            &option.optionalServices,
563            sender,
564            can_gc,
565        );
566        // Note: Step 3 - 4. in response function, Step 5. in handle_response function.
567        p
568    }
569
570    // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-getavailability
571    fn GetAvailability(&self, comp: InRealm, can_gc: CanGc) -> Rc<Promise> {
572        let p = Promise::new_in_current_realm(comp, can_gc);
573        // Step 1. We did not override the method
574        // Step 2 - 3. in handle_response
575        let sender = response_async(&p, self);
576        self.get_bluetooth_thread()
577            .send(BluetoothRequest::GetAvailability(sender))
578            .unwrap();
579        p
580    }
581
582    // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-onavailabilitychanged
583    event_handler!(
584        availabilitychanged,
585        GetOnavailabilitychanged,
586        SetOnavailabilitychanged
587    );
588}
589
590impl AsyncBluetoothListener for Bluetooth {
591    fn handle_response(&self, response: BluetoothResponse, promise: &Rc<Promise>, can_gc: CanGc) {
592        match response {
593            // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices
594            // Step 11, 13 - 14.
595            BluetoothResponse::RequestDevice(device) => {
596                let mut device_instance_map = self.device_instance_map.borrow_mut();
597                if let Some(existing_device) = device_instance_map.get(&device.id.clone()) {
598                    return promise.resolve_native(&**existing_device, can_gc);
599                }
600                let bt_device = BluetoothDevice::new(
601                    &self.global(),
602                    DOMString::from(device.id.clone()),
603                    device.name.map(DOMString::from),
604                    self,
605                    can_gc,
606                );
607                device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device));
608
609                self.global()
610                    .as_window()
611                    .bluetooth_extra_permission_data()
612                    .add_new_allowed_device(AllowedBluetoothDevice {
613                        deviceId: DOMString::from(device.id),
614                        mayUseGATT: true,
615                    });
616                // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
617                // Step 5.
618                promise.resolve_native(&bt_device, can_gc);
619            },
620            // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-getavailability
621            // Step 2 - 3.
622            BluetoothResponse::GetAvailability(is_available) => {
623                promise.resolve_native(&is_available, can_gc);
624            },
625            _ => promise.reject_error(Error::Type("Something went wrong...".to_owned()), can_gc),
626        }
627    }
628}
629
630impl PermissionAlgorithm for Bluetooth {
631    type Descriptor = BluetoothPermissionDescriptor;
632    type Status = BluetoothPermissionResult;
633
634    fn create_descriptor(
635        cx: JSContext,
636        permission_descriptor_obj: *mut JSObject,
637        can_gc: CanGc,
638    ) -> Result<BluetoothPermissionDescriptor, Error> {
639        rooted!(in(*cx) let mut property = UndefinedValue());
640        property
641            .handle_mut()
642            .set(ObjectValue(permission_descriptor_obj));
643        match BluetoothPermissionDescriptor::new(cx, property.handle(), can_gc) {
644            Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
645            Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
646            Err(_) => Err(Error::Type(String::from(BT_DESC_CONVERSION_ERROR))),
647        }
648    }
649
650    // https://webbluetoothcg.github.io/web-bluetooth/#query-the-bluetooth-permission
651    fn permission_query(
652        _cx: JSContext,
653        promise: &Rc<Promise>,
654        descriptor: &BluetoothPermissionDescriptor,
655        status: &BluetoothPermissionResult,
656    ) {
657        // Step 1: We are not using the `global` variable.
658
659        // Step 2.
660        status.set_state(descriptor_permission_state(status.get_query(), None));
661
662        // Step 3.
663        if let PermissionState::Denied = status.get_state() {
664            status.set_devices(Vec::new());
665            return promise.resolve_native(status, CanGc::note());
666        }
667
668        // Step 4.
669        rooted_vec!(let mut matching_devices);
670
671        // Step 5.
672        let global = status.global();
673        let allowed_devices = global
674            .as_window()
675            .bluetooth_extra_permission_data()
676            .get_allowed_devices();
677
678        let bluetooth = status.get_bluetooth();
679        let device_map = bluetooth.get_device_map().borrow();
680
681        // Step 6.
682        for allowed_device in allowed_devices.iter() {
683            // Step 6.1.
684            if let Some(ref id) = descriptor.deviceId {
685                if &allowed_device.deviceId != id {
686                    continue;
687                }
688            }
689            let device_id = String::from(allowed_device.deviceId.str());
690
691            // Step 6.2.
692            if let Some(ref filters) = descriptor.filters {
693                let mut scan_filters: Vec<BluetoothScanfilter> = Vec::new();
694
695                // Step 6.2.1.
696                for filter in filters {
697                    match canonicalize_filter(filter) {
698                        Ok(f) => scan_filters.push(f),
699                        Err(error) => return promise.reject_error(error, CanGc::note()),
700                    }
701                }
702
703                // Step 6.2.2.
704                // Instead of creating an internal slot we send an ipc message to the Bluetooth thread
705                // to check if one of the filters matches.
706                let (sender, receiver) =
707                    ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap();
708                status
709                    .get_bluetooth_thread()
710                    .send(BluetoothRequest::MatchesFilter(
711                        device_id.clone(),
712                        BluetoothScanfilterSequence::new(scan_filters),
713                        sender,
714                    ))
715                    .unwrap();
716
717                match receiver.recv().unwrap() {
718                    Ok(true) => (),
719                    Ok(false) => continue,
720                    Err(error) => return promise.reject_error(error.convert(), CanGc::note()),
721                };
722            }
723
724            // Step 6.3.
725            // TODO: Implement this correctly, not just using device ids here.
726            // https://webbluetoothcg.github.io/web-bluetooth/#get-the-bluetoothdevice-representing
727            if let Some(device) = device_map.get(&device_id) {
728                matching_devices.push(Dom::from_ref(&**device));
729            }
730        }
731
732        // Step 7.
733        status.set_devices(matching_devices.drain(..).collect());
734
735        // https://w3c.github.io/permissions/#dom-permissions-query
736        // Step 7.
737        promise.resolve_native(status, CanGc::note());
738    }
739
740    // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission
741    fn permission_request(
742        _cx: JSContext,
743        promise: &Rc<Promise>,
744        descriptor: &BluetoothPermissionDescriptor,
745        status: &BluetoothPermissionResult,
746    ) {
747        // Step 1.
748        if descriptor.filters.is_some() == descriptor.acceptAllDevices {
749            return promise.reject_error(Error::Type(OPTIONS_ERROR.to_owned()), CanGc::note());
750        }
751
752        // Step 2.
753        let sender = response_async(promise, status);
754        let bluetooth = status.get_bluetooth();
755        bluetooth.request_bluetooth_devices(
756            promise,
757            &descriptor.filters,
758            &descriptor.optionalServices,
759            sender,
760            CanGc::note(),
761        );
762
763        // NOTE: Step 3. is in BluetoothPermissionResult's `handle_response` function.
764    }
765
766    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
767    // https://webbluetoothcg.github.io/web-bluetooth/#revoke-bluetooth-access
768    fn permission_revoke(
769        _descriptor: &BluetoothPermissionDescriptor,
770        status: &BluetoothPermissionResult,
771        can_gc: CanGc,
772    ) {
773        // Step 1.
774        let global = status.global();
775        let allowed_devices = global
776            .as_window()
777            .bluetooth_extra_permission_data()
778            .get_allowed_devices();
779        // Step 2.
780        let bluetooth = status.get_bluetooth();
781        let device_map = bluetooth.get_device_map().borrow();
782        for (id, device) in device_map.iter() {
783            let id = DOMString::from(id.clone());
784            // Step 2.1.
785            if allowed_devices.iter().any(|d| d.deviceId == id) &&
786                !device.is_represented_device_null()
787            {
788                // Note: We don't need to update the allowed_services,
789                // because we store it in the lower level
790                // where it is already up-to-date
791                continue;
792            }
793            // Step 2.2 - 2.4
794            let _ = device.get_gatt().Disconnect(can_gc);
795        }
796    }
797}