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