1use js::gc::HandleValue;
6use script_bindings::reflector::{DomObject, reflect_dom_object};
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 script_bindings::domstring::{DOMString, TracedDOMString};
17use js::context::JSContext;
18use crate::conversions::Convert;
19use script_bindings::cell::{Ref, DomRefCell};
20use crate::dom::bindings::buffer_source::get_buffer_source_copy;
21use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothDataFilterInit;
22use crate::dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions};
23use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothLEScanFilterInit;
24use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor;
25use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServer_Binding::
26BluetoothRemoteGATTServerMethods;
27use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState};
28use crate::dom::bindings::codegen::UnionTypes::StringOrUnsignedLong;
29use crate::dom::bindings::error::Error::{self, Network, Security, Type};
30use crate::dom::bindings::error::Fallible;
31use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
32use crate::dom::bindings::reflector::DomGlobal;
33use crate::dom::bindings::root::{Dom, DomRoot};
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)]
71#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
72pub(crate) struct AllowedBluetoothDevice {
73 pub(crate) deviceId: TracedDOMString,
74 pub(crate) mayUseGATT: bool,
75}
76
77impl AllowedBluetoothDevice {
78 pub(crate) fn new(device_id: String) -> Self {
79 Self {
80 deviceId: TracedDOMString::from(device_id),
81 mayUseGATT: true,
82 }
83 }
84}
85
86#[derive(JSTraceable, MallocSizeOf)]
87#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
88pub(crate) struct BluetoothExtraPermissionData {
89 allowed_devices: DomRefCell<Vec<AllowedBluetoothDevice>>,
90}
91
92impl BluetoothExtraPermissionData {
93 pub(crate) fn new() -> BluetoothExtraPermissionData {
94 BluetoothExtraPermissionData {
95 allowed_devices: DomRefCell::new(Vec::new()),
96 }
97 }
98
99 pub(crate) fn add_new_allowed_device(&self, device_id: String) {
100 self.allowed_devices
101 .borrow_mut()
102 .push(AllowedBluetoothDevice::new(device_id));
103 }
104
105 fn get_allowed_devices(&self) -> Ref<'_, Vec<AllowedBluetoothDevice>> {
106 self.allowed_devices.borrow()
107 }
108
109 pub(crate) fn allowed_devices_contains_id(&self, id: &TracedDOMString) -> bool {
110 self.allowed_devices
111 .borrow()
112 .iter()
113 .any(|d| d.deviceId == *id)
114 }
115}
116
117impl Default for BluetoothExtraPermissionData {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123struct BluetoothContext<T: AsyncBluetoothListener + DomObject> {
124 promise: Option<TrustedPromise>,
125 receiver: Trusted<T>,
126}
127
128pub(crate) trait AsyncBluetoothListener {
129 fn handle_response(
130 &self,
131 cx: &mut JSContext,
132 result: BluetoothResponse,
133 promise: &RootedPromise,
134 );
135}
136
137impl<T> BluetoothContext<T>
138where
139 T: AsyncBluetoothListener + DomObject,
140{
141 fn response(&mut self, cx: &mut JSContext, response: BluetoothResponseResult) {
142 let promise = self
143 .promise
144 .take()
145 .expect("Bluetooth promise is missing")
146 .root(cx);
147
148 match response {
151 Ok(response) => self.receiver.root().handle_response(cx, response, &promise),
152 Err(error) => promise.reject_error(cx, error.convert()),
155 }
156 }
157}
158
159#[dom_struct]
161pub(crate) struct Bluetooth {
162 eventtarget: EventTarget,
163 device_instance_map: DomRefCell<HashMap<String, Dom<BluetoothDevice>>>,
164}
165
166impl Bluetooth {
167 pub(crate) fn new_inherited() -> Bluetooth {
168 Bluetooth {
169 eventtarget: EventTarget::new_inherited(),
170 device_instance_map: DomRefCell::new(HashMap::new()),
171 }
172 }
173
174 pub(crate) fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<Bluetooth> {
175 reflect_dom_object(cx, Box::new(Bluetooth::new_inherited()), global)
176 }
177
178 fn get_bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
179 self.global().as_window().bluetooth_thread()
180 }
181
182 pub(crate) fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
183 &self.device_instance_map
184 }
185
186 fn request_bluetooth_devices(
188 &self,
189 cx: &mut JSContext,
190 p: &RootedPromise,
191 filters: &Option<Vec<BluetoothLEScanFilterInit>>,
192 optional_services: &[BluetoothServiceUUID],
193 sender: GenericCallback<BluetoothResponseResult>,
194 ) {
195 let mut uuid_filters = vec![];
199
200 if let Some(filters) = filters {
201 if filters.is_empty() {
203 p.reject_error(cx, Type(FILTER_EMPTY_ERROR.to_owned()));
204 return;
205 }
206
207 for filter in filters {
211 match canonicalize_filter(filter) {
213 Ok(f) => uuid_filters.push(f),
215 Err(e) => {
216 p.reject_error(cx, e);
217 return;
218 },
219 }
220 }
222 }
223
224 let mut optional_services_uuids = vec![];
225 for opt_service in optional_services {
226 let uuid = match BluetoothUUID::service(opt_service.clone()) {
228 Ok(u) => String::from(u),
229 Err(e) => {
230 p.reject_error(cx, e);
231 return;
232 },
233 };
234
235 if !uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
239 optional_services_uuids.push(uuid);
240 }
241 }
242
243 let option = RequestDeviceoptions::new(
244 self.global().as_window().webview_id(),
245 BluetoothScanfilterSequence::new(uuid_filters),
246 ServiceUUIDSequence::new(optional_services_uuids),
247 );
248
249 if let PermissionState::Denied =
251 descriptor_permission_state(PermissionName::Bluetooth, None)
252 {
253 return p.reject_error(cx, Error::NotFound(None));
254 }
255
256 self.get_bluetooth_thread()
259 .send(BluetoothRequest::RequestDevice(option, sender))
260 .unwrap();
261 }
262}
263
264pub(crate) fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
265 promise: &RootedPromise,
266 receiver: &T,
267) -> GenericCallback<BluetoothResponseResult> {
268 let task_source = receiver
269 .global()
270 .task_manager()
271 .networking_task_source()
272 .to_sendable();
273 let context = Arc::new(Mutex::new(BluetoothContext {
274 promise: Some(TrustedPromise::from(promise)),
275 receiver: Trusted::new(receiver),
276 }));
277 GenericCallback::new(move |message| {
278 struct ListenerTask<T: AsyncBluetoothListener + DomObject> {
279 context: Arc<Mutex<BluetoothContext<T>>>,
280 action: BluetoothResponseResult,
281 }
282
283 impl<T> TaskOnce for ListenerTask<T>
284 where
285 T: AsyncBluetoothListener + DomObject,
286 {
287 fn run_once(self, cx: &mut JSContext) {
288 let mut context = self.context.lock().unwrap();
289 context.response(cx, self.action);
290 }
291 }
292
293 let task = ListenerTask {
294 context: context.clone(),
295 action: message.unwrap(),
296 };
297
298 task_source.queue_unconditionally(task);
299 })
300 .expect("Could not create callback")
301}
302
303#[expect(clippy::too_many_arguments)]
305pub(crate) fn get_gatt_children<T, F>(
306 cx: &mut CurrentRealm,
307 attribute: &T,
308 single: bool,
309 uuid_canonicalizer: F,
310 uuid: Option<StringOrUnsignedLong>,
311 instance_id: String,
312 connected: bool,
313 child_type: GATTType,
314) -> RootedPromise
315where
316 T: AsyncBluetoothListener + DomObject + 'static,
317 F: FnOnce(StringOrUnsignedLong) -> Fallible<UUID>,
318{
319 let p = Promise::new_in_realm(cx);
320
321 let result_uuid = if let Some(u) = uuid {
322 let canonicalized = match uuid_canonicalizer(u) {
324 Ok(canonicalized_uuid) => String::from(canonicalized_uuid),
325 Err(e) => {
326 p.reject_error(cx, e);
327 return p;
328 },
329 };
330 if uuid_is_blocklisted(canonicalized.as_ref(), Blocklist::All) {
332 p.reject_error(cx, Security(None));
333 return p;
334 }
335 Some(canonicalized)
336 } else {
337 None
338 };
339
340 if !connected {
342 p.reject_error(cx, Network(None));
343 return p;
344 }
345
346 let sender = response_async(&p, attribute);
351 attribute
352 .global()
353 .as_window()
354 .bluetooth_thread()
355 .send(BluetoothRequest::GetGATTChildren(
356 instance_id,
357 result_uuid,
358 single,
359 child_type,
360 sender,
361 ))
362 .unwrap();
363 p
364}
365
366fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<BluetoothScanfilter> {
368 if filter.services.is_none() &&
370 filter.name.is_none() &&
371 filter.namePrefix.is_none() &&
372 filter.manufacturerData.is_none() &&
373 filter.serviceData.is_none()
374 {
375 return Err(Type(FILTER_ERROR.to_owned()));
376 }
377
378 let services_vec = match filter.services {
383 Some(ref services) => {
384 if services.is_empty() {
386 return Err(Type(SERVICE_ERROR.to_owned()));
387 }
388
389 let mut services_vec = vec![];
390
391 for service in services {
392 let uuid = String::from(BluetoothUUID::service(service.clone())?);
394
395 if uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
397 return Err(Security(None));
398 }
399
400 services_vec.push(uuid);
401 }
402 services_vec
404 },
405 None => vec![],
406 };
407
408 let name = match filter.name {
410 Some(ref name) => {
411 if name.len_utf8() > MAX_DEVICE_NAME_LENGTH {
413 return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
414 }
415
416 Some(name.to_string())
418 },
419 None => None,
420 };
421
422 let name_prefix = match filter.namePrefix {
424 Some(ref name_prefix) => {
425 if name_prefix.is_empty() {
427 return Err(Type(NAME_PREFIX_ERROR.to_owned()));
428 }
429 if name_prefix.len_utf8() > MAX_DEVICE_NAME_LENGTH {
430 return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
431 }
432
433 name_prefix.to_string()
435 },
436 None => String::new(),
437 };
438
439 let manufacturer_data = match filter.manufacturerData {
441 Some(ref manufacturer_data_map) => {
442 if manufacturer_data_map.is_empty() {
444 return Err(Type(MANUFACTURER_DATA_ERROR.to_owned()));
445 }
446 let mut map = HashMap::new();
447 for (key, bdfi) in manufacturer_data_map.iter() {
448 let manufacturer_id = match key.str().parse::<u16>() {
450 Ok(id) => id,
451 Err(err) => {
452 return Err(Type(cformat!("{} {} {}", KEY_CONVERSION_ERROR, key, err)));
453 },
454 };
455
456 map.insert(
460 manufacturer_id,
461 canonicalize_bluetooth_data_filter_init(bdfi)?,
462 );
463 }
464 Some(map)
465 },
466 None => None,
467 };
468
469 let service_data = match filter.serviceData {
471 Some(ref service_data_map) => {
472 if service_data_map.is_empty() {
474 return Err(Type(SERVICE_DATA_ERROR.to_owned()));
475 }
476 let mut map = HashMap::new();
477 for (key, bdfi) in service_data_map.iter() {
478 let service_name = match key.str().parse::<u32>() {
479 Ok(number) => StringOrUnsignedLong::UnsignedLong(number),
481 _ => StringOrUnsignedLong::String(key.clone()),
483 };
484
485 let service = String::from(BluetoothUUID::service(service_name)?);
487
488 if uuid_is_blocklisted(service.as_ref(), Blocklist::All) {
490 return Err(Security(None));
491 }
492
493 map.insert(service, canonicalize_bluetooth_data_filter_init(bdfi)?);
497 }
498 Some(map)
499 },
500 None => None,
501 };
502
503 Ok(BluetoothScanfilter::new(
505 name,
506 name_prefix,
507 services_vec,
508 manufacturer_data,
509 service_data,
510 ))
511}
512
513fn canonicalize_bluetooth_data_filter_init(
515 bdfi: &BluetoothDataFilterInit,
516) -> Fallible<(Vec<u8>, Vec<u8>)> {
517 let data_prefix = match &bdfi.dataPrefix {
519 Some(buffer_source) => get_buffer_source_copy(buffer_source.into()),
520 None => vec![],
521 };
522
523 let mask = match &bdfi.mask {
527 Some(buffer_source) => get_buffer_source_copy(buffer_source.into()),
528 None => vec![0xFF; data_prefix.len()],
529 };
530
531 if mask.len() != data_prefix.len() {
533 return Err(Type(MASK_LENGTH_ERROR.to_owned()));
534 }
535
536 Ok((data_prefix, mask))
538}
539
540impl Convert<Error> for BluetoothError {
541 fn convert(self) -> Error {
542 match self {
543 BluetoothError::Type(message) => Error::Type(cformat!("{message}")),
544 BluetoothError::Network => Error::Network(None),
545 BluetoothError::NotFound => Error::NotFound(None),
546 BluetoothError::NotSupported => Error::NotSupported(None),
547 BluetoothError::Security => Error::Security(None),
548 BluetoothError::InvalidState => Error::InvalidState(None),
549 }
550 }
551}
552
553impl BluetoothMethods<crate::DomTypeHolder> for Bluetooth {
554 fn RequestDevice(&self, cx: &mut CurrentRealm, option: &RequestDeviceOptions) -> RootedPromise {
556 let p = Promise::new_in_realm(cx);
557 if (option.filters.is_some() && option.acceptAllDevices) ||
559 (option.filters.is_none() && !option.acceptAllDevices)
560 {
561 p.reject_error(cx, Error::Type(OPTIONS_ERROR.to_owned()));
562 return p;
563 }
564
565 let sender = response_async(&p, self);
567 self.request_bluetooth_devices(cx, &p, &option.filters, &option.optionalServices, sender);
568 p
570 }
571
572 fn GetAvailability(&self, cx: &mut CurrentRealm) -> RootedPromise {
574 let p = Promise::new_in_realm(cx);
575 let sender = response_async(&p, self);
578 self.get_bluetooth_thread()
579 .send(BluetoothRequest::GetAvailability(sender))
580 .unwrap();
581 p
582 }
583
584 event_handler!(
586 availabilitychanged,
587 GetOnavailabilitychanged,
588 SetOnavailabilitychanged
589 );
590}
591
592impl AsyncBluetoothListener for Bluetooth {
593 fn handle_response(
594 &self,
595 cx: &mut JSContext,
596 response: BluetoothResponse,
597 promise: &RootedPromise,
598 ) {
599 match response {
600 BluetoothResponse::RequestDevice(device) => {
603 {
604 let device_instance_map = self.device_instance_map.borrow();
605 if let Some(existing_device) = device_instance_map.get(&device.id) {
606 return promise.resolve_native(cx, &**existing_device);
607 }
608 }
609 let bt_device = BluetoothDevice::new(
610 cx,
611 &self.global(),
612 DOMString::from(device.id.clone()),
613 device.name.map(DOMString::from),
614 self,
615 );
616 self.device_instance_map
617 .borrow_mut()
618 .insert(device.id.clone(), Dom::from_ref(&bt_device));
619
620 self.global()
621 .as_window()
622 .bluetooth_extra_permission_data()
623 .add_new_allowed_device(device.id);
624 promise.resolve_native(cx, &bt_device);
627 },
628 BluetoothResponse::GetAvailability(is_available) => {
631 promise.resolve_native(cx, &is_available);
632 },
633 _ => promise.reject_error(cx, Error::Type(c"Something went wrong...".to_owned())),
634 }
635 }
636}
637
638impl PermissionAlgorithm for Bluetooth {
639 type Descriptor = BluetoothPermissionDescriptor;
640 type Status = BluetoothPermissionResult;
641
642 fn create_descriptor(
643 cx: &mut JSContext,
644 permission_descriptor_obj: HandleValue,
645 ) -> Result<BluetoothPermissionDescriptor, Error> {
646 match BluetoothPermissionDescriptor::new(cx, permission_descriptor_obj) {
647 Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
648 Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
649 Err(_) => Err(Error::Type(BT_DESC_CONVERSION_ERROR.into())),
650 }
651 }
652
653 fn permission_query(
655 cx: &mut JSContext,
656 promise: &RootedPromise,
657 descriptor: &BluetoothPermissionDescriptor,
658 status: &BluetoothPermissionResult,
659 ) {
660 status.set_state(descriptor_permission_state(status.get_query(), None));
664
665 if let PermissionState::Denied = status.get_state() {
667 status.set_devices(Vec::new());
668 return promise.resolve_native(cx, status);
669 }
670
671 rooted_vec!(let mut matching_devices);
673
674 let global = status.global();
676 let allowed_devices = global
677 .as_window()
678 .bluetooth_extra_permission_data()
679 .get_allowed_devices();
680
681 let bluetooth = status.get_bluetooth(cx);
682 let device_map = bluetooth.get_device_map().borrow();
683
684 for allowed_device in allowed_devices.iter() {
686 if let Some(ref id) = descriptor.deviceId &&
688 allowed_device.deviceId != **id
689 {
690 continue;
691 }
692 let device_id = String::from(allowed_device.deviceId.str());
693
694 if let Some(ref filters) = descriptor.filters {
696 let mut scan_filters: Vec<BluetoothScanfilter> = Vec::new();
697
698 for filter in filters {
700 match canonicalize_filter(filter) {
701 Ok(f) => scan_filters.push(f),
702 Err(error) => return promise.reject_error(cx, error),
703 }
704 }
705
706 let (sender, receiver) =
710 generic_channel::channel(global.time_profiler_chan().clone()).unwrap();
711 status
712 .get_bluetooth_thread()
713 .send(BluetoothRequest::MatchesFilter(
714 device_id.clone(),
715 BluetoothScanfilterSequence::new(scan_filters),
716 sender,
717 ))
718 .unwrap();
719
720 match receiver.recv().unwrap() {
721 Ok(true) => (),
722 Ok(false) => continue,
723 Err(error) => return promise.reject_error(cx, error.convert()),
724 };
725 }
726
727 if let Some(device) = device_map.get(&device_id) {
731 matching_devices.push(Dom::from_ref(&**device));
732 }
733 }
734
735 status.set_devices(std::mem::take(&mut matching_devices));
737
738 promise.resolve_native(cx, status);
741 }
742
743 fn permission_request(
745 cx: &mut JSContext,
746 promise: &RootedPromise,
747 descriptor: &BluetoothPermissionDescriptor,
748 status: &BluetoothPermissionResult,
749 ) {
750 if descriptor.filters.is_some() == descriptor.acceptAllDevices {
752 return promise.reject_error(cx, Error::Type(OPTIONS_ERROR.to_owned()));
753 }
754
755 let sender = response_async(promise, status);
757 let bluetooth = status.get_bluetooth(cx);
758 bluetooth.request_bluetooth_devices(
759 cx,
760 promise,
761 &descriptor.filters,
762 &descriptor.optionalServices,
763 sender,
764 );
765
766 }
768
769 fn permission_revoke(
771 cx: &mut JSContext,
772 _descriptor: &BluetoothPermissionDescriptor,
773 status: &BluetoothPermissionResult,
774 ) {
775 let global = status.global();
777 let allowed_devices = global
778 .as_window()
779 .bluetooth_extra_permission_data()
780 .get_allowed_devices();
781 let bluetooth = status.get_bluetooth(cx);
783 let device_map = bluetooth.get_device_map().borrow();
784 for (id, device) in device_map.iter() {
785 if allowed_devices.iter().any(|d| d.deviceId == *id) &&
787 !device.is_represented_device_null()
788 {
789 continue;
793 }
794 let _ = device.get_gatt(cx).Disconnect(cx);
796 }
797 }
798}