Skip to main content

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 script_bindings::reflector::{DomObject, reflect_dom_object_with_cx};
6use servo_base::generic_channel::{GenericCallback, GenericSender};
7use servo_bluetooth_traits::{BluetoothError, BluetoothRequest, GATTType};
8use servo_bluetooth_traits::{BluetoothResponse, BluetoothResponseResult};
9use servo_bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted};
10use servo_bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence};
11use servo_bluetooth_traits::scanfilter::{RequestDeviceoptions, ServiceUUIDSequence};
12use js::realm::CurrentRealm;
13use script_bindings::cformat;
14use js::context::JSContext;
15use crate::conversions::Convert;
16use script_bindings::cell::{Ref, DomRefCell};
17use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothDataFilterInit;
18use crate::dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions};
19use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothLEScanFilterInit;
20use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor;
21use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServer_Binding::
22BluetoothRemoteGATTServerMethods;
23use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState};
24use crate::dom::bindings::codegen::UnionTypes::{ArrayBufferViewOrArrayBuffer, StringOrUnsignedLong};
25use crate::dom::bindings::error::Error::{self, Network, Security, Type};
26use crate::dom::bindings::error::Fallible;
27use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
28use crate::dom::bindings::reflector::DomGlobal;
29use crate::dom::bindings::root::{Dom, DomRoot};
30use crate::dom::bindings::str::DOMString;
31use crate::dom::bluetoothdevice::BluetoothDevice;
32use crate::dom::bluetoothpermissionresult::BluetoothPermissionResult;
33use crate::dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID, UUID};
34use crate::dom::eventtarget::EventTarget;
35use crate::dom::globalscope::GlobalScope;
36use crate::dom::permissions::{descriptor_permission_state, PermissionAlgorithm};
37use crate::dom::promise::Promise;
38use crate::task::TaskOnce;
39use dom_struct::dom_struct;
40use js::conversions::ConversionResult;
41use js::jsapi::JSObject;
42use js::jsval::{ObjectValue, UndefinedValue};
43use profile_traits::{generic_channel};
44use std::collections::HashMap;
45use std::ffi::CStr;
46use std::rc::Rc;
47use std::sync::{Arc, Mutex};
48
49const KEY_CONVERSION_ERROR: &str =
50    "This `manufacturerData` key can not be parsed as unsigned short:";
51const FILTER_EMPTY_ERROR: &CStr =
52    c"'filters' member, if present, must be nonempty to find any devices.";
53const FILTER_ERROR: &CStr = c"A filter must restrict the devices in some way.";
54const MANUFACTURER_DATA_ERROR: &CStr =
55    c"'manufacturerData', if present, must be non-empty to filter devices.";
56const MASK_LENGTH_ERROR: &CStr = c"`mask`, if present, must have the same length as `dataPrefix`.";
57// 248 is the maximum number of UTF-8 code units in a Bluetooth Device Name.
58const MAX_DEVICE_NAME_LENGTH: usize = 248;
59const NAME_PREFIX_ERROR: &CStr = c"'namePrefix', if present, must be nonempty.";
60const NAME_TOO_LONG_ERROR: &CStr = c"A device name can't be longer than 248 bytes.";
61const SERVICE_DATA_ERROR: &CStr =
62    c"'serviceData', if present, must be non-empty to filter devices.";
63const SERVICE_ERROR: &CStr = c"'services', if present, must contain at least one service.";
64const OPTIONS_ERROR: &CStr = c"Fields of 'options' conflict with each other.
65 Either 'acceptAllDevices' member must be true, or 'filters' member must be set to a value.";
66const BT_DESC_CONVERSION_ERROR: &CStr =
67    c"Can't convert to an IDL value of type BluetoothPermissionDescriptor";
68
69#[derive(JSTraceable, MallocSizeOf)]
70#[expect(non_snake_case)]
71pub(crate) struct AllowedBluetoothDevice {
72    pub(crate) deviceId: DOMString,
73    pub(crate) mayUseGATT: bool,
74}
75
76#[derive(JSTraceable, MallocSizeOf)]
77pub(crate) struct BluetoothExtraPermissionData {
78    allowed_devices: DomRefCell<Vec<AllowedBluetoothDevice>>,
79}
80
81impl BluetoothExtraPermissionData {
82    pub(crate) fn new() -> BluetoothExtraPermissionData {
83        BluetoothExtraPermissionData {
84            allowed_devices: DomRefCell::new(Vec::new()),
85        }
86    }
87
88    pub(crate) fn add_new_allowed_device(&self, allowed_device: AllowedBluetoothDevice) {
89        self.allowed_devices.borrow_mut().push(allowed_device);
90    }
91
92    fn get_allowed_devices(&self) -> Ref<'_, Vec<AllowedBluetoothDevice>> {
93        self.allowed_devices.borrow()
94    }
95
96    pub(crate) fn allowed_devices_contains_id(&self, id: DOMString) -> bool {
97        self.allowed_devices
98            .borrow()
99            .iter()
100            .any(|d| d.deviceId == id)
101    }
102}
103
104impl Default for BluetoothExtraPermissionData {
105    fn default() -> Self {
106        Self::new()
107    }
108}
109
110struct BluetoothContext<T: AsyncBluetoothListener + DomObject> {
111    promise: Option<TrustedPromise>,
112    receiver: Trusted<T>,
113}
114
115pub(crate) trait AsyncBluetoothListener {
116    fn handle_response(&self, cx: &mut JSContext, result: BluetoothResponse, promise: &Rc<Promise>);
117}
118
119impl<T> BluetoothContext<T>
120where
121    T: AsyncBluetoothListener + DomObject,
122{
123    fn response(&mut self, cx: &mut JSContext, response: BluetoothResponseResult) {
124        let promise = self.promise.take().expect("bt promise is missing").root();
125
126        // JSAutoRealm needs to be manually made.
127        // Otherwise, Servo will crash.
128        match response {
129            Ok(response) => self.receiver.root().handle_response(cx, response, &promise),
130            // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
131            // Step 3 - 4.
132            Err(error) => promise.reject_error_with_cx(cx, error.convert()),
133        }
134    }
135}
136
137// https://webbluetoothcg.github.io/web-bluetooth/#bluetooth
138#[dom_struct]
139pub(crate) struct Bluetooth {
140    eventtarget: EventTarget,
141    device_instance_map: DomRefCell<HashMap<String, Dom<BluetoothDevice>>>,
142}
143
144impl Bluetooth {
145    pub(crate) fn new_inherited() -> Bluetooth {
146        Bluetooth {
147            eventtarget: EventTarget::new_inherited(),
148            device_instance_map: DomRefCell::new(HashMap::new()),
149        }
150    }
151
152    pub(crate) fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<Bluetooth> {
153        reflect_dom_object_with_cx(Box::new(Bluetooth::new_inherited()), global, cx)
154    }
155
156    fn get_bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
157        self.global().as_window().bluetooth_thread()
158    }
159
160    pub(crate) fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
161        &self.device_instance_map
162    }
163
164    /// <https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices>
165    fn request_bluetooth_devices(
166        &self,
167        cx: &mut JSContext,
168        p: &Rc<Promise>,
169        filters: &Option<Vec<BluetoothLEScanFilterInit>>,
170        optional_services: &[BluetoothServiceUUID],
171        sender: GenericCallback<BluetoothResponseResult>,
172    ) {
173        // TODO: Step 1: Triggered by user activation.
174
175        // Step 2.2: There are no requiredServiceUUIDS, we scan for all devices.
176        let mut uuid_filters = vec![];
177
178        if let Some(filters) = filters {
179            // Step 2.1.
180            if filters.is_empty() {
181                p.reject_error_with_cx(cx, Type(FILTER_EMPTY_ERROR.to_owned()));
182                return;
183            }
184
185            // Step 2.3: There are no requiredServiceUUIDS, we scan for all devices.
186
187            // Step 2.4.
188            for filter in filters {
189                // Step 2.4.1.
190                match canonicalize_filter(filter) {
191                    // Step 2.4.2.
192                    Ok(f) => uuid_filters.push(f),
193                    Err(e) => {
194                        p.reject_error_with_cx(cx, e);
195                        return;
196                    },
197                }
198                // Step 2.4.3: There are no requiredServiceUUIDS, we scan for all devices.
199            }
200        }
201
202        let mut optional_services_uuids = vec![];
203        for opt_service in optional_services {
204            // Step 2.5 - 2.6.
205            let uuid = match BluetoothUUID::service(opt_service.clone()) {
206                Ok(u) => String::from(u),
207                Err(e) => {
208                    p.reject_error_with_cx(cx, e);
209                    return;
210                },
211            };
212
213            // Step 2.7.
214            // Note: What we are doing here, is adding the not blocklisted UUIDs to the result vector,
215            // instead of removing them from an already filled vector.
216            if !uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
217                optional_services_uuids.push(uuid);
218            }
219        }
220
221        let option = RequestDeviceoptions::new(
222            self.global().as_window().webview_id(),
223            BluetoothScanfilterSequence::new(uuid_filters),
224            ServiceUUIDSequence::new(optional_services_uuids),
225        );
226
227        // Step 4 - 5.
228        if let PermissionState::Denied =
229            descriptor_permission_state(PermissionName::Bluetooth, None)
230        {
231            return p.reject_error_with_cx(cx, Error::NotFound(None));
232        }
233
234        // Note: Step 3, 6 - 8 are implemented in
235        // components/net/bluetooth_thread.rs in request_device function.
236        self.get_bluetooth_thread()
237            .send(BluetoothRequest::RequestDevice(option, sender))
238            .unwrap();
239    }
240}
241
242pub(crate) fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
243    promise: &Rc<Promise>,
244    receiver: &T,
245) -> GenericCallback<BluetoothResponseResult> {
246    let task_source = receiver
247        .global()
248        .task_manager()
249        .networking_task_source()
250        .to_sendable();
251    let context = Arc::new(Mutex::new(BluetoothContext {
252        promise: Some(TrustedPromise::new(promise.clone())),
253        receiver: Trusted::new(receiver),
254    }));
255    GenericCallback::new(move |message| {
256        struct ListenerTask<T: AsyncBluetoothListener + DomObject> {
257            context: Arc<Mutex<BluetoothContext<T>>>,
258            action: BluetoothResponseResult,
259        }
260
261        impl<T> TaskOnce for ListenerTask<T>
262        where
263            T: AsyncBluetoothListener + DomObject,
264        {
265            fn run_once(self, cx: &mut JSContext) {
266                let mut context = self.context.lock().unwrap();
267                context.response(cx, self.action);
268            }
269        }
270
271        let task = ListenerTask {
272            context: context.clone(),
273            action: message.unwrap(),
274        };
275
276        task_source.queue_unconditionally(task);
277    })
278    .expect("Could not create callback")
279}
280
281// https://webbluetoothcg.github.io/web-bluetooth/#getgattchildren
282#[allow(clippy::too_many_arguments)]
283pub(crate) fn get_gatt_children<T, F>(
284    cx: &mut CurrentRealm,
285    attribute: &T,
286    single: bool,
287    uuid_canonicalizer: F,
288    uuid: Option<StringOrUnsignedLong>,
289    instance_id: String,
290    connected: bool,
291    child_type: GATTType,
292) -> Rc<Promise>
293where
294    T: AsyncBluetoothListener + DomObject + 'static,
295    F: FnOnce(StringOrUnsignedLong) -> Fallible<UUID>,
296{
297    let p = Promise::new_in_realm(cx);
298
299    let result_uuid = if let Some(u) = uuid {
300        // Step 1.
301        let canonicalized = match uuid_canonicalizer(u) {
302            Ok(canonicalized_uuid) => String::from(canonicalized_uuid),
303            Err(e) => {
304                p.reject_error_with_cx(cx, e);
305                return p;
306            },
307        };
308        // Step 2.
309        if uuid_is_blocklisted(canonicalized.as_ref(), Blocklist::All) {
310            p.reject_error_with_cx(cx, Security(None));
311            return p;
312        }
313        Some(canonicalized)
314    } else {
315        None
316    };
317
318    // Step 3 - 4.
319    if !connected {
320        p.reject_error_with_cx(cx, Network(None));
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 = String::from(BluetoothUUID::service(service.clone())?);
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(cformat!("{} {} {}", 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 = String::from(BluetoothUUID::service(service_name)?);
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(cformat!("{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(&self, cx: &mut CurrentRealm, option: &RequestDeviceOptions) -> Rc<Promise> {
537        let p = Promise::new_in_realm(cx);
538        // Step 1.
539        if (option.filters.is_some() && option.acceptAllDevices) ||
540            (option.filters.is_none() && !option.acceptAllDevices)
541        {
542            p.reject_error_with_cx(cx, Error::Type(OPTIONS_ERROR.to_owned()));
543            return p;
544        }
545
546        // Step 2.
547        let sender = response_async(&p, self);
548        self.request_bluetooth_devices(cx, &p, &option.filters, &option.optionalServices, sender);
549        // Note: Step 3 - 4. in response function, Step 5. in handle_response function.
550        p
551    }
552
553    /// <https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-getavailability>
554    fn GetAvailability(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
555        let p = Promise::new_in_realm(cx);
556        // Step 1. We did not override the method
557        // Step 2 - 3. in handle_response
558        let sender = response_async(&p, self);
559        self.get_bluetooth_thread()
560            .send(BluetoothRequest::GetAvailability(sender))
561            .unwrap();
562        p
563    }
564
565    // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-onavailabilitychanged
566    event_handler!(
567        availabilitychanged,
568        GetOnavailabilitychanged,
569        SetOnavailabilitychanged
570    );
571}
572
573impl AsyncBluetoothListener for Bluetooth {
574    fn handle_response(
575        &self,
576        cx: &mut JSContext,
577        response: BluetoothResponse,
578        promise: &Rc<Promise>,
579    ) {
580        match response {
581            // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices
582            // Step 11, 13 - 14.
583            BluetoothResponse::RequestDevice(device) => {
584                let mut device_instance_map = self.device_instance_map.borrow_mut();
585                if let Some(existing_device) = device_instance_map.get(&device.id) {
586                    return promise.resolve_native_with_cx(cx, &**existing_device);
587                }
588                let bt_device = BluetoothDevice::new(
589                    cx,
590                    &self.global(),
591                    DOMString::from(device.id.clone()),
592                    device.name.map(DOMString::from),
593                    self,
594                );
595                device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device));
596
597                self.global()
598                    .as_window()
599                    .bluetooth_extra_permission_data()
600                    .add_new_allowed_device(AllowedBluetoothDevice {
601                        deviceId: DOMString::from(device.id),
602                        mayUseGATT: true,
603                    });
604                // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
605                // Step 5.
606                promise.resolve_native_with_cx(cx, &bt_device);
607            },
608            // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-getavailability
609            // Step 2 - 3.
610            BluetoothResponse::GetAvailability(is_available) => {
611                promise.resolve_native_with_cx(cx, &is_available);
612            },
613            _ => {
614                promise.reject_error_with_cx(cx, Error::Type(c"Something went wrong...".to_owned()))
615            },
616        }
617    }
618}
619
620impl PermissionAlgorithm for Bluetooth {
621    type Descriptor = BluetoothPermissionDescriptor;
622    type Status = BluetoothPermissionResult;
623
624    fn create_descriptor(
625        cx: &mut JSContext,
626        permission_descriptor_obj: *mut JSObject,
627    ) -> Result<BluetoothPermissionDescriptor, Error> {
628        rooted!(&in(cx) let mut property = UndefinedValue());
629        property
630            .handle_mut()
631            .set(ObjectValue(permission_descriptor_obj));
632        match BluetoothPermissionDescriptor::new(cx, property.handle()) {
633            Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
634            Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
635            Err(_) => Err(Error::Type(BT_DESC_CONVERSION_ERROR.into())),
636        }
637    }
638
639    /// <https://webbluetoothcg.github.io/web-bluetooth/#query-the-bluetooth-permission>
640    fn permission_query(
641        cx: &mut JSContext,
642        promise: &Rc<Promise>,
643        descriptor: &BluetoothPermissionDescriptor,
644        status: &BluetoothPermissionResult,
645    ) {
646        // Step 1: We are not using the `global` variable.
647
648        // Step 2.
649        status.set_state(descriptor_permission_state(status.get_query(), None));
650
651        // Step 3.
652        if let PermissionState::Denied = status.get_state() {
653            status.set_devices(Vec::new());
654            return promise.resolve_native_with_cx(cx, status);
655        }
656
657        // Step 4.
658        rooted_vec!(let mut matching_devices);
659
660        // Step 5.
661        let global = status.global();
662        let allowed_devices = global
663            .as_window()
664            .bluetooth_extra_permission_data()
665            .get_allowed_devices();
666
667        let bluetooth = status.get_bluetooth(cx);
668        let device_map = bluetooth.get_device_map().borrow();
669
670        // Step 6.
671        for allowed_device in allowed_devices.iter() {
672            // Step 6.1.
673            if let Some(ref id) = descriptor.deviceId &&
674                &allowed_device.deviceId != id
675            {
676                continue;
677            }
678            let device_id = String::from(allowed_device.deviceId.str());
679
680            // Step 6.2.
681            if let Some(ref filters) = descriptor.filters {
682                let mut scan_filters: Vec<BluetoothScanfilter> = Vec::new();
683
684                // Step 6.2.1.
685                for filter in filters {
686                    match canonicalize_filter(filter) {
687                        Ok(f) => scan_filters.push(f),
688                        Err(error) => return promise.reject_error_with_cx(cx, error),
689                    }
690                }
691
692                // Step 6.2.2.
693                // Instead of creating an internal slot we send an ipc message to the Bluetooth thread
694                // to check if one of the filters matches.
695                let (sender, receiver) =
696                    generic_channel::channel(global.time_profiler_chan().clone()).unwrap();
697                status
698                    .get_bluetooth_thread()
699                    .send(BluetoothRequest::MatchesFilter(
700                        device_id.clone(),
701                        BluetoothScanfilterSequence::new(scan_filters),
702                        sender,
703                    ))
704                    .unwrap();
705
706                match receiver.recv().unwrap() {
707                    Ok(true) => (),
708                    Ok(false) => continue,
709                    Err(error) => return promise.reject_error_with_cx(cx, error.convert()),
710                };
711            }
712
713            // Step 6.3.
714            // TODO: Implement this correctly, not just using device ids here.
715            // https://webbluetoothcg.github.io/web-bluetooth/#get-the-bluetoothdevice-representing
716            if let Some(device) = device_map.get(&device_id) {
717                matching_devices.push(Dom::from_ref(&**device));
718            }
719        }
720
721        // Step 7.
722        status.set_devices(std::mem::take(&mut matching_devices));
723
724        // https://w3c.github.io/permissions/#dom-permissions-query
725        // Step 7.
726        promise.resolve_native_with_cx(cx, status);
727    }
728
729    /// <https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission>
730    fn permission_request(
731        cx: &mut JSContext,
732        promise: &Rc<Promise>,
733        descriptor: &BluetoothPermissionDescriptor,
734        status: &BluetoothPermissionResult,
735    ) {
736        // Step 1.
737        if descriptor.filters.is_some() == descriptor.acceptAllDevices {
738            return promise.reject_error_with_cx(cx, Error::Type(OPTIONS_ERROR.to_owned()));
739        }
740
741        // Step 2.
742        let sender = response_async(promise, status);
743        let bluetooth = status.get_bluetooth(cx);
744        bluetooth.request_bluetooth_devices(
745            cx,
746            promise,
747            &descriptor.filters,
748            &descriptor.optionalServices,
749            sender,
750        );
751
752        // NOTE: Step 3. is in BluetoothPermissionResult's `handle_response` function.
753    }
754
755    /// <https://webbluetoothcg.github.io/web-bluetooth/#revoke-bluetooth-access>
756    fn permission_revoke(
757        cx: &mut JSContext,
758        _descriptor: &BluetoothPermissionDescriptor,
759        status: &BluetoothPermissionResult,
760    ) {
761        // Step 1.
762        let global = status.global();
763        let allowed_devices = global
764            .as_window()
765            .bluetooth_extra_permission_data()
766            .get_allowed_devices();
767        // Step 2.
768        let bluetooth = status.get_bluetooth(cx);
769        let device_map = bluetooth.get_device_map().borrow();
770        for (id, device) in device_map.iter() {
771            let id = DOMString::from(id.clone());
772            // Step 2.1.
773            if allowed_devices.iter().any(|d| d.deviceId == id) &&
774                !device.is_represented_device_null()
775            {
776                // Note: We don't need to update the allowed_services,
777                // because we store it in the lower level
778                // where it is already up-to-date
779                continue;
780            }
781            // Step 2.2 - 2.4
782            let _ = device.get_gatt(cx).Disconnect(cx);
783        }
784    }
785}