1use js::gc::HandleValue;
6use script_bindings::reflector::{DomObject, reflect_dom_object_with_cx};
7use servo_base::generic_channel::{GenericCallback, GenericSender};
8use servo_base::text::Utf8CodeUnits;
9use servo_bluetooth_traits::{BluetoothError, BluetoothRequest, GATTType};
10use servo_bluetooth_traits::{BluetoothResponse, BluetoothResponseResult};
11use servo_bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted};
12use servo_bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence};
13use servo_bluetooth_traits::scanfilter::{RequestDeviceoptions, ServiceUUIDSequence};
14use js::realm::CurrentRealm;
15use script_bindings::cformat;
16use js::context::JSContext;
17use crate::conversions::Convert;
18use script_bindings::cell::{Ref, DomRefCell};
19use crate::dom::bindings::buffer_source::get_buffer_source_copy;
20use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothDataFilterInit;
21use crate::dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions};
22use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothLEScanFilterInit;
23use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor;
24use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServer_Binding::
25BluetoothRemoteGATTServerMethods;
26use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState};
27use crate::dom::bindings::codegen::UnionTypes::StringOrUnsignedLong;
28use crate::dom::bindings::error::Error::{self, Network, Security, Type};
29use crate::dom::bindings::error::Fallible;
30use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
31use crate::dom::bindings::reflector::DomGlobal;
32use crate::dom::bindings::root::{Dom, DomRoot};
33use crate::dom::bindings::str::DOMString;
34use crate::dom::bluetoothdevice::BluetoothDevice;
35use crate::dom::bluetoothpermissionresult::BluetoothPermissionResult;
36use crate::dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID, UUID};
37use crate::dom::eventtarget::EventTarget;
38use crate::dom::globalscope::GlobalScope;
39use crate::dom::permissions::{descriptor_permission_state, PermissionAlgorithm};
40use crate::dom::promise::{Promise, RootedPromise};
41use crate::tasks::task::TaskOnce;
42use dom_struct::dom_struct;
43use js::conversions::ConversionResult;
44use profile_traits::{generic_channel};
45use std::collections::HashMap;
46use std::ffi::CStr;
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`.";
57const MAX_DEVICE_NAME_LENGTH: Utf8CodeUnits = Utf8CodeUnits(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(
117 &self,
118 cx: &mut JSContext,
119 result: BluetoothResponse,
120 promise: &RootedPromise,
121 );
122}
123
124impl<T> BluetoothContext<T>
125where
126 T: AsyncBluetoothListener + DomObject,
127{
128 fn response(&mut self, cx: &mut JSContext, response: BluetoothResponseResult) {
129 let promise = self
130 .promise
131 .take()
132 .expect("Bluetooth promise is missing")
133 .root(cx);
134
135 match response {
138 Ok(response) => self.receiver.root().handle_response(cx, response, &promise),
139 Err(error) => promise.reject_error(cx, error.convert()),
142 }
143 }
144}
145
146#[dom_struct]
148pub(crate) struct Bluetooth {
149 eventtarget: EventTarget,
150 device_instance_map: DomRefCell<HashMap<String, Dom<BluetoothDevice>>>,
151}
152
153impl Bluetooth {
154 pub(crate) fn new_inherited() -> Bluetooth {
155 Bluetooth {
156 eventtarget: EventTarget::new_inherited(),
157 device_instance_map: DomRefCell::new(HashMap::new()),
158 }
159 }
160
161 pub(crate) fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<Bluetooth> {
162 reflect_dom_object_with_cx(Box::new(Bluetooth::new_inherited()), global, cx)
163 }
164
165 fn get_bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
166 self.global().as_window().bluetooth_thread()
167 }
168
169 pub(crate) fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
170 &self.device_instance_map
171 }
172
173 fn request_bluetooth_devices(
175 &self,
176 cx: &mut JSContext,
177 p: &RootedPromise,
178 filters: &Option<Vec<BluetoothLEScanFilterInit>>,
179 optional_services: &[BluetoothServiceUUID],
180 sender: GenericCallback<BluetoothResponseResult>,
181 ) {
182 let mut uuid_filters = vec![];
186
187 if let Some(filters) = filters {
188 if filters.is_empty() {
190 p.reject_error(cx, Type(FILTER_EMPTY_ERROR.to_owned()));
191 return;
192 }
193
194 for filter in filters {
198 match canonicalize_filter(filter) {
200 Ok(f) => uuid_filters.push(f),
202 Err(e) => {
203 p.reject_error(cx, e);
204 return;
205 },
206 }
207 }
209 }
210
211 let mut optional_services_uuids = vec![];
212 for opt_service in optional_services {
213 let uuid = match BluetoothUUID::service(opt_service.clone()) {
215 Ok(u) => String::from(u),
216 Err(e) => {
217 p.reject_error(cx, e);
218 return;
219 },
220 };
221
222 if !uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
226 optional_services_uuids.push(uuid);
227 }
228 }
229
230 let option = RequestDeviceoptions::new(
231 self.global().as_window().webview_id(),
232 BluetoothScanfilterSequence::new(uuid_filters),
233 ServiceUUIDSequence::new(optional_services_uuids),
234 );
235
236 if let PermissionState::Denied =
238 descriptor_permission_state(PermissionName::Bluetooth, None)
239 {
240 return p.reject_error(cx, Error::NotFound(None));
241 }
242
243 self.get_bluetooth_thread()
246 .send(BluetoothRequest::RequestDevice(option, sender))
247 .unwrap();
248 }
249}
250
251pub(crate) fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
252 promise: &RootedPromise,
253 receiver: &T,
254) -> GenericCallback<BluetoothResponseResult> {
255 let task_source = receiver
256 .global()
257 .task_manager()
258 .networking_task_source()
259 .to_sendable();
260 let context = Arc::new(Mutex::new(BluetoothContext {
261 promise: Some(TrustedPromise::from(promise)),
262 receiver: Trusted::new(receiver),
263 }));
264 GenericCallback::new(move |message| {
265 struct ListenerTask<T: AsyncBluetoothListener + DomObject> {
266 context: Arc<Mutex<BluetoothContext<T>>>,
267 action: BluetoothResponseResult,
268 }
269
270 impl<T> TaskOnce for ListenerTask<T>
271 where
272 T: AsyncBluetoothListener + DomObject,
273 {
274 fn run_once(self, cx: &mut JSContext) {
275 let mut context = self.context.lock().unwrap();
276 context.response(cx, self.action);
277 }
278 }
279
280 let task = ListenerTask {
281 context: context.clone(),
282 action: message.unwrap(),
283 };
284
285 task_source.queue_unconditionally(task);
286 })
287 .expect("Could not create callback")
288}
289
290#[allow(clippy::too_many_arguments)]
292pub(crate) fn get_gatt_children<T, F>(
293 cx: &mut CurrentRealm,
294 attribute: &T,
295 single: bool,
296 uuid_canonicalizer: F,
297 uuid: Option<StringOrUnsignedLong>,
298 instance_id: String,
299 connected: bool,
300 child_type: GATTType,
301) -> RootedPromise
302where
303 T: AsyncBluetoothListener + DomObject + 'static,
304 F: FnOnce(StringOrUnsignedLong) -> Fallible<UUID>,
305{
306 let p = Promise::new_in_realm_rooted(cx);
307
308 let result_uuid = if let Some(u) = uuid {
309 let canonicalized = match uuid_canonicalizer(u) {
311 Ok(canonicalized_uuid) => String::from(canonicalized_uuid),
312 Err(e) => {
313 p.reject_error(cx, e);
314 return p;
315 },
316 };
317 if uuid_is_blocklisted(canonicalized.as_ref(), Blocklist::All) {
319 p.reject_error(cx, Security(None));
320 return p;
321 }
322 Some(canonicalized)
323 } else {
324 None
325 };
326
327 if !connected {
329 p.reject_error(cx, Network(None));
330 return p;
331 }
332
333 let sender = response_async(&p, attribute);
338 attribute
339 .global()
340 .as_window()
341 .bluetooth_thread()
342 .send(BluetoothRequest::GetGATTChildren(
343 instance_id,
344 result_uuid,
345 single,
346 child_type,
347 sender,
348 ))
349 .unwrap();
350 p
351}
352
353fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<BluetoothScanfilter> {
355 if filter.services.is_none() &&
357 filter.name.is_none() &&
358 filter.namePrefix.is_none() &&
359 filter.manufacturerData.is_none() &&
360 filter.serviceData.is_none()
361 {
362 return Err(Type(FILTER_ERROR.to_owned()));
363 }
364
365 let services_vec = match filter.services {
370 Some(ref services) => {
371 if services.is_empty() {
373 return Err(Type(SERVICE_ERROR.to_owned()));
374 }
375
376 let mut services_vec = vec![];
377
378 for service in services {
379 let uuid = String::from(BluetoothUUID::service(service.clone())?);
381
382 if uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
384 return Err(Security(None));
385 }
386
387 services_vec.push(uuid);
388 }
389 services_vec
391 },
392 None => vec![],
393 };
394
395 let name = match filter.name {
397 Some(ref name) => {
398 if name.len_utf8() > MAX_DEVICE_NAME_LENGTH {
400 return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
401 }
402
403 Some(name.to_string())
405 },
406 None => None,
407 };
408
409 let name_prefix = match filter.namePrefix {
411 Some(ref name_prefix) => {
412 if name_prefix.is_empty() {
414 return Err(Type(NAME_PREFIX_ERROR.to_owned()));
415 }
416 if name_prefix.len_utf8() > MAX_DEVICE_NAME_LENGTH {
417 return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
418 }
419
420 name_prefix.to_string()
422 },
423 None => String::new(),
424 };
425
426 let manufacturer_data = match filter.manufacturerData {
428 Some(ref manufacturer_data_map) => {
429 if manufacturer_data_map.is_empty() {
431 return Err(Type(MANUFACTURER_DATA_ERROR.to_owned()));
432 }
433 let mut map = HashMap::new();
434 for (key, bdfi) in manufacturer_data_map.iter() {
435 let manufacturer_id = match key.str().parse::<u16>() {
437 Ok(id) => id,
438 Err(err) => {
439 return Err(Type(cformat!("{} {} {}", KEY_CONVERSION_ERROR, key, err)));
440 },
441 };
442
443 map.insert(
447 manufacturer_id,
448 canonicalize_bluetooth_data_filter_init(bdfi)?,
449 );
450 }
451 Some(map)
452 },
453 None => None,
454 };
455
456 let service_data = match filter.serviceData {
458 Some(ref service_data_map) => {
459 if service_data_map.is_empty() {
461 return Err(Type(SERVICE_DATA_ERROR.to_owned()));
462 }
463 let mut map = HashMap::new();
464 for (key, bdfi) in service_data_map.iter() {
465 let service_name = match key.str().parse::<u32>() {
466 Ok(number) => StringOrUnsignedLong::UnsignedLong(number),
468 _ => StringOrUnsignedLong::String(key.clone()),
470 };
471
472 let service = String::from(BluetoothUUID::service(service_name)?);
474
475 if uuid_is_blocklisted(service.as_ref(), Blocklist::All) {
477 return Err(Security(None));
478 }
479
480 map.insert(service, canonicalize_bluetooth_data_filter_init(bdfi)?);
484 }
485 Some(map)
486 },
487 None => None,
488 };
489
490 Ok(BluetoothScanfilter::new(
492 name,
493 name_prefix,
494 services_vec,
495 manufacturer_data,
496 service_data,
497 ))
498}
499
500fn canonicalize_bluetooth_data_filter_init(
502 bdfi: &BluetoothDataFilterInit,
503) -> Fallible<(Vec<u8>, Vec<u8>)> {
504 let data_prefix = match &bdfi.dataPrefix {
506 Some(buffer_source) => get_buffer_source_copy(buffer_source.into()),
507 None => vec![],
508 };
509
510 let mask = match &bdfi.mask {
514 Some(buffer_source) => get_buffer_source_copy(buffer_source.into()),
515 None => vec![0xFF; data_prefix.len()],
516 };
517
518 if mask.len() != data_prefix.len() {
520 return Err(Type(MASK_LENGTH_ERROR.to_owned()));
521 }
522
523 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(cformat!("{message}")),
531 BluetoothError::Network => Error::Network(None),
532 BluetoothError::NotFound => Error::NotFound(None),
533 BluetoothError::NotSupported => Error::NotSupported(None),
534 BluetoothError::Security => Error::Security(None),
535 BluetoothError::InvalidState => Error::InvalidState(None),
536 }
537 }
538}
539
540impl BluetoothMethods<crate::DomTypeHolder> for Bluetooth {
541 fn RequestDevice(&self, cx: &mut CurrentRealm, option: &RequestDeviceOptions) -> RootedPromise {
543 let p = Promise::new_in_realm_rooted(cx);
544 if (option.filters.is_some() && option.acceptAllDevices) ||
546 (option.filters.is_none() && !option.acceptAllDevices)
547 {
548 p.reject_error(cx, Error::Type(OPTIONS_ERROR.to_owned()));
549 return p;
550 }
551
552 let sender = response_async(&p, self);
554 self.request_bluetooth_devices(cx, &p, &option.filters, &option.optionalServices, sender);
555 p
557 }
558
559 fn GetAvailability(&self, cx: &mut CurrentRealm) -> RootedPromise {
561 let p = Promise::new_in_realm_rooted(cx);
562 let sender = response_async(&p, self);
565 self.get_bluetooth_thread()
566 .send(BluetoothRequest::GetAvailability(sender))
567 .unwrap();
568 p
569 }
570
571 event_handler!(
573 availabilitychanged,
574 GetOnavailabilitychanged,
575 SetOnavailabilitychanged
576 );
577}
578
579impl AsyncBluetoothListener for Bluetooth {
580 fn handle_response(
581 &self,
582 cx: &mut JSContext,
583 response: BluetoothResponse,
584 promise: &RootedPromise,
585 ) {
586 match response {
587 BluetoothResponse::RequestDevice(device) => {
590 {
591 let device_instance_map = self.device_instance_map.borrow();
592 if let Some(existing_device) = device_instance_map.get(&device.id) {
593 return promise.resolve_native(cx, &**existing_device);
594 }
595 }
596 let bt_device = BluetoothDevice::new(
597 cx,
598 &self.global(),
599 DOMString::from(device.id.clone()),
600 device.name.map(DOMString::from),
601 self,
602 );
603 self.device_instance_map
604 .borrow_mut()
605 .insert(device.id.clone(), Dom::from_ref(&bt_device));
606
607 self.global()
608 .as_window()
609 .bluetooth_extra_permission_data()
610 .add_new_allowed_device(AllowedBluetoothDevice {
611 deviceId: DOMString::from(device.id),
612 mayUseGATT: true,
613 });
614 promise.resolve_native(cx, &bt_device);
617 },
618 BluetoothResponse::GetAvailability(is_available) => {
621 promise.resolve_native(cx, &is_available);
622 },
623 _ => promise.reject_error(cx, Error::Type(c"Something went wrong...".to_owned())),
624 }
625 }
626}
627
628impl PermissionAlgorithm for Bluetooth {
629 type Descriptor = BluetoothPermissionDescriptor;
630 type Status = BluetoothPermissionResult;
631
632 fn create_descriptor(
633 cx: &mut JSContext,
634 permission_descriptor_obj: HandleValue,
635 ) -> Result<BluetoothPermissionDescriptor, Error> {
636 match BluetoothPermissionDescriptor::new(cx, permission_descriptor_obj) {
637 Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
638 Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
639 Err(_) => Err(Error::Type(BT_DESC_CONVERSION_ERROR.into())),
640 }
641 }
642
643 fn permission_query(
645 cx: &mut JSContext,
646 promise: &RootedPromise,
647 descriptor: &BluetoothPermissionDescriptor,
648 status: &BluetoothPermissionResult,
649 ) {
650 status.set_state(descriptor_permission_state(status.get_query(), None));
654
655 if let PermissionState::Denied = status.get_state() {
657 status.set_devices(Vec::new());
658 return promise.resolve_native(cx, status);
659 }
660
661 rooted_vec!(let mut matching_devices);
663
664 let global = status.global();
666 let allowed_devices = global
667 .as_window()
668 .bluetooth_extra_permission_data()
669 .get_allowed_devices();
670
671 let bluetooth = status.get_bluetooth(cx);
672 let device_map = bluetooth.get_device_map().borrow();
673
674 for allowed_device in allowed_devices.iter() {
676 if let Some(ref id) = descriptor.deviceId &&
678 &allowed_device.deviceId != id
679 {
680 continue;
681 }
682 let device_id = String::from(allowed_device.deviceId.str());
683
684 if let Some(ref filters) = descriptor.filters {
686 let mut scan_filters: Vec<BluetoothScanfilter> = Vec::new();
687
688 for filter in filters {
690 match canonicalize_filter(filter) {
691 Ok(f) => scan_filters.push(f),
692 Err(error) => return promise.reject_error(cx, error),
693 }
694 }
695
696 let (sender, receiver) =
700 generic_channel::channel(global.time_profiler_chan().clone()).unwrap();
701 status
702 .get_bluetooth_thread()
703 .send(BluetoothRequest::MatchesFilter(
704 device_id.clone(),
705 BluetoothScanfilterSequence::new(scan_filters),
706 sender,
707 ))
708 .unwrap();
709
710 match receiver.recv().unwrap() {
711 Ok(true) => (),
712 Ok(false) => continue,
713 Err(error) => return promise.reject_error(cx, error.convert()),
714 };
715 }
716
717 if let Some(device) = device_map.get(&device_id) {
721 matching_devices.push(Dom::from_ref(&**device));
722 }
723 }
724
725 status.set_devices(std::mem::take(&mut matching_devices));
727
728 promise.resolve_native(cx, status);
731 }
732
733 fn permission_request(
735 cx: &mut JSContext,
736 promise: &RootedPromise,
737 descriptor: &BluetoothPermissionDescriptor,
738 status: &BluetoothPermissionResult,
739 ) {
740 if descriptor.filters.is_some() == descriptor.acceptAllDevices {
742 return promise.reject_error(cx, Error::Type(OPTIONS_ERROR.to_owned()));
743 }
744
745 let sender = response_async(promise, status);
747 let bluetooth = status.get_bluetooth(cx);
748 bluetooth.request_bluetooth_devices(
749 cx,
750 promise,
751 &descriptor.filters,
752 &descriptor.optionalServices,
753 sender,
754 );
755
756 }
758
759 fn permission_revoke(
761 cx: &mut JSContext,
762 _descriptor: &BluetoothPermissionDescriptor,
763 status: &BluetoothPermissionResult,
764 ) {
765 let global = status.global();
767 let allowed_devices = global
768 .as_window()
769 .bluetooth_extra_permission_data()
770 .get_allowed_devices();
771 let bluetooth = status.get_bluetooth(cx);
773 let device_map = bluetooth.get_device_map().borrow();
774 for (id, device) in device_map.iter() {
775 let id = DOMString::from(id.clone());
776 if allowed_devices.iter().any(|d| d.deviceId == id) &&
778 !device.is_represented_device_null()
779 {
780 continue;
784 }
785 let _ = device.get_gatt(cx).Disconnect(cx);
787 }
788 }
789}