1 /******************************************************************************
2  *
3  *  Copyright (C) 2016 The Linux Foundation
4  *  Copyright 2009-2012 Broadcom Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 /*******************************************************************************
21  *
22  *  Filename:      bluetooth.c
23  *
24  *  Description:   Bluetooth HAL implementation
25  *
26  ******************************************************************************/
27 
28 #define LOG_TAG "bt_btif"
29 
30 #include "hardware/bluetooth.h"
31 
32 #include <base/functional/bind.h>
33 #include <base/functional/callback.h>
34 #include <bluetooth/log.h>
35 
36 #include <cstdint>
37 #include <cstdlib>
38 #include <cstring>
39 #include <string>
40 #include <utility>
41 #include <vector>
42 
43 #include "bta/hh/bta_hh_int.h"
44 #include "bta/include/bta_api.h"
45 #include "bta/include/bta_ar_api.h"
46 #include "bta/include/bta_av_api.h"
47 #include "bta/include/bta_csis_api.h"
48 #include "bta/include/bta_has_api.h"
49 #include "bta/include/bta_hearing_aid_api.h"
50 #include "bta/include/bta_hf_client_api.h"
51 #include "bta/include/bta_le_audio_api.h"
52 #include "bta/include/bta_le_audio_broadcaster_api.h"
53 #include "bta/include/bta_vc_api.h"
54 #include "btif/avrcp/avrcp_service.h"
55 #include "btif/include/btif_a2dp.h"
56 #include "btif/include/btif_a2dp_source.h"
57 #include "btif/include/btif_api.h"
58 #include "btif/include/btif_av.h"
59 #include "btif/include/btif_bqr.h"
60 #include "btif/include/btif_common.h"
61 #include "btif/include/btif_config.h"
62 #include "btif/include/btif_debug_conn.h"
63 #include "btif/include/btif_dm.h"
64 #include "btif/include/btif_hd.h"
65 #include "btif/include/btif_hearing_aid.h"
66 #include "btif/include/btif_hf.h"
67 #include "btif/include/btif_hf_client.h"
68 #include "btif/include/btif_hh.h"
69 #include "btif/include/btif_keystore.h"
70 #include "btif/include/btif_metrics_logging.h"
71 #include "btif/include/btif_pan.h"
72 #include "btif/include/btif_profile_storage.h"
73 #include "btif/include/btif_rc.h"
74 #include "btif/include/btif_sock.h"
75 #include "btif/include/btif_sock_logging.h"
76 #include "btif/include/btif_storage.h"
77 #include "btif/include/core_callbacks.h"
78 #include "btif/include/stack_manager_t.h"
79 #include "common/address_obfuscator.h"
80 #include "common/metrics.h"
81 #include "common/os_utils.h"
82 #include "device/include/device_iot_config.h"
83 #include "device/include/esco_parameters.h"
84 #include "device/include/interop.h"
85 #include "device/include/interop_config.h"
86 #include "hardware/avrcp/avrcp.h"
87 #include "hardware/bt_csis.h"
88 #include "hardware/bt_gatt.h"
89 #include "hardware/bt_has.h"
90 #include "hardware/bt_hearing_aid.h"
91 #include "hardware/bt_le_audio.h"
92 #include "hardware/bt_rc.h"
93 #include "hardware/bt_sdp.h"
94 #include "hardware/bt_sock.h"
95 #include "hardware/bt_vc.h"
96 #include "internal_include/bt_target.h"
97 #include "main/shim/dumpsys.h"
98 #include "os/parameter_provider.h"
99 #include "osi/include/alarm.h"
100 #include "osi/include/allocator.h"
101 #include "osi/include/properties.h"
102 #include "osi/include/stack_power_telemetry.h"
103 #include "osi/include/wakelock.h"
104 #include "stack/btm/btm_dev.h"
105 #include "stack/btm/btm_sco_hfp_hal.h"
106 #include "stack/connection_manager/connection_manager.h"
107 #include "stack/include/a2dp_api.h"
108 #include "stack/include/avct_api.h"
109 #include "stack/include/avdt_api.h"
110 #include "stack/include/avrc_api.h"
111 #include "stack/include/bnep_api.h"
112 #include "stack/include/bt_name.h"
113 #include "stack/include/bt_octets.h"
114 #include "stack/include/btm_client_interface.h"
115 #include "stack/include/btm_status.h"
116 #include "stack/include/gatt_api.h"
117 #include "stack/include/hcidefs.h"
118 #include "stack/include/hfp_lc3_decoder.h"
119 #include "stack/include/hfp_lc3_encoder.h"
120 #include "stack/include/hfp_msbc_decoder.h"
121 #include "stack/include/hfp_msbc_encoder.h"
122 #include "stack/include/hidh_api.h"
123 #include "stack/include/l2cap_module.h"
124 #include "stack/include/main_thread.h"
125 #include "stack/include/pan_api.h"
126 #include "stack/include/sdp_api.h"
127 #include "storage/config_keys.h"
128 #include "types/ble_address_with_type.h"
129 #include "types/bt_transport.h"
130 #include "types/raw_address.h"
131 
132 // TODO(b/369381361) Enfore -Wmissing-prototypes
133 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
134 
135 using bluetooth::csis::CsisClientInterface;
136 using bluetooth::has::HasClientInterface;
137 using bluetooth::le_audio::LeAudioBroadcasterInterface;
138 using bluetooth::le_audio::LeAudioClientInterface;
139 using bluetooth::vc::VolumeControlInterface;
140 using namespace bluetooth;
141 
142 namespace {
to_bt_transport(int val)143 tBT_TRANSPORT to_bt_transport(int val) {
144   switch (val) {
145     case 0:
146       return BT_TRANSPORT_AUTO;
147     case 1:
148       return BT_TRANSPORT_BR_EDR;
149     case 2:
150       return BT_TRANSPORT_LE;
151     default:
152       break;
153   }
154   log::warn("Passed unexpected transport value:{}", val);
155   return BT_TRANSPORT_AUTO;
156 }
157 
158 }  // namespace
159 
160 /*******************************************************************************
161  *  Static variables
162  ******************************************************************************/
163 
164 static bt_callbacks_t* bt_hal_cbacks = NULL;
165 bool restricted_mode = false;
166 bool common_criteria_mode = false;
167 const int CONFIG_COMPARE_ALL_PASS = 0b11;
168 int common_criteria_config_compare_result = CONFIG_COMPARE_ALL_PASS;
169 bool is_local_device_atv = false;
170 
171 /*******************************************************************************
172  *  Externs
173  ******************************************************************************/
174 
175 /* list all extended interfaces here */
176 
177 /*rfc l2cap*/
178 extern const btsock_interface_t* btif_sock_get_interface();
179 /* gatt */
180 extern const btgatt_interface_t* btif_gatt_get_interface();
181 /* avrc target */
182 extern const btrc_interface_t* btif_rc_get_interface();
183 /* avrc controller */
184 extern const btrc_ctrl_interface_t* btif_rc_ctrl_get_interface();
185 /*SDP search client*/
186 extern const btsdp_interface_t* btif_sdp_get_interface();
187 /* Hearing Access client */
188 extern HasClientInterface* btif_has_client_get_interface();
189 /* LeAudio testi client */
190 extern LeAudioClientInterface* btif_le_audio_get_interface();
191 /* LeAudio Broadcaster */
192 extern LeAudioBroadcasterInterface* btif_le_audio_broadcaster_get_interface();
193 /* Coordinated Set Service Client */
194 extern CsisClientInterface* btif_csis_client_get_interface();
195 /* Volume Control client */
196 extern VolumeControlInterface* btif_volume_control_get_interface();
197 
198 bt_status_t btif_av_sink_execute_service(bool b_enable);
199 
200 extern void bta_gatt_client_dump(int fd);
201 
202 /*******************************************************************************
203  *  Callbacks from bluetooth::core (see go/invisalign-bt)
204  ******************************************************************************/
205 
206 struct ConfigInterfaceImpl : bluetooth::core::ConfigInterface {
ConfigInterfaceImplConfigInterfaceImpl207   ConfigInterfaceImpl() : bluetooth::core::ConfigInterface() {}
208 
isRestrictedModeConfigInterfaceImpl209   bool isRestrictedMode() override { return is_restricted_mode(); }
210 
isA2DPOffloadEnabledConfigInterfaceImpl211   bool isA2DPOffloadEnabled() override {
212     char value_sup[PROPERTY_VALUE_MAX] = {'\0'};
213     char value_dis[PROPERTY_VALUE_MAX] = {'\0'};
214 
215     osi_property_get("ro.bluetooth.a2dp_offload.supported", value_sup, "false");
216     osi_property_get("persist.bluetooth.a2dp_offload.disabled", value_dis, "false");
217     auto a2dp_offload_enabled =
218             (strcmp(value_sup, "true") == 0) && (strcmp(value_dis, "false") == 0);
219     log::verbose("a2dp_offload.enable = {}", a2dp_offload_enabled);
220 
221     return a2dp_offload_enabled;
222   }
223 
isAndroidTVDeviceConfigInterfaceImpl224   bool isAndroidTVDevice() override { return is_atv_device(); }
225 };
226 
227 // TODO(aryarahul): remove unnecessary indirection through hfp_msbc_*.cc
228 struct MSBCCodec : bluetooth::core::CodecInterface {
MSBCCodecMSBCCodec229   MSBCCodec() : bluetooth::core::CodecInterface() {}
230 
initializeMSBCCodec231   void initialize() override {
232     hfp_msbc_decoder_init();
233     hfp_msbc_encoder_init();
234   }
235 
cleanupMSBCCodec236   void cleanup() override {
237     hfp_msbc_decoder_cleanup();
238     hfp_msbc_encoder_cleanup();
239   }
240 
encodePacketMSBCCodec241   uint32_t encodePacket(int16_t* input, uint8_t* output) {
242     return hfp_msbc_encode_frames(input, output);
243   }
244 
decodePacketMSBCCodec245   bool decodePacket(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) {
246     return hfp_msbc_decoder_decode_packet(i_buf, o_buf, out_len);
247   }
248 };
249 
250 struct LC3Codec : bluetooth::core::CodecInterface {
LC3CodecLC3Codec251   LC3Codec() : bluetooth::core::CodecInterface() {}
252 
initializeLC3Codec253   void initialize() override {
254     hfp_lc3_decoder_init();
255     hfp_lc3_encoder_init();
256   }
257 
cleanupLC3Codec258   void cleanup() override {
259     hfp_lc3_encoder_cleanup();
260     hfp_lc3_decoder_cleanup();
261   }
262 
encodePacketLC3Codec263   uint32_t encodePacket(int16_t* input, uint8_t* output) {
264     return hfp_lc3_encode_frames(input, output);
265   }
266 
decodePacketLC3Codec267   bool decodePacket(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) {
268     return hfp_lc3_decoder_decode_packet(i_buf, o_buf, out_len);
269   }
270 };
271 
272 struct CoreInterfaceImpl : bluetooth::core::CoreInterface {
273   using bluetooth::core::CoreInterface::CoreInterface;
274 
onBluetoothEnabledCoreInterfaceImpl275   void onBluetoothEnabled() override {
276     /* init pan */
277     btif_pan_init();
278   }
279 
toggleProfileCoreInterfaceImpl280   bt_status_t toggleProfile(tBTA_SERVICE_ID service_id, bool enable) override {
281     /* Check the service_ID and invoke the profile's BT state changed API */
282     switch (service_id) {
283       case BTA_HFP_SERVICE_ID:
284       case BTA_HSP_SERVICE_ID: {
285         bluetooth::headset::ExecuteService(enable);
286       } break;
287       case BTA_A2DP_SOURCE_SERVICE_ID: {
288         btif_av_source_execute_service(enable);
289       } break;
290       case BTA_A2DP_SINK_SERVICE_ID: {
291         btif_av_sink_execute_service(enable);
292       } break;
293       case BTA_HID_SERVICE_ID: {
294         btif_hh_execute_service(enable);
295       } break;
296       case BTA_HFP_HS_SERVICE_ID: {
297         btif_hf_client_execute_service(enable);
298       } break;
299       case BTA_HIDD_SERVICE_ID: {
300         btif_hd_execute_service(enable);
301       } break;
302       case BTA_PBAP_SERVICE_ID:
303       case BTA_PCE_SERVICE_ID:
304       case BTA_MAP_SERVICE_ID:
305       case BTA_MN_SERVICE_ID: {
306         /**
307          * Do nothing; these services were started elsewhere. However, we need
308          * to flow through this codepath in order to properly report back the
309          * local UUIDs back to adapter properties in Java. To achieve this, we
310          * need to catch these service IDs in order for {@link
311          * btif_in_execute_service_request} to return {@code BT_STATUS_SUCCESS},
312          * so that in {@link btif_dm_enable_service} the check passes and the
313          * UUIDs are allowed to be passed up into the Java layer.
314          */
315       } break;
316       default:
317         log::error("Unknown service {} being {}", service_id, (enable) ? "enabled" : "disabled");
318         return BT_STATUS_FAIL;
319     }
320     return BT_STATUS_SUCCESS;
321   }
322 
removeDeviceFromProfilesCoreInterfaceImpl323   void removeDeviceFromProfiles(const RawAddress& bd_addr) override {
324 /*special handling for HID devices */
325 #if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
326     tAclLinkSpec link_spec;
327     link_spec.addrt.bda = bd_addr;
328     link_spec.addrt.type = BLE_ADDR_PUBLIC;
329     link_spec.transport = BT_TRANSPORT_AUTO;
330 
331     btif_hh_remove_device(link_spec);
332 #endif
333 #if (defined(BTA_HD_INCLUDED) && (BTA_HD_INCLUDED == TRUE))
334     btif_hd_remove_device(bd_addr);
335 #endif
336     btif_hearing_aid_get_interface()->RemoveDevice(bd_addr);
337 
338     if (bluetooth::csis::CsisClient::IsCsisClientRunning()) {
339       btif_csis_client_get_interface()->RemoveDevice(bd_addr);
340     }
341 
342     if (LeAudioClient::IsLeAudioClientRunning()) {
343       btif_le_audio_get_interface()->RemoveDevice(bd_addr);
344     }
345 
346     if (VolumeControl::IsVolumeControlRunning()) {
347       btif_volume_control_get_interface()->RemoveDevice(bd_addr);
348     }
349   }
350 
onLinkDownCoreInterfaceImpl351   void onLinkDown(const RawAddress& bd_addr, tBT_TRANSPORT transport) override {
352     if (transport != BT_TRANSPORT_BR_EDR) {
353       return;
354     }
355 
356     btif_av_acl_disconnected(bd_addr, A2dpType::kSource);
357     btif_av_acl_disconnected(bd_addr, A2dpType::kSink);
358   }
359 };
360 
CreateInterfaceToProfiles()361 static bluetooth::core::CoreInterface* CreateInterfaceToProfiles() {
362   static bluetooth::core::EventCallbacks eventCallbacks{
363           .invoke_adapter_state_changed_cb = invoke_adapter_state_changed_cb,
364           .invoke_adapter_properties_cb = invoke_adapter_properties_cb,
365           .invoke_remote_device_properties_cb = invoke_remote_device_properties_cb,
366           .invoke_device_found_cb = invoke_device_found_cb,
367           .invoke_discovery_state_changed_cb = invoke_discovery_state_changed_cb,
368           .invoke_pin_request_cb = invoke_pin_request_cb,
369           .invoke_ssp_request_cb = invoke_ssp_request_cb,
370           .invoke_oob_data_request_cb = invoke_oob_data_request_cb,
371           .invoke_bond_state_changed_cb = invoke_bond_state_changed_cb,
372           .invoke_address_consolidate_cb = invoke_address_consolidate_cb,
373           .invoke_le_address_associate_cb = invoke_le_address_associate_cb,
374           .invoke_acl_state_changed_cb = invoke_acl_state_changed_cb,
375           .invoke_thread_evt_cb = invoke_thread_evt_cb,
376           .invoke_le_test_mode_cb = invoke_le_test_mode_cb,
377           .invoke_energy_info_cb = invoke_energy_info_cb,
378           .invoke_link_quality_report_cb = invoke_link_quality_report_cb,
379           .invoke_key_missing_cb = invoke_key_missing_cb,
380           .invoke_encryption_change_cb = invoke_encryption_change_cb,
381   };
382   static bluetooth::core::HACK_ProfileInterface profileInterface{
383           // HID
384           .btif_hh_virtual_unplug = btif_hh_virtual_unplug,
385           .bta_hh_read_ssr_param = bta_hh_read_ssr_param,
386 
387           // AVDTP
388           .btif_av_set_dynamic_audio_buffer_size = btif_av_set_dynamic_audio_buffer_size,
389 
390           // ASHA
391           .GetHearingAidDeviceCount = HearingAid::GetDeviceCount,
392 
393           // LE Audio
394           .IsLeAudioClientRunning = LeAudioClient::IsLeAudioClientRunning,
395 
396           // AVRCP
397           .AVRC_GetProfileVersion = AVRC_GetProfileVersion,
398   };
399 
400   static auto configInterface = ConfigInterfaceImpl();
401   static auto msbcCodecInterface = MSBCCodec();
402   static auto lc3CodecInterface = LC3Codec();
403 
404   static auto interfaceForCore =
405           CoreInterfaceImpl(&eventCallbacks, &configInterface, &msbcCodecInterface,
406                             &lc3CodecInterface, &profileInterface);
407   return &interfaceForCore;
408 }
409 
410 /*******************************************************************************
411  *  Functions
412  ******************************************************************************/
413 
interface_ready(void)414 static bool interface_ready(void) { return bt_hal_cbacks != NULL; }
set_hal_cbacks(bt_callbacks_t * callbacks)415 static void set_hal_cbacks(bt_callbacks_t* callbacks) { bt_hal_cbacks = callbacks; }
416 
is_profile(const char * p1,const char * p2)417 static bool is_profile(const char* p1, const char* p2) {
418   log::assert_that(p1 != nullptr, "assert failed: p1 != nullptr");
419   log::assert_that(p2 != nullptr, "assert failed: p2 != nullptr");
420   return strlen(p1) == strlen(p2) && strncmp(p1, p2, strlen(p2)) == 0;
421 }
422 
423 /*****************************************************************************
424  *
425  *   BLUETOOTH HAL INTERFACE FUNCTIONS
426  *
427  ****************************************************************************/
428 
429 #ifdef TARGET_FLOSS
430 static int global_hci_adapter = 0;
431 
set_adapter_index(int adapter)432 static void set_adapter_index(int adapter) { global_hci_adapter = adapter; }
GetAdapterIndex()433 int GetAdapterIndex() { return global_hci_adapter; }
434 #else
GetAdapterIndex()435 int GetAdapterIndex() { return 0; }  // Unsupported outside of FLOSS
436 #endif
437 
init(bt_callbacks_t * callbacks,bool start_restricted,bool is_common_criteria_mode,int config_compare_result,bool is_atv)438 static int init(bt_callbacks_t* callbacks, bool start_restricted, bool is_common_criteria_mode,
439                 int config_compare_result, bool is_atv) {
440   log::info(
441           "start restricted = {} ; common criteria mode = {}, config compare "
442           "result = {}",
443           start_restricted, is_common_criteria_mode, config_compare_result);
444 
445   if (interface_ready()) {
446     return BT_STATUS_DONE;
447   }
448 
449   set_hal_cbacks(callbacks);
450 
451   restricted_mode = start_restricted;
452 
453   bluetooth::os::ParameterProvider::SetBtKeystoreInterface(
454           bluetooth::bluetooth_keystore::getBluetoothKeystoreInterface());
455   bluetooth::os::ParameterProvider::SetCommonCriteriaMode(is_common_criteria_mode);
456   if (is_bluetooth_uid() && is_common_criteria_mode) {
457     bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult(config_compare_result);
458   } else {
459     bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult(CONFIG_COMPARE_ALL_PASS);
460   }
461 
462   is_local_device_atv = is_atv;
463 
464   stack_manager_get_interface()->init_stack(CreateInterfaceToProfiles());
465   return BT_STATUS_SUCCESS;
466 }
467 
start_profiles()468 static void start_profiles() {
469 #if (BNEP_INCLUDED == TRUE)
470   BNEP_Init();
471 #if (PAN_INCLUDED == TRUE)
472   PAN_Init();
473 #endif /* PAN */
474 #endif /* BNEP Included */
475   A2DP_Init();
476   AVRC_Init();
477 #if (HID_HOST_INCLUDED == TRUE)
478   HID_HostInit();
479 #endif
480   bta_ar_init();
481 }
482 
stop_profiles()483 static void stop_profiles() {
484   btif_sock_cleanup();
485   btif_pan_cleanup();
486 }
487 
enable()488 static int enable() {
489   if (!interface_ready()) {
490     return BT_STATUS_NOT_READY;
491   }
492 
493   stack_manager_get_interface()->start_up_stack_async(CreateInterfaceToProfiles(), &start_profiles,
494                                                       &stop_profiles);
495   return BT_STATUS_SUCCESS;
496 }
497 
disable(void)498 static int disable(void) {
499   if (!interface_ready()) {
500     return BT_STATUS_NOT_READY;
501   }
502 
503   stack_manager_get_interface()->shut_down_stack_async(&stop_profiles);
504   return BT_STATUS_SUCCESS;
505 }
506 
cleanup(void)507 static void cleanup(void) { stack_manager_get_interface()->clean_up_stack(&stop_profiles); }
508 
start_rust_module(void)509 static void start_rust_module(void) {
510   std::promise<void> rust_up_promise;
511   auto rust_up_future = rust_up_promise.get_future();
512   stack_manager_get_interface()->start_up_rust_module_async(std::move(rust_up_promise));
513   auto status = rust_up_future.wait_for(std::chrono::milliseconds(1000));
514   if (status != std::future_status::ready) {
515     log::error("Failed to wait for rust initialization in time. May lead to unpredictable crash");
516   }
517 }
518 
stop_rust_module(void)519 static void stop_rust_module(void) { stack_manager_get_interface()->shut_down_rust_module_async(); }
520 
is_restricted_mode()521 bool is_restricted_mode() { return restricted_mode; }
522 
get_wbs_supported()523 static bool get_wbs_supported() { return hfp_hal_interface::get_wbs_supported(); }
524 
get_swb_supported()525 static bool get_swb_supported() { return hfp_hal_interface::get_swb_supported(); }
526 
is_coding_format_supported(esco_coding_format_t coding_format)527 static bool is_coding_format_supported(esco_coding_format_t coding_format) {
528   return hfp_hal_interface::is_coding_format_supported(coding_format);
529 }
530 
is_common_criteria_mode()531 bool is_common_criteria_mode() { return is_bluetooth_uid() && common_criteria_mode; }
532 // if common criteria mode disable, will always return
533 // CONFIG_COMPARE_ALL_PASS(0b11) indicate don't check config checksum.
get_common_criteria_config_compare_result()534 int get_common_criteria_config_compare_result() {
535   return is_common_criteria_mode() ? common_criteria_config_compare_result
536                                    : CONFIG_COMPARE_ALL_PASS;
537 }
538 
is_atv_device()539 bool is_atv_device() { return is_local_device_atv; }
540 
get_adapter_properties(void)541 static int get_adapter_properties(void) {
542   if (!btif_is_enabled()) {
543     return BT_STATUS_NOT_READY;
544   }
545 
546   do_in_main_thread(base::BindOnce(btif_get_adapter_properties));
547   return BT_STATUS_SUCCESS;
548 }
549 
get_adapter_property(bt_property_type_t type)550 static int get_adapter_property(bt_property_type_t type) {
551   /* Allow get_adapter_property only for BDADDR and BDNAME if BT is disabled */
552   if (!btif_is_enabled() && (type != BT_PROPERTY_BDADDR) && (type != BT_PROPERTY_BDNAME)) {
553     return BT_STATUS_NOT_READY;
554   }
555 
556   do_in_main_thread(base::BindOnce(btif_get_adapter_property, type));
557   return BT_STATUS_SUCCESS;
558 }
559 
set_scan_mode(bt_scan_mode_t mode)560 static void set_scan_mode(bt_scan_mode_t mode) {
561   do_in_main_thread(base::BindOnce(btif_set_scan_mode, mode));
562 }
563 
set_adapter_property(const bt_property_t * property)564 static int set_adapter_property(const bt_property_t* property) {
565   if (!btif_is_enabled()) {
566     return BT_STATUS_NOT_READY;
567   }
568 
569   switch (property->type) {
570     case BT_PROPERTY_BDNAME:
571     case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT:
572     case BT_PROPERTY_CLASS_OF_DEVICE:
573       break;
574     default:
575       return BT_STATUS_UNHANDLED;
576   }
577 
578   do_in_main_thread(base::BindOnce(
579           [](bt_property_t* property) {
580             btif_set_adapter_property(property);
581             osi_free(property);
582           },
583           property_deep_copy(property)));
584   return BT_STATUS_SUCCESS;
585 }
586 
get_remote_device_properties(RawAddress * remote_addr)587 int get_remote_device_properties(RawAddress* remote_addr) {
588   if (!btif_is_enabled()) {
589     return BT_STATUS_NOT_READY;
590   }
591 
592   do_in_main_thread(base::BindOnce(btif_get_remote_device_properties, *remote_addr));
593   return BT_STATUS_SUCCESS;
594 }
595 
get_remote_device_property(RawAddress * remote_addr,bt_property_type_t type)596 int get_remote_device_property(RawAddress* remote_addr, bt_property_type_t type) {
597   if (!btif_is_enabled()) {
598     return BT_STATUS_NOT_READY;
599   }
600 
601   do_in_main_thread(base::BindOnce(btif_get_remote_device_property, *remote_addr, type));
602   return BT_STATUS_SUCCESS;
603 }
604 
set_remote_device_property(RawAddress * remote_addr,const bt_property_t * property)605 int set_remote_device_property(RawAddress* remote_addr, const bt_property_t* property) {
606   if (!btif_is_enabled()) {
607     return BT_STATUS_NOT_READY;
608   }
609 
610   do_in_main_thread(base::BindOnce(
611           [](RawAddress remote_addr, bt_property_t* property) {
612             btif_set_remote_device_property(&remote_addr, property);
613             osi_free(property);
614           },
615           *remote_addr, property_deep_copy(property)));
616   return BT_STATUS_SUCCESS;
617 }
618 
get_remote_services(RawAddress * remote_addr,int transport)619 int get_remote_services(RawAddress* remote_addr, int transport) {
620   if (!interface_ready()) {
621     return BT_STATUS_NOT_READY;
622   }
623 
624   do_in_main_thread(
625           base::BindOnce(btif_dm_get_remote_services, *remote_addr, to_bt_transport(transport)));
626   return BT_STATUS_SUCCESS;
627 }
628 
start_discovery(void)629 static int start_discovery(void) {
630   if (!interface_ready()) {
631     return BT_STATUS_NOT_READY;
632   }
633 
634   do_in_main_thread(base::BindOnce(btif_dm_start_discovery));
635   return BT_STATUS_SUCCESS;
636 }
637 
cancel_discovery(void)638 static int cancel_discovery(void) {
639   if (!interface_ready()) {
640     return BT_STATUS_NOT_READY;
641   }
642 
643   do_in_main_thread(base::BindOnce(btif_dm_cancel_discovery));
644   return BT_STATUS_SUCCESS;
645 }
646 
create_bond(const RawAddress * bd_addr,int transport)647 static int create_bond(const RawAddress* bd_addr, int transport) {
648   if (!interface_ready()) {
649     return BT_STATUS_NOT_READY;
650   }
651   if (btif_dm_pairing_is_busy()) {
652     return BT_STATUS_BUSY;
653   }
654 
655   do_in_main_thread(base::BindOnce(btif_dm_create_bond, *bd_addr, to_bt_transport(transport)));
656   return BT_STATUS_SUCCESS;
657 }
658 
create_bond_le(const RawAddress * bd_addr,uint8_t addr_type)659 static int create_bond_le(const RawAddress* bd_addr, uint8_t addr_type) {
660   if (!interface_ready()) {
661     return BT_STATUS_NOT_READY;
662   }
663   if (btif_dm_pairing_is_busy()) {
664     return BT_STATUS_BUSY;
665   }
666 
667   do_in_main_thread(base::BindOnce(btif_dm_create_bond_le, *bd_addr, addr_type));
668   return BT_STATUS_SUCCESS;
669 }
670 
create_bond_out_of_band(const RawAddress * bd_addr,int transport,const bt_oob_data_t * p192_data,const bt_oob_data_t * p256_data)671 static int create_bond_out_of_band(const RawAddress* bd_addr, int transport,
672                                    const bt_oob_data_t* p192_data, const bt_oob_data_t* p256_data) {
673   if (!interface_ready()) {
674     return BT_STATUS_NOT_READY;
675   }
676   if (btif_dm_pairing_is_busy()) {
677     return BT_STATUS_BUSY;
678   }
679 
680   do_in_main_thread(base::BindOnce(btif_dm_create_bond_out_of_band, *bd_addr,
681                                    to_bt_transport(transport), *p192_data, *p256_data));
682   return BT_STATUS_SUCCESS;
683 }
684 
generate_local_oob_data(tBT_TRANSPORT transport)685 static int generate_local_oob_data(tBT_TRANSPORT transport) {
686   log::info("");
687   if (!interface_ready()) {
688     return BT_STATUS_NOT_READY;
689   }
690 
691   return do_in_main_thread(base::BindOnce(btif_dm_generate_local_oob_data, transport));
692 }
693 
cancel_bond(const RawAddress * bd_addr)694 static int cancel_bond(const RawAddress* bd_addr) {
695   if (!interface_ready()) {
696     return BT_STATUS_NOT_READY;
697   }
698 
699   do_in_main_thread(base::BindOnce(btif_dm_cancel_bond, *bd_addr));
700   return BT_STATUS_SUCCESS;
701 }
702 
remove_bond(const RawAddress * bd_addr)703 static int remove_bond(const RawAddress* bd_addr) {
704   if (is_restricted_mode() && !btif_storage_is_restricted_device(bd_addr)) {
705     log::info("{} cannot be removed in restricted mode", *bd_addr);
706     return BT_STATUS_SUCCESS;
707   }
708 
709   if (!interface_ready()) {
710     return BT_STATUS_NOT_READY;
711   }
712 
713   do_in_main_thread(base::BindOnce(btif_dm_remove_bond, *bd_addr));
714   return BT_STATUS_SUCCESS;
715 }
716 
pairing_is_busy()717 static bool pairing_is_busy() {
718   if (btif_dm_pairing_is_busy()) {
719     return true;
720   }
721 
722   return false;
723 }
724 
get_connection_state(const RawAddress * bd_addr)725 static int get_connection_state(const RawAddress* bd_addr) {
726   if (!interface_ready()) {
727     return 0;
728   }
729 
730   if (bd_addr == nullptr) {
731     return 0;
732   }
733 
734   return btif_dm_get_connection_state(*bd_addr);
735 }
736 
pin_reply(const RawAddress * bd_addr,uint8_t accept,uint8_t pin_len,bt_pin_code_t * pin_code)737 static int pin_reply(const RawAddress* bd_addr, uint8_t accept, uint8_t pin_len,
738                      bt_pin_code_t* pin_code) {
739   bt_pin_code_t tmp_pin_code;
740   if (!interface_ready()) {
741     return BT_STATUS_NOT_READY;
742   }
743   if (pin_code == nullptr || pin_len > PIN_CODE_LEN) {
744     return BT_STATUS_PARM_INVALID;
745   }
746 
747   memcpy(&tmp_pin_code, pin_code, pin_len);
748 
749   do_in_main_thread(base::BindOnce(btif_dm_pin_reply, *bd_addr, accept, pin_len, tmp_pin_code));
750   return BT_STATUS_SUCCESS;
751 }
752 
ssp_reply(const RawAddress * bd_addr,bt_ssp_variant_t variant,uint8_t accept,uint32_t)753 static int ssp_reply(const RawAddress* bd_addr, bt_ssp_variant_t variant, uint8_t accept,
754                      uint32_t /* passkey */) {
755   if (!interface_ready()) {
756     return BT_STATUS_NOT_READY;
757   }
758   if (variant == BT_SSP_VARIANT_PASSKEY_ENTRY) {
759     return BT_STATUS_PARM_INVALID;
760   }
761 
762   do_in_main_thread(base::BindOnce(btif_dm_ssp_reply, *bd_addr, variant, accept));
763   return BT_STATUS_SUCCESS;
764 }
765 
read_energy_info()766 static int read_energy_info() {
767   if (!interface_ready()) {
768     return BT_STATUS_NOT_READY;
769   }
770 
771   do_in_main_thread(base::BindOnce(btif_dm_read_energy_info));
772   return BT_STATUS_SUCCESS;
773 }
774 
clear_event_filter()775 static int clear_event_filter() {
776   log::verbose("");
777   if (!interface_ready()) {
778     return BT_STATUS_NOT_READY;
779   }
780 
781   do_in_main_thread(base::BindOnce(btif_dm_clear_event_filter));
782   return BT_STATUS_SUCCESS;
783 }
784 
clear_event_mask()785 static int clear_event_mask() {
786   log::verbose("");
787   if (!interface_ready()) {
788     return BT_STATUS_NOT_READY;
789   }
790 
791   do_in_main_thread(base::BindOnce(btif_dm_clear_event_mask));
792   return BT_STATUS_SUCCESS;
793 }
794 
clear_filter_accept_list()795 static int clear_filter_accept_list() {
796   log::verbose("");
797   if (!interface_ready()) {
798     return BT_STATUS_NOT_READY;
799   }
800 
801   do_in_main_thread(base::BindOnce(btif_dm_clear_filter_accept_list));
802   return BT_STATUS_SUCCESS;
803 }
804 
disconnect_all_acls()805 static int disconnect_all_acls() {
806   log::verbose("");
807   if (!interface_ready()) {
808     return BT_STATUS_NOT_READY;
809   }
810 
811   do_in_main_thread(base::BindOnce(btif_dm_disconnect_all_acls));
812   return BT_STATUS_SUCCESS;
813 }
814 
le_rand_btif_cb(uint64_t random_number)815 static void le_rand_btif_cb(uint64_t random_number) {
816   log::verbose("");
817   do_in_jni_thread(base::BindOnce(
818           [](uint64_t random) { HAL_CBACK(bt_hal_cbacks, le_rand_cb, random); }, random_number));
819 }
820 
le_rand()821 static int le_rand() {
822   log::verbose("");
823   if (!interface_ready()) {
824     return BT_STATUS_NOT_READY;
825   }
826 
827   do_in_main_thread(base::BindOnce(btif_dm_le_rand, get_main_thread()->BindOnce(&le_rand_btif_cb)));
828   return BT_STATUS_SUCCESS;
829 }
830 
set_event_filter_inquiry_result_all_devices()831 static int set_event_filter_inquiry_result_all_devices() {
832   if (!interface_ready()) {
833     return BT_STATUS_NOT_READY;
834   }
835   do_in_main_thread(base::BindOnce(btif_dm_set_event_filter_inquiry_result_all_devices));
836   return BT_STATUS_SUCCESS;
837 }
838 
set_default_event_mask_except(uint64_t mask,uint64_t le_mask)839 static int set_default_event_mask_except(uint64_t mask, uint64_t le_mask) {
840   if (!interface_ready()) {
841     return BT_STATUS_NOT_READY;
842   }
843   do_in_main_thread(base::BindOnce(btif_dm_set_default_event_mask_except, mask, le_mask));
844   return BT_STATUS_SUCCESS;
845 }
846 
restore_filter_accept_list()847 static int restore_filter_accept_list() {
848   if (!interface_ready()) {
849     return BT_STATUS_NOT_READY;
850   }
851   // TODO(b/260922031) - When restoring the filter accept list after a system
852   // suspend, we need to re-arm the LE connections that had `is_direct=False`.
853   // This should be the list of bonded devices and potentially any GATT
854   // connections that have `is_direct=False`. Currently, we only restore LE hid
855   // devices.
856   auto le_hid_addrs = btif_storage_get_le_hid_devices();
857   do_in_main_thread(base::BindOnce(btif_dm_restore_filter_accept_list, std::move(le_hid_addrs)));
858   return BT_STATUS_SUCCESS;
859 }
860 
allow_wake_by_hid()861 static int allow_wake_by_hid() {
862   if (!interface_ready()) {
863     return BT_STATUS_NOT_READY;
864   }
865   auto le_hid_addrs = btif_storage_get_le_hid_devices();
866   auto classic_hid_addrs = btif_storage_get_wake_capable_classic_hid_devices();
867   do_in_main_thread(base::BindOnce(btif_dm_allow_wake_by_hid, std::move(classic_hid_addrs),
868                                    std::move(le_hid_addrs)));
869   return BT_STATUS_SUCCESS;
870 }
871 
set_event_filter_connection_setup_all_devices()872 static int set_event_filter_connection_setup_all_devices() {
873   if (!interface_ready()) {
874     return BT_STATUS_NOT_READY;
875   }
876   do_in_main_thread(base::BindOnce(btif_dm_set_event_filter_connection_setup_all_devices));
877   return BT_STATUS_SUCCESS;
878 }
879 
dump(int fd,const char ** arguments)880 static void dump(int fd, const char** arguments) {
881   log::debug("Started bluetooth dumpsys");
882   btif_debug_conn_dump(fd);
883   btif_debug_bond_event_dump(fd);
884   btif_debug_linkkey_type_dump(fd);
885   btif_debug_rc_dump(fd);
886   btif_debug_a2dp_dump(fd);
887   btif_debug_av_dump(fd);
888   bta_debug_av_dump(fd);
889   stack_debug_avdtp_api_dump(fd);
890   btif_sock_dump(fd);
891   bluetooth::avrcp::AvrcpService::DebugDump(fd);
892   gatt_tcb_dump(fd);
893   bta_gatt_client_dump(fd);
894   device_debug_iot_config_dump(fd);
895   BTA_HfClientDumpStatistics(fd);
896   wakelock_debug_dump(fd);
897   alarm_debug_dump(fd);
898   bluetooth::csis::CsisClient::DebugDump(fd);
899   ::bluetooth::le_audio::has::HasClient::DebugDump(fd);
900   HearingAid::DebugDump(fd);
901   LeAudioClient::DebugDump(fd);
902   LeAudioBroadcaster::DebugDump(fd);
903   VolumeControl::DebugDump(fd);
904   connection_manager::dump(fd);
905   bluetooth::bqr::DebugDump(fd);
906   AVCT_Dumpsys(fd);
907   PAN_Dumpsys(fd);
908   DumpsysHid(fd);
909   DumpsysBtaDm(fd);
910   SDP_Dumpsys(fd);
911   DumpsysRecord(fd);
912   L2CA_Dumpsys(fd);
913   DumpsysBtm(fd);
914   bluetooth::shim::Dump(fd, arguments);
915   power_telemetry::GetInstance().Dumpsys(fd);
916   log::debug("Finished bluetooth dumpsys");
917 }
918 
dumpMetrics(std::string * output)919 static void dumpMetrics(std::string* output) {
920   bluetooth::common::BluetoothMetricsLogger::GetInstance()->WriteString(output);
921 }
922 
get_remote_pbap_pce_version(const RawAddress * bd_addr)923 static int get_remote_pbap_pce_version(const RawAddress* bd_addr) {
924   // Read and restore the PCE version from local storage
925   uint16_t pce_version = 0;
926   size_t version_value_size = sizeof(pce_version);
927   if (!btif_config_get_bin(bd_addr->ToString(), BTIF_STORAGE_KEY_PBAP_PCE_VERSION,
928                            (uint8_t*)&pce_version, &version_value_size)) {
929     log::warn("Failed to read cached peer PCE version for {}", *bd_addr);
930   }
931   return pce_version;
932 }
933 
pbap_pse_dynamic_version_upgrade_is_enabled()934 static bool pbap_pse_dynamic_version_upgrade_is_enabled() {
935   log::info("PBAP PSE dynamic version upgrade is not enabled");
936   return false;
937 }
938 
get_profile_interface(const char * profile_id)939 static const void* get_profile_interface(const char* profile_id) {
940   log::info("id = {}", profile_id);
941 
942   /* sanity check */
943   if (!interface_ready()) {
944     return NULL;
945   }
946 
947   /* check for supported profile interfaces */
948   if (is_profile(profile_id, BT_PROFILE_HANDSFREE_ID)) {
949     return bluetooth::headset::GetInterface();
950   }
951 
952   if (is_profile(profile_id, BT_PROFILE_HANDSFREE_CLIENT_ID)) {
953     return btif_hf_client_get_interface();
954   }
955 
956   if (is_profile(profile_id, BT_PROFILE_SOCKETS_ID)) {
957     return btif_sock_get_interface();
958   }
959 
960   if (is_profile(profile_id, BT_PROFILE_PAN_ID)) {
961     return btif_pan_get_interface();
962   }
963 
964   if (is_profile(profile_id, BT_PROFILE_HIDHOST_ID)) {
965     return btif_hh_get_interface();
966   }
967 
968   if (is_profile(profile_id, BT_PROFILE_HIDDEV_ID)) {
969     return btif_hd_get_interface();
970   }
971 
972   if (is_profile(profile_id, BT_PROFILE_SDP_CLIENT_ID)) {
973     return btif_sdp_get_interface();
974   }
975 
976   if (is_profile(profile_id, BT_PROFILE_GATT_ID)) {
977     return btif_gatt_get_interface();
978   }
979 
980   if (is_profile(profile_id, BT_PROFILE_AV_RC_ID)) {
981     return btif_rc_get_interface();
982   }
983 
984   if (is_profile(profile_id, BT_PROFILE_AV_RC_CTRL_ID)) {
985     return btif_rc_ctrl_get_interface();
986   }
987 
988   if (is_profile(profile_id, BT_PROFILE_HEARING_AID_ID)) {
989     return btif_hearing_aid_get_interface();
990   }
991 
992   if (is_profile(profile_id, BT_PROFILE_HAP_CLIENT_ID)) {
993     return btif_has_client_get_interface();
994   }
995 
996   if (is_profile(profile_id, BT_KEYSTORE_ID)) {
997     return bluetooth::bluetooth_keystore::getBluetoothKeystoreInterface();
998   }
999 
1000   if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_ID)) {
1001     return btif_le_audio_get_interface();
1002   }
1003 
1004   if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_BROADCASTER_ID)) {
1005     return btif_le_audio_broadcaster_get_interface();
1006   }
1007 
1008   if (is_profile(profile_id, BT_PROFILE_VC_ID)) {
1009     return btif_volume_control_get_interface();
1010   }
1011 
1012   if (is_profile(profile_id, BT_PROFILE_CSIS_CLIENT_ID)) {
1013     return btif_csis_client_get_interface();
1014   }
1015 
1016   if (is_profile(profile_id, BT_BQR_ID)) {
1017     return bluetooth::bqr::getBluetoothQualityReportInterface();
1018   }
1019 
1020   return NULL;
1021 }
1022 
dut_mode_configure(uint8_t enable)1023 int dut_mode_configure(uint8_t enable) {
1024   if (!interface_ready()) {
1025     return BT_STATUS_NOT_READY;
1026   }
1027   if (!stack_manager_get_interface()->get_stack_is_running()) {
1028     return BT_STATUS_NOT_READY;
1029   }
1030 
1031   do_in_main_thread(base::BindOnce(btif_dut_mode_configure, enable));
1032   return BT_STATUS_SUCCESS;
1033 }
1034 
dut_mode_send(uint16_t opcode,uint8_t * buf,uint8_t len)1035 int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
1036   if (!interface_ready()) {
1037     return BT_STATUS_NOT_READY;
1038   }
1039   if (!btif_is_dut_mode()) {
1040     return BT_STATUS_UNEXPECTED_STATE;
1041   }
1042 
1043   uint8_t* copy = (uint8_t*)osi_calloc(len);
1044   memcpy(copy, buf, len);
1045 
1046   do_in_main_thread(base::BindOnce(
1047           [](uint16_t opcode, uint8_t* buf, uint8_t len) {
1048             btif_dut_mode_send(opcode, buf, len);
1049             osi_free(buf);
1050           },
1051           opcode, copy, len));
1052   return BT_STATUS_SUCCESS;
1053 }
1054 
le_test_mode(uint16_t opcode,uint8_t * buf,uint8_t len)1055 int le_test_mode(uint16_t opcode, uint8_t* buf, uint8_t len) {
1056   if (!interface_ready()) {
1057     return BT_STATUS_NOT_READY;
1058   }
1059 
1060   switch (opcode) {
1061     case HCI_BLE_TRANSMITTER_TEST:
1062       if (len != 3) {
1063         return BT_STATUS_PARM_INVALID;
1064       }
1065       do_in_main_thread(base::BindOnce(btif_ble_transmitter_test, buf[0], buf[1], buf[2]));
1066       break;
1067     case HCI_BLE_RECEIVER_TEST:
1068       if (len != 1) {
1069         return BT_STATUS_PARM_INVALID;
1070       }
1071       do_in_main_thread(base::BindOnce(btif_ble_receiver_test, buf[0]));
1072       break;
1073     case HCI_BLE_TEST_END:
1074       do_in_main_thread(base::BindOnce(btif_ble_test_end));
1075       break;
1076     default:
1077       return BT_STATUS_UNSUPPORTED;
1078   }
1079   return BT_STATUS_SUCCESS;
1080 }
1081 
1082 static bt_os_callouts_t* wakelock_os_callouts_saved = nullptr;
1083 
acquire_wake_lock_cb(const char * lock_name)1084 static int acquire_wake_lock_cb(const char* lock_name) {
1085   return do_in_jni_thread(base::BindOnce(
1086           base::IgnoreResult(wakelock_os_callouts_saved->acquire_wake_lock), lock_name));
1087 }
1088 
release_wake_lock_cb(const char * lock_name)1089 static int release_wake_lock_cb(const char* lock_name) {
1090   return do_in_jni_thread(base::BindOnce(
1091           base::IgnoreResult(wakelock_os_callouts_saved->release_wake_lock), lock_name));
1092 }
1093 
1094 static bt_os_callouts_t wakelock_os_callouts_jni = {
1095         sizeof(wakelock_os_callouts_jni),
1096         acquire_wake_lock_cb,
1097         release_wake_lock_cb,
1098 };
1099 
set_os_callouts(bt_os_callouts_t * callouts)1100 static int set_os_callouts(bt_os_callouts_t* callouts) {
1101   wakelock_os_callouts_saved = callouts;
1102   wakelock_set_os_callouts(&wakelock_os_callouts_jni);
1103   return BT_STATUS_SUCCESS;
1104 }
1105 
config_clear(void)1106 static int config_clear(void) {
1107   log::info("");
1108   int ret = BT_STATUS_SUCCESS;
1109   if (!btif_config_clear()) {
1110     log::error("Failed to clear btif config");
1111     ret = BT_STATUS_FAIL;
1112   }
1113 
1114   if (!device_iot_config_clear()) {
1115     log::error("Failed to clear device iot config");
1116     ret = BT_STATUS_FAIL;
1117   }
1118 
1119   return ret;
1120 }
1121 
get_avrcp_service(void)1122 static bluetooth::avrcp::ServiceInterface* get_avrcp_service(void) {
1123   return bluetooth::avrcp::AvrcpService::GetServiceInterface();
1124 }
1125 
obfuscate_address(const RawAddress & address)1126 static std::string obfuscate_address(const RawAddress& address) {
1127   return bluetooth::common::AddressObfuscator::GetInstance()->Obfuscate(address);
1128 }
1129 
get_metric_id(const RawAddress & address)1130 static int get_metric_id(const RawAddress& address) {
1131   return allocate_metric_id_from_metric_id_allocator(address);
1132 }
1133 
set_dynamic_audio_buffer_size(int codec,int size)1134 static int set_dynamic_audio_buffer_size(int codec, int size) {
1135   return btif_set_dynamic_audio_buffer_size(codec, size);
1136 }
1137 
allow_low_latency_audio(bool allowed,const RawAddress &)1138 static bool allow_low_latency_audio(bool allowed, const RawAddress& /* address */) {
1139   btif_a2dp_source_allow_low_latency_audio(allowed);
1140   return true;
1141 }
1142 
metadata_changed(const RawAddress & remote_bd_addr,int key,std::vector<uint8_t> value)1143 static void metadata_changed(const RawAddress& remote_bd_addr, int key,
1144                              std::vector<uint8_t> value) {
1145   if (!interface_ready()) {
1146     log::error("Interface not ready!");
1147     return;
1148   }
1149 
1150   do_in_main_thread(
1151           base::BindOnce(btif_dm_metadata_changed, remote_bd_addr, key, std::move(value)));
1152 }
1153 
interop_match_addr(const char * feature_name,const RawAddress * addr)1154 static bool interop_match_addr(const char* feature_name, const RawAddress* addr) {
1155   if (feature_name == NULL || addr == NULL) {
1156     return false;
1157   }
1158 
1159   int feature = interop_feature_name_to_feature_id(feature_name);
1160   if (feature == -1) {
1161     log::error("feature doesn't exist: {}", feature_name);
1162     return false;
1163   }
1164 
1165   return interop_match_addr((interop_feature_t)feature, addr);
1166 }
1167 
interop_match_name(const char * feature_name,const char * name)1168 static bool interop_match_name(const char* feature_name, const char* name) {
1169   if (feature_name == NULL || name == NULL) {
1170     return false;
1171   }
1172 
1173   int feature = interop_feature_name_to_feature_id(feature_name);
1174   if (feature == -1) {
1175     log::error("feature doesn't exist: {}", feature_name);
1176     return false;
1177   }
1178 
1179   return interop_match_name((interop_feature_t)feature, name);
1180 }
1181 
interop_match_addr_or_name(const char * feature_name,const RawAddress * addr)1182 static bool interop_match_addr_or_name(const char* feature_name, const RawAddress* addr) {
1183   if (feature_name == NULL || addr == NULL) {
1184     return false;
1185   }
1186 
1187   int feature = interop_feature_name_to_feature_id(feature_name);
1188   if (feature == -1) {
1189     log::error("feature doesn't exist: {}", feature_name);
1190     return false;
1191   }
1192 
1193   return interop_match_addr_or_name((interop_feature_t)feature, addr,
1194                                     &btif_storage_get_remote_device_property);
1195 }
1196 
interop_database_add_remove_addr(bool do_add,const char * feature_name,const RawAddress * addr,int length)1197 static void interop_database_add_remove_addr(bool do_add, const char* feature_name,
1198                                              const RawAddress* addr, int length) {
1199   if (feature_name == NULL || addr == NULL) {
1200     return;
1201   }
1202 
1203   int feature = interop_feature_name_to_feature_id(feature_name);
1204   if (feature == -1) {
1205     log::error("feature doesn't exist: {}", feature_name);
1206     return;
1207   }
1208 
1209   if (do_add) {
1210     interop_database_add_addr((interop_feature_t)feature, addr, (size_t)length);
1211   } else {
1212     interop_database_remove_addr((interop_feature_t)feature, addr);
1213   }
1214 }
1215 
interop_database_add_remove_name(bool do_add,const char * feature_name,const char * name)1216 static void interop_database_add_remove_name(bool do_add, const char* feature_name,
1217                                              const char* name) {
1218   if (feature_name == NULL || name == NULL) {
1219     return;
1220   }
1221 
1222   int feature = interop_feature_name_to_feature_id(feature_name);
1223   if (feature == -1) {
1224     log::error("feature doesn't exist: {}", feature_name);
1225     return;
1226   }
1227 
1228   if (do_add) {
1229     interop_database_add_name((interop_feature_t)feature, name);
1230   } else {
1231     interop_database_remove_name((interop_feature_t)feature, name);
1232   }
1233 }
1234 
1235 EXPORT_SYMBOL bt_interface_t bluetoothInterface = {
1236         sizeof(bluetoothInterface),
1237 #ifdef TARGET_FLOSS
1238         .set_adapter_index = set_adapter_index,
1239 #endif
1240         .init = init,
1241         .enable = enable,
1242         .disable = disable,
1243         .cleanup = cleanup,
1244         .start_rust_module = start_rust_module,
1245         .stop_rust_module = stop_rust_module,
1246         .get_adapter_properties = get_adapter_properties,
1247         .get_adapter_property = get_adapter_property,
1248         .set_scan_mode = set_scan_mode,
1249         .set_adapter_property = set_adapter_property,
1250         .get_remote_device_properties = get_remote_device_properties,
1251         .get_remote_device_property = get_remote_device_property,
1252         .set_remote_device_property = set_remote_device_property,
1253         .get_remote_service_record = nullptr,
1254         .get_remote_services = get_remote_services,
1255         .start_discovery = start_discovery,
1256         .cancel_discovery = cancel_discovery,
1257         .create_bond = create_bond,
1258         .create_bond_le = create_bond_le,
1259         .create_bond_out_of_band = create_bond_out_of_band,
1260         .remove_bond = remove_bond,
1261         .cancel_bond = cancel_bond,
1262         .pairing_is_busy = pairing_is_busy,
1263         .get_connection_state = get_connection_state,
1264         .pin_reply = pin_reply,
1265         .ssp_reply = ssp_reply,
1266         .get_profile_interface = get_profile_interface,
1267         .dut_mode_configure = dut_mode_configure,
1268         .dut_mode_send = dut_mode_send,
1269         .le_test_mode = le_test_mode,
1270         .set_os_callouts = set_os_callouts,
1271         .read_energy_info = read_energy_info,
1272         .dump = dump,
1273         .dumpMetrics = dumpMetrics,
1274         .config_clear = config_clear,
1275         .interop_database_clear = interop_database_clear,
1276         .interop_database_add = interop_database_add,
1277         .get_avrcp_service = get_avrcp_service,
1278         .obfuscate_address = obfuscate_address,
1279         .get_metric_id = get_metric_id,
1280         .set_dynamic_audio_buffer_size = set_dynamic_audio_buffer_size,
1281         .generate_local_oob_data = generate_local_oob_data,
1282         .allow_low_latency_audio = allow_low_latency_audio,
1283         .clear_event_filter = clear_event_filter,
1284         .clear_event_mask = clear_event_mask,
1285         .clear_filter_accept_list = clear_filter_accept_list,
1286         .disconnect_all_acls = disconnect_all_acls,
1287         .le_rand = le_rand,
1288         .set_event_filter_inquiry_result_all_devices = set_event_filter_inquiry_result_all_devices,
1289         .set_default_event_mask_except = set_default_event_mask_except,
1290         .restore_filter_accept_list = restore_filter_accept_list,
1291         .allow_wake_by_hid = allow_wake_by_hid,
1292         .set_event_filter_connection_setup_all_devices =
1293                 set_event_filter_connection_setup_all_devices,
1294         .get_wbs_supported = get_wbs_supported,
1295         .get_swb_supported = get_swb_supported,
1296         .is_coding_format_supported = is_coding_format_supported,
1297         .metadata_changed = metadata_changed,
1298         .interop_match_addr = interop_match_addr,
1299         .interop_match_name = interop_match_name,
1300         .interop_match_addr_or_name = interop_match_addr_or_name,
1301         .interop_database_add_remove_addr = interop_database_add_remove_addr,
1302         .interop_database_add_remove_name = interop_database_add_remove_name,
1303         .get_remote_pbap_pce_version = get_remote_pbap_pce_version,
1304         .pbap_pse_dynamic_version_upgrade_is_enabled = pbap_pse_dynamic_version_upgrade_is_enabled,
1305 };
1306 
1307 // callback reporting helpers
1308 
property_deep_copy_array(int num_properties,bt_property_t * properties)1309 bt_property_t* property_deep_copy_array(int num_properties, bt_property_t* properties) {
1310   bt_property_t* copy = nullptr;
1311   if (num_properties > 0) {
1312     size_t content_len = 0;
1313     for (int i = 0; i < num_properties; i++) {
1314       auto len = properties[i].len;
1315       if (len > 0) {
1316         content_len += len;
1317       }
1318     }
1319 
1320     copy = (bt_property_t*)osi_calloc((sizeof(bt_property_t) * num_properties) + content_len);
1321     log::assert_that(copy != nullptr, "assert failed: copy != nullptr");
1322     uint8_t* content = (uint8_t*)(copy + num_properties);
1323 
1324     for (int i = 0; i < num_properties; i++) {
1325       auto len = properties[i].len;
1326       copy[i].type = properties[i].type;
1327       copy[i].len = len;
1328       if (len <= 0) {
1329         continue;
1330       }
1331       copy[i].val = content;
1332       memcpy(content, properties[i].val, len);
1333       content += len;
1334     }
1335   }
1336   return copy;
1337 }
1338 
invoke_adapter_state_changed_cb(bt_state_t state)1339 void invoke_adapter_state_changed_cb(bt_state_t state) {
1340   do_in_jni_thread(base::BindOnce(
1341           [](bt_state_t state) { HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, state); },
1342           state));
1343 }
1344 
invoke_adapter_properties_cb(bt_status_t status,int num_properties,bt_property_t * properties)1345 void invoke_adapter_properties_cb(bt_status_t status, int num_properties,
1346                                   bt_property_t* properties) {
1347   do_in_jni_thread(base::BindOnce(
1348           [](bt_status_t status, int num_properties, bt_property_t* properties) {
1349             HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status, num_properties, properties);
1350             if (properties) {
1351               osi_free(properties);
1352             }
1353           },
1354           status, num_properties, property_deep_copy_array(num_properties, properties)));
1355 }
1356 
invoke_remote_device_properties_cb(bt_status_t status,RawAddress bd_addr,int num_properties,bt_property_t * properties)1357 void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr, int num_properties,
1358                                         bt_property_t* properties) {
1359   do_in_jni_thread(base::BindOnce(
1360           [](bt_status_t status, RawAddress bd_addr, int num_properties,
1361              bt_property_t* properties) {
1362             HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, status, &bd_addr, num_properties,
1363                       properties);
1364             if (properties) {
1365               osi_free(properties);
1366             }
1367           },
1368           status, bd_addr, num_properties, property_deep_copy_array(num_properties, properties)));
1369 }
1370 
invoke_device_found_cb(int num_properties,bt_property_t * properties)1371 void invoke_device_found_cb(int num_properties, bt_property_t* properties) {
1372   do_in_jni_thread(base::BindOnce(
1373           [](int num_properties, bt_property_t* properties) {
1374             HAL_CBACK(bt_hal_cbacks, device_found_cb, num_properties, properties);
1375             if (properties) {
1376               osi_free(properties);
1377             }
1378           },
1379           num_properties, property_deep_copy_array(num_properties, properties)));
1380 }
1381 
invoke_discovery_state_changed_cb(bt_discovery_state_t state)1382 void invoke_discovery_state_changed_cb(bt_discovery_state_t state) {
1383   do_in_jni_thread(base::BindOnce(
1384           [](bt_discovery_state_t state) {
1385             HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, state);
1386           },
1387           state));
1388 }
1389 
invoke_pin_request_cb(RawAddress bd_addr,bt_bdname_t bd_name,uint32_t cod,bool min_16_digit)1390 void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod,
1391                            bool min_16_digit) {
1392   do_in_jni_thread(base::BindOnce(
1393           [](RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod, bool min_16_digit) {
1394             HAL_CBACK(bt_hal_cbacks, pin_request_cb, &bd_addr, &bd_name, cod, min_16_digit);
1395           },
1396           bd_addr, bd_name, cod, min_16_digit));
1397 }
1398 
invoke_ssp_request_cb(RawAddress bd_addr,bt_ssp_variant_t pairing_variant,uint32_t pass_key)1399 void invoke_ssp_request_cb(RawAddress bd_addr, bt_ssp_variant_t pairing_variant,
1400                            uint32_t pass_key) {
1401   do_in_jni_thread(base::BindOnce(
1402           [](RawAddress bd_addr, bt_ssp_variant_t pairing_variant, uint32_t pass_key) {
1403             HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, pairing_variant, pass_key);
1404           },
1405           bd_addr, pairing_variant, pass_key));
1406 }
1407 
invoke_oob_data_request_cb(tBT_TRANSPORT t,bool valid,Octet16 c,Octet16 r,RawAddress raw_address,uint8_t address_type)1408 void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c, Octet16 r,
1409                                 RawAddress raw_address, uint8_t address_type) {
1410   log::info("");
1411   bt_oob_data_t oob_data = {};
1412   const char* local_name;
1413   if (get_btm_client_interface().local.BTM_ReadLocalDeviceName(&local_name) !=
1414       tBTM_STATUS::BTM_SUCCESS) {
1415     log::warn("Unable to read local device name");
1416   }
1417   for (int i = 0; i < BD_NAME_LEN; i++) {
1418     oob_data.device_name[i] = local_name[i];
1419   }
1420 
1421   // Set the local address
1422   int j = 5;
1423   for (int i = 0; i < 6; i++) {
1424     oob_data.address[i] = raw_address.address[j];
1425     j--;
1426   }
1427   oob_data.address[6] = address_type;
1428 
1429   // Each value (for C and R) is 16 octets in length
1430   bool c_empty = true;
1431   for (int i = 0; i < 16; i++) {
1432     // C cannot be all 0s, if so then we want to fail
1433     if (c[i] != 0) {
1434       c_empty = false;
1435     }
1436     oob_data.c[i] = c[i];
1437     // R is optional and may be empty
1438     oob_data.r[i] = r[i];
1439   }
1440   oob_data.is_valid = valid && !c_empty;
1441   // The oob_data_length is 2 octets in length.  The value includes the length
1442   // of itself. 16 + 16 + 2 = 34 Data 0x0022 Little Endian order 0x2200
1443   oob_data.oob_data_length[0] = 0;
1444   oob_data.oob_data_length[1] = 34;
1445   bt_status_t status = do_in_jni_thread(base::BindOnce(
1446           [](tBT_TRANSPORT t, bt_oob_data_t oob_data) {
1447             HAL_CBACK(bt_hal_cbacks, generate_local_oob_data_cb, t, oob_data);
1448           },
1449           t, oob_data));
1450   if (status != BT_STATUS_SUCCESS) {
1451     log::error("Failed to call callback!");
1452   }
1453 }
1454 
invoke_bond_state_changed_cb(bt_status_t status,RawAddress bd_addr,bt_bond_state_t state,int fail_reason)1455 void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr, bt_bond_state_t state,
1456                                   int fail_reason) {
1457   do_in_jni_thread(base::BindOnce(
1458           [](bt_status_t status, RawAddress bd_addr, bt_bond_state_t state, int fail_reason) {
1459             HAL_CBACK(bt_hal_cbacks, bond_state_changed_cb, status, &bd_addr, state, fail_reason);
1460           },
1461           status, bd_addr, state, fail_reason));
1462 }
1463 
invoke_address_consolidate_cb(RawAddress main_bd_addr,RawAddress secondary_bd_addr)1464 void invoke_address_consolidate_cb(RawAddress main_bd_addr, RawAddress secondary_bd_addr) {
1465   do_in_jni_thread(base::BindOnce(
1466           [](RawAddress main_bd_addr, RawAddress secondary_bd_addr) {
1467             HAL_CBACK(bt_hal_cbacks, address_consolidate_cb, &main_bd_addr, &secondary_bd_addr);
1468           },
1469           main_bd_addr, secondary_bd_addr));
1470 }
1471 
invoke_le_address_associate_cb(RawAddress main_bd_addr,RawAddress secondary_bd_addr,uint8_t identity_address_type)1472 void invoke_le_address_associate_cb(RawAddress main_bd_addr, RawAddress secondary_bd_addr,
1473                                     uint8_t identity_address_type) {
1474   do_in_jni_thread(base::BindOnce(
1475           [](RawAddress main_bd_addr, RawAddress secondary_bd_addr, uint8_t identity_address_type) {
1476             HAL_CBACK(bt_hal_cbacks, le_address_associate_cb, &main_bd_addr, &secondary_bd_addr,
1477                       identity_address_type);
1478           },
1479           main_bd_addr, secondary_bd_addr, identity_address_type));
1480 }
1481 
invoke_acl_state_changed_cb(bt_status_t status,RawAddress bd_addr,bt_acl_state_t state,int transport_link_type,bt_hci_error_code_t hci_reason,bt_conn_direction_t direction,uint16_t acl_handle)1482 void invoke_acl_state_changed_cb(bt_status_t status, RawAddress bd_addr, bt_acl_state_t state,
1483                                  int transport_link_type, bt_hci_error_code_t hci_reason,
1484                                  bt_conn_direction_t direction, uint16_t acl_handle) {
1485   do_in_jni_thread(base::BindOnce(
1486           [](bt_status_t status, RawAddress bd_addr, bt_acl_state_t state, int transport_link_type,
1487              bt_hci_error_code_t hci_reason, bt_conn_direction_t direction, uint16_t acl_handle) {
1488             HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, status, &bd_addr, state,
1489                       transport_link_type, hci_reason, direction, acl_handle);
1490           },
1491           status, bd_addr, state, transport_link_type, hci_reason, direction, acl_handle));
1492 }
1493 
invoke_thread_evt_cb(bt_cb_thread_evt event)1494 void invoke_thread_evt_cb(bt_cb_thread_evt event) {
1495   do_in_jni_thread(base::BindOnce(
1496           [](bt_cb_thread_evt event) {
1497             HAL_CBACK(bt_hal_cbacks, thread_evt_cb, event);
1498             if (event == DISASSOCIATE_JVM) {
1499               bt_hal_cbacks = NULL;
1500             }
1501           },
1502           event));
1503 }
1504 
invoke_le_test_mode_cb(bt_status_t status,uint16_t count)1505 void invoke_le_test_mode_cb(bt_status_t status, uint16_t count) {
1506   do_in_jni_thread(base::BindOnce(
1507           [](bt_status_t status, uint16_t count) {
1508             HAL_CBACK(bt_hal_cbacks, le_test_mode_cb, status, count);
1509           },
1510           status, count));
1511 }
1512 
1513 // takes ownership of |uid_data|
invoke_energy_info_cb(bt_activity_energy_info energy_info,bt_uid_traffic_t * uid_data)1514 void invoke_energy_info_cb(bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data) {
1515   do_in_jni_thread(base::BindOnce(
1516           [](bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data) {
1517             HAL_CBACK(bt_hal_cbacks, energy_info_cb, &energy_info, uid_data);
1518             osi_free(uid_data);
1519           },
1520           energy_info, uid_data));
1521 }
1522 
invoke_link_quality_report_cb(uint64_t timestamp,int report_id,int rssi,int snr,int retransmission_count,int packets_not_receive_count,int negative_acknowledgement_count)1523 void invoke_link_quality_report_cb(uint64_t timestamp, int report_id, int rssi, int snr,
1524                                    int retransmission_count, int packets_not_receive_count,
1525                                    int negative_acknowledgement_count) {
1526   do_in_jni_thread(base::BindOnce(
1527           [](uint64_t timestamp, int report_id, int rssi, int snr, int retransmission_count,
1528              int packets_not_receive_count, int negative_acknowledgement_count) {
1529             HAL_CBACK(bt_hal_cbacks, link_quality_report_cb, timestamp, report_id, rssi, snr,
1530                       retransmission_count, packets_not_receive_count,
1531                       negative_acknowledgement_count);
1532           },
1533           timestamp, report_id, rssi, snr, retransmission_count, packets_not_receive_count,
1534           negative_acknowledgement_count));
1535 }
1536 
invoke_switch_buffer_size_cb(bool is_low_latency_buffer_size)1537 void invoke_switch_buffer_size_cb(bool is_low_latency_buffer_size) {
1538   do_in_jni_thread(base::BindOnce(
1539           [](bool is_low_latency_buffer_size) {
1540             HAL_CBACK(bt_hal_cbacks, switch_buffer_size_cb, is_low_latency_buffer_size);
1541           },
1542           is_low_latency_buffer_size));
1543 }
1544 
invoke_switch_codec_cb(bool is_low_latency_buffer_size)1545 void invoke_switch_codec_cb(bool is_low_latency_buffer_size) {
1546   do_in_jni_thread(base::BindOnce(
1547           [](bool is_low_latency_buffer_size) {
1548             HAL_CBACK(bt_hal_cbacks, switch_codec_cb, is_low_latency_buffer_size);
1549           },
1550           is_low_latency_buffer_size));
1551 }
1552 
invoke_key_missing_cb(RawAddress bd_addr)1553 void invoke_key_missing_cb(RawAddress bd_addr) {
1554   do_in_jni_thread(base::BindOnce(
1555           [](RawAddress bd_addr) { HAL_CBACK(bt_hal_cbacks, key_missing_cb, bd_addr); }, bd_addr));
1556 }
1557 
invoke_encryption_change_cb(bt_encryption_change_evt encryption_change)1558 void invoke_encryption_change_cb(bt_encryption_change_evt encryption_change) {
1559   do_in_jni_thread(base::BindOnce(
1560           [](bt_encryption_change_evt encryption_change) {
1561             HAL_CBACK(bt_hal_cbacks, encryption_change_cb, encryption_change);
1562           },
1563           encryption_change));
1564 }
1565 
1566 namespace bluetooth::testing {
set_hal_cbacks(bt_callbacks_t * callbacks)1567 void set_hal_cbacks(bt_callbacks_t* callbacks) { ::set_hal_cbacks(callbacks); }
1568 
1569 }  // namespace bluetooth::testing
1570