1 /******************************************************************************
2  *
3  *  Copyright 2014 The Android Open Source Project
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:      btif_core.c
23  *
24  *  Description:   Contains core functionality related to interfacing between
25  *                 Bluetooth HAL and BTE core stack.
26  *
27  ******************************************************************************/
28 
29 #define LOG_TAG "bt_btif_core"
30 
31 #include <android_bluetooth_sysprop.h>
32 #include <base/at_exit.h>
33 #include <base/functional/bind.h>
34 #include <base/threading/platform_thread.h>
35 #include <bluetooth/log.h>
36 #include <com_android_bluetooth_flags.h>
37 #include <signal.h>
38 #include <sys/types.h>
39 
40 #include <cstdint>
41 
42 #include "btif/include/btif_common.h"
43 #include "btif/include/btif_config.h"
44 #include "btif/include/btif_dm.h"
45 #include "btif/include/btif_jni_task.h"
46 #include "btif/include/btif_profile_queue.h"
47 #include "btif/include/btif_sock.h"
48 #include "btif/include/btif_storage.h"
49 #include "btif/include/core_callbacks.h"
50 #include "btif/include/stack_manager_t.h"
51 #include "common/message_loop_thread.h"
52 #include "device/include/device_iot_config.h"
53 #include "hci/controller_interface.h"
54 #include "internal_include/bt_target.h"
55 #include "internal_include/bt_trace.h"
56 #include "main/shim/entry.h"
57 #include "main/shim/helpers.h"
58 #include "os/log.h"
59 #include "osi/include/allocator.h"
60 #include "osi/include/future.h"
61 #include "osi/include/properties.h"
62 #include "stack/include/a2dp_api.h"
63 #include "stack/include/bt_types.h"
64 #include "stack/include/btm_api.h"
65 #include "stack/include/btm_ble_api.h"
66 #include "storage/config_keys.h"
67 #include "types/bluetooth/uuid.h"
68 #include "types/raw_address.h"
69 
70 using base::PlatformThread;
71 using bluetooth::Uuid;
72 using bluetooth::common::MessageLoopThread;
73 using namespace bluetooth;
74 
75 /*******************************************************************************
76  *  Constants & Macros
77  ******************************************************************************/
78 
79 #ifndef BTE_DID_CONF_FILE
80 // TODO(armansito): Find a better way than searching by a hardcoded path.
81 #if defined(TARGET_FLOSS)
82 #define BTE_DID_CONF_FILE "/var/lib/bluetooth/bt_did.conf"
83 #elif defined(__ANDROID__)
84 #define BTE_DID_CONF_FILE \
85   "/apex/com.android.btservices/etc/bluetooth/bt_did.conf"
86 #else  // !defined(__ANDROID__)
87 #define BTE_DID_CONF_FILE "bt_did.conf"
88 #endif  // defined(__ANDROID__)
89 #endif  // BTE_DID_CONF_FILE
90 
91 #define CODEC_TYPE_NUMBER 32
92 #define DEFAULT_BUFFER_TIME (MAX_PCM_FRAME_NUM_PER_TICK * 2)
93 #define MAXIMUM_BUFFER_TIME (MAX_PCM_FRAME_NUM_PER_TICK * 2)
94 #define MINIMUM_BUFFER_TIME MAX_PCM_FRAME_NUM_PER_TICK
95 
96 /*******************************************************************************
97  *  Static variables
98  ******************************************************************************/
99 
100 static tBTA_SERVICE_MASK btif_enabled_services = 0;
101 
102 /*
103  * This variable should be set to 1, if the Bluedroid+BTIF libraries are to
104  * function in DUT mode.
105  *
106  * To set this, the btif_init_bluetooth needs to be called with argument as 1
107  */
108 static uint8_t btif_dut_mode = 0;
109 
110 static base::AtExitManager* exit_manager;
111 static uid_set_t* uid_set;
112 
113 /*******************************************************************************
114  *  Externs
115  ******************************************************************************/
116 void btif_dm_enable_service(tBTA_SERVICE_ID service_id, bool enable);
117 void btif_dm_load_local_oob(void);
118 
119 /*******************************************************************************
120  *
121  * Function         btif_is_dut_mode
122  *
123  * Description      checks if BTIF is currently in DUT mode
124  *
125  * Returns          true if test mode, otherwise false
126  *
127  ******************************************************************************/
128 
btif_is_dut_mode()129 bool btif_is_dut_mode() { return btif_dut_mode == 1; }
130 
131 /*******************************************************************************
132  *
133  * Function         btif_is_enabled
134  *
135  * Description      checks if main adapter is fully enabled
136  *
137  * Returns          1 if fully enabled, otherwize 0
138  *
139  ******************************************************************************/
140 
btif_is_enabled(void)141 int btif_is_enabled(void) {
142   return ((!btif_is_dut_mode()) &&
143           (stack_manager_get_interface()->get_stack_is_running()));
144 }
145 
btif_init_ok()146 void btif_init_ok() {
147   btif_dm_load_ble_local_keys();
148 }
149 
150 /*******************************************************************************
151  *
152  * Function         btif_init_bluetooth
153  *
154  * Description      Creates BTIF task and prepares BT scheduler for startup
155  *
156  * Returns          bt_status_t
157  *
158  ******************************************************************************/
btif_init_bluetooth()159 bt_status_t btif_init_bluetooth() {
160   log::info("entered");
161   exit_manager = new base::AtExitManager();
162   jni_thread_startup();
163   GetInterfaceToProfiles()->events->invoke_thread_evt_cb(ASSOCIATE_JVM);
164   log::info("finished");
165   return BT_STATUS_SUCCESS;
166 }
167 
168 /*******************************************************************************
169  *
170  * Function         btif_enable_bluetooth_evt
171  *
172  * Description      Event indicating bluetooth enable is completed
173  *                  Notifies HAL user with updated adapter state
174  *
175  * Returns          void
176  *
177  ******************************************************************************/
178 
btif_enable_bluetooth_evt()179 void btif_enable_bluetooth_evt() {
180   /* Fetch the local BD ADDR */
181   RawAddress local_bd_addr = bluetooth::ToRawAddress(
182       bluetooth::shim::GetController()->GetMacAddress());
183 
184   std::string bdstr = local_bd_addr.ToString();
185 
186   // save bd addr to iot conf file
187   device_iot_config_set_str(IOT_CONF_KEY_SECTION_ADAPTER, IOT_CONF_KEY_ADDRESS,
188                             bdstr);
189 
190   char val[PROPERTY_VALUE_MAX] = "";
191   int val_size = PROPERTY_VALUE_MAX;
192   if (!btif_config_get_str(BTIF_STORAGE_SECTION_ADAPTER,
193                            BTIF_STORAGE_KEY_ADDRESS, val, &val_size) ||
194       strcmp(bdstr.c_str(), val) != 0) {
195     // We failed to get an address or the one in the config file does not match
196     // the address given by the controller interface. Update the config cache
197     log::info("Storing '{}' into the config file", local_bd_addr);
198     btif_config_set_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS,
199                         bdstr.c_str());
200 
201     // fire HAL callback for property change
202     bt_property_t prop;
203     prop.type = BT_PROPERTY_BDADDR;
204     prop.val = (void*)&local_bd_addr;
205     prop.len = sizeof(RawAddress);
206     GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(
207         BT_STATUS_SUCCESS, 1, &prop);
208   }
209 
210   /* callback to HAL */
211   uid_set = uid_set_create();
212 
213   btif_dm_init(uid_set);
214 
215   /* init rfcomm & l2cap api */
216   btif_sock_init(uid_set);
217 
218   GetInterfaceToProfiles()->onBluetoothEnabled();
219 
220   if (!com::android::bluetooth::flags::load_did_config_from_sysprops()) {
221     bte_load_did_conf(BTE_DID_CONF_FILE);
222   } else {
223     tSDP_DI_RECORD record = {
224         .vendor = uint16_t(
225             GET_SYSPROP(DeviceIDProperties, vendor_id, LMP_COMPID_GOOGLE)),
226         .vendor_id_source = uint16_t(GET_SYSPROP(
227             DeviceIDProperties, vendor_id_source, DI_VENDOR_ID_SOURCE_BTSIG)),
228         .product = uint16_t(GET_SYSPROP(DeviceIDProperties, product_id, 0)),
229         .primary_record = true,
230     };
231 
232     uint32_t record_handle;
233     tBTA_STATUS status = BTA_DmSetLocalDiRecord(&record, &record_handle);
234     if (status != BTA_SUCCESS) {
235       log::error("unable to set device ID record error {}.",
236                  bta_status_text(status));
237     }
238   }
239 
240   btif_dm_load_local_oob();
241 
242   future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
243   log::info("Bluetooth enable event completed");
244 }
245 
246 /*******************************************************************************
247  *
248  * Function         btif_cleanup_bluetooth
249  *
250  * Description      Cleanup BTIF state.
251  *
252  * Returns          void
253  *
254  ******************************************************************************/
255 
btif_cleanup_bluetooth()256 bt_status_t btif_cleanup_bluetooth() {
257   log::info("entered");
258   btif_dm_cleanup();
259   GetInterfaceToProfiles()->events->invoke_thread_evt_cb(DISASSOCIATE_JVM);
260   btif_queue_release();
261   jni_thread_shutdown();
262   delete exit_manager;
263   exit_manager = nullptr;
264   btif_dut_mode = 0;
265   log::info("finished");
266   return BT_STATUS_SUCCESS;
267 }
268 
269 /*******************************************************************************
270  *
271  * Function         btif_dut_mode_configure
272  *
273  * Description      Configure Test Mode - 'enable' to 1 puts the device in test
274  *                       mode and 0 exits test mode
275  *
276  ******************************************************************************/
btif_dut_mode_configure(uint8_t enable)277 void btif_dut_mode_configure(uint8_t enable) {
278   log::verbose("");
279 
280   btif_dut_mode = enable;
281   if (enable == 1) {
282     BTA_EnableTestMode();
283   } else {
284     // Can't do in process reset anyways - just quit
285     kill(getpid(), SIGKILL);
286   }
287 }
288 
289 /*******************************************************************************
290  *
291  * Function         btif_dut_mode_send
292  *
293  * Description     Sends a HCI Vendor specific command to the controller
294  *
295  ******************************************************************************/
btif_dut_mode_send(uint16_t opcode,uint8_t * buf,uint8_t len)296 void btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
297   log::verbose("");
298   /* For now nothing to be done. */
299   BTM_VendorSpecificCommand(opcode, len, buf, [](tBTM_VSC_CMPL*) {});
300 }
301 
302 /*****************************************************************************
303  *
304  *   btif api adapter property functions
305  *
306  ****************************************************************************/
307 
btif_in_get_adapter_properties(void)308 static bt_status_t btif_in_get_adapter_properties(void) {
309   const static uint32_t NUM_ADAPTER_PROPERTIES = 6;
310   bt_property_t properties[NUM_ADAPTER_PROPERTIES];
311   uint32_t num_props = 0;
312 
313   RawAddress addr;
314   bt_bdname_t name;
315   bt_scan_mode_t mode;
316   uint32_t disc_timeout;
317   RawAddress bonded_devices[BTM_SEC_MAX_DEVICE_RECORDS];
318   Uuid local_uuids[BT_MAX_NUM_UUIDS];
319   bt_status_t status;
320 
321   /* RawAddress */
322   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDADDR,
323                              sizeof(addr), &addr);
324   status = btif_storage_get_adapter_property(&properties[num_props]);
325   // Add BT_PROPERTY_BDADDR property into list only when successful.
326   // Otherwise, skip this property entry.
327   if (status == BT_STATUS_SUCCESS) {
328     num_props++;
329   }
330 
331   /* BD_NAME */
332   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDNAME,
333                              sizeof(name), &name);
334   btif_storage_get_adapter_property(&properties[num_props]);
335   num_props++;
336 
337   /* SCAN_MODE */
338   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props],
339                              BT_PROPERTY_ADAPTER_SCAN_MODE, sizeof(mode),
340                              &mode);
341   btif_storage_get_adapter_property(&properties[num_props]);
342   num_props++;
343 
344   /* DISC_TIMEOUT */
345   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props],
346                              BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT,
347                              sizeof(disc_timeout), &disc_timeout);
348   btif_storage_get_adapter_property(&properties[num_props]);
349   num_props++;
350 
351   /* BONDED_DEVICES */
352   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props],
353                              BT_PROPERTY_ADAPTER_BONDED_DEVICES,
354                              sizeof(bonded_devices), bonded_devices);
355   btif_storage_get_adapter_property(&properties[num_props]);
356   num_props++;
357 
358   /* LOCAL UUIDs */
359   BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_UUIDS,
360                              sizeof(local_uuids), local_uuids);
361   btif_storage_get_adapter_property(&properties[num_props]);
362   num_props++;
363 
364   GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(
365       BT_STATUS_SUCCESS, num_props, properties);
366   return BT_STATUS_SUCCESS;
367 }
368 
btif_in_get_remote_device_properties(RawAddress * bd_addr)369 static bt_status_t btif_in_get_remote_device_properties(RawAddress* bd_addr) {
370   bt_property_t remote_properties[8];
371   uint32_t num_props = 0;
372 
373   bt_bdname_t name, alias;
374   uint32_t cod, devtype;
375   Uuid remote_uuids[BT_MAX_NUM_UUIDS];
376 
377   memset(remote_properties, 0, sizeof(remote_properties));
378   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_BDNAME,
379                              sizeof(name), &name);
380   btif_storage_get_remote_device_property(bd_addr,
381                                           &remote_properties[num_props]);
382   num_props++;
383 
384   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props],
385                              BT_PROPERTY_REMOTE_FRIENDLY_NAME, sizeof(alias),
386                              &alias);
387   btif_storage_get_remote_device_property(bd_addr,
388                                           &remote_properties[num_props]);
389   num_props++;
390 
391   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props],
392                              BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
393   btif_storage_get_remote_device_property(bd_addr,
394                                           &remote_properties[num_props]);
395   num_props++;
396 
397   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props],
398                              BT_PROPERTY_TYPE_OF_DEVICE, sizeof(devtype),
399                              &devtype);
400   btif_storage_get_remote_device_property(bd_addr,
401                                           &remote_properties[num_props]);
402   num_props++;
403 
404   BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_UUIDS,
405                              sizeof(remote_uuids), remote_uuids);
406   btif_storage_get_remote_device_property(bd_addr,
407                                           &remote_properties[num_props]);
408   num_props++;
409 
410   GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
411       BT_STATUS_SUCCESS, *bd_addr, num_props, remote_properties);
412 
413   return BT_STATUS_SUCCESS;
414 }
415 
btif_core_storage_adapter_write(bt_property_t * prop)416 static void btif_core_storage_adapter_write(bt_property_t* prop) {
417   log::verbose("type: {}, len {}, {}", prop->type, prop->len,
418                fmt::ptr(prop->val));
419   bt_status_t status = btif_storage_set_adapter_property(prop);
420   GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(status, 1,
421                                                                  prop);
422 }
423 
btif_adapter_properties_evt(bt_status_t status,uint32_t num_props,bt_property_t * p_props)424 void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props,
425                                  bt_property_t* p_props) {
426   GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(
427       status, num_props, p_props);
428 }
btif_remote_properties_evt(bt_status_t status,RawAddress * remote_addr,uint32_t num_props,bt_property_t * p_props)429 void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr,
430                                 uint32_t num_props, bt_property_t* p_props) {
431   GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
432       status, *remote_addr, num_props, p_props);
433 }
434 
435 /*******************************************************************************
436  *
437  * Function         btif_get_adapter_properties
438  *
439  * Description      Fetch all available properties (local & remote)
440  *
441  ******************************************************************************/
442 
btif_get_adapter_properties(void)443 void btif_get_adapter_properties(void) {
444   log::verbose("");
445 
446   btif_in_get_adapter_properties();
447 }
448 
449 /*******************************************************************************
450  *
451  * Function         btif_get_adapter_property
452  *
453  * Description      Fetches property value from local cache
454  *
455  ******************************************************************************/
456 
btif_get_adapter_property(bt_property_type_t type)457 void btif_get_adapter_property(bt_property_type_t type) {
458   log::verbose("{}", type);
459 
460   bt_status_t status = BT_STATUS_SUCCESS;
461   char buf[512];
462   bt_property_t prop;
463   prop.type = type;
464   prop.val = (void*)buf;
465   prop.len = sizeof(buf);
466   if (prop.type == BT_PROPERTY_LOCAL_LE_FEATURES) {
467     tBTM_BLE_VSC_CB cmn_vsc_cb;
468     bt_local_le_features_t local_le_features;
469 
470     /* LE features are not stored in storage. Should be retrived from stack
471      */
472     BTM_BleGetVendorCapabilities(&cmn_vsc_cb);
473     local_le_features.local_privacy_enabled = BTM_BleLocalPrivacyEnabled();
474 
475     prop.len = sizeof(bt_local_le_features_t);
476     if (cmn_vsc_cb.filter_support == 1)
477       local_le_features.max_adv_filter_supported = cmn_vsc_cb.max_filter;
478     else
479       local_le_features.max_adv_filter_supported = 0;
480     local_le_features.max_adv_instance = cmn_vsc_cb.adv_inst_max;
481     local_le_features.max_irk_list_size = cmn_vsc_cb.max_irk_list_sz;
482     local_le_features.rpa_offload_supported = cmn_vsc_cb.rpa_offloading;
483     local_le_features.scan_result_storage_size =
484         cmn_vsc_cb.tot_scan_results_strg;
485     local_le_features.activity_energy_info_supported =
486         cmn_vsc_cb.energy_support;
487     local_le_features.version_supported = cmn_vsc_cb.version_supported;
488     local_le_features.total_trackable_advertisers =
489         cmn_vsc_cb.total_trackable_advertisers;
490 
491     local_le_features.extended_scan_support =
492         cmn_vsc_cb.extended_scan_support > 0;
493     local_le_features.debug_logging_supported =
494         cmn_vsc_cb.debug_logging_supported > 0;
495     auto controller = bluetooth::shim::GetController();
496 
497     if (controller->SupportsBleExtendedAdvertising()) {
498       local_le_features.max_adv_instance =
499           controller->GetLeNumberOfSupportedAdverisingSets();
500     }
501     local_le_features.le_2m_phy_supported = controller->SupportsBle2mPhy();
502     local_le_features.le_coded_phy_supported =
503         controller->SupportsBleCodedPhy();
504     local_le_features.le_extended_advertising_supported =
505         controller->SupportsBleExtendedAdvertising();
506     local_le_features.le_periodic_advertising_supported =
507         controller->SupportsBlePeriodicAdvertising();
508     local_le_features.le_maximum_advertising_data_length =
509         controller->GetLeMaximumAdvertisingDataLength();
510 
511     local_le_features.dynamic_audio_buffer_supported =
512         cmn_vsc_cb.dynamic_audio_buffer_support;
513 
514     local_le_features.le_periodic_advertising_sync_transfer_sender_supported =
515         controller->SupportsBlePeriodicAdvertisingSyncTransferSender();
516     local_le_features.le_connected_isochronous_stream_central_supported =
517         controller->SupportsBleConnectedIsochronousStreamCentral();
518     local_le_features.le_isochronous_broadcast_supported =
519         controller->SupportsBleIsochronousBroadcaster();
520     local_le_features
521         .le_periodic_advertising_sync_transfer_recipient_supported =
522         controller->SupportsBlePeriodicAdvertisingSyncTransferRecipient();
523     local_le_features.adv_filter_extended_features_mask =
524         cmn_vsc_cb.adv_filter_extended_features_mask;
525     local_le_features.le_channel_sounding_supported =
526         controller->SupportsBleChannelSounding();
527 
528     memcpy(prop.val, &local_le_features, prop.len);
529   } else if (prop.type == BT_PROPERTY_DYNAMIC_AUDIO_BUFFER) {
530     tBTM_BLE_VSC_CB cmn_vsc_cb;
531     bt_dynamic_audio_buffer_item_t dynamic_audio_buffer_item;
532 
533     BTM_BleGetVendorCapabilities(&cmn_vsc_cb);
534 
535     prop.len = sizeof(bt_dynamic_audio_buffer_item_t);
536     if (GetInterfaceToProfiles()->config->isA2DPOffloadEnabled() == false) {
537       log::verbose("Get buffer millis for A2DP software encoding");
538       for (int i = 0; i < CODEC_TYPE_NUMBER; i++) {
539         dynamic_audio_buffer_item.dab_item[i] = {
540             .default_buffer_time = DEFAULT_BUFFER_TIME,
541             .maximum_buffer_time = MAXIMUM_BUFFER_TIME,
542             .minimum_buffer_time = MINIMUM_BUFFER_TIME};
543       }
544       memcpy(prop.val, &dynamic_audio_buffer_item, prop.len);
545     } else {
546       if (cmn_vsc_cb.dynamic_audio_buffer_support != 0) {
547         log::verbose("Get buffer millis for A2DP Offload");
548         tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB
549             bt_dynamic_audio_buffer_cb[CODEC_TYPE_NUMBER];
550         BTM_BleGetDynamicAudioBuffer(bt_dynamic_audio_buffer_cb);
551 
552         for (int i = 0; i < CODEC_TYPE_NUMBER; i++) {
553           dynamic_audio_buffer_item.dab_item[i] = {
554               .default_buffer_time =
555                   bt_dynamic_audio_buffer_cb[i].default_buffer_time,
556               .maximum_buffer_time =
557                   bt_dynamic_audio_buffer_cb[i].maximum_buffer_time,
558               .minimum_buffer_time =
559                   bt_dynamic_audio_buffer_cb[i].minimum_buffer_time};
560         }
561         memcpy(prop.val, &dynamic_audio_buffer_item, prop.len);
562       } else {
563         log::verbose("Don't support Dynamic Audio Buffer");
564       }
565     }
566   } else {
567     status = btif_storage_get_adapter_property(&prop);
568   }
569   GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(status, 1,
570                                                                  &prop);
571 }
572 
property_deep_copy(const bt_property_t * prop)573 bt_property_t* property_deep_copy(const bt_property_t* prop) {
574   bt_property_t* copy =
575       (bt_property_t*)osi_calloc(sizeof(bt_property_t) + prop->len);
576   copy->type = prop->type;
577   copy->len = prop->len;
578   copy->val = (uint8_t*)(copy + 1);
579   memcpy(copy->val, prop->val, prop->len);
580   return copy;
581 }
582 
583 /*******************************************************************************
584  *
585  * Function         btif_set_adapter_property
586  *
587  * Description      Updates core stack with property value and stores it in
588  *                  local cache
589  *
590  * Returns          bt_status_t
591  *
592  ******************************************************************************/
593 
btif_set_adapter_property(bt_property_t * property)594 void btif_set_adapter_property(bt_property_t* property) {
595   log::verbose("btif_set_adapter_property type: {}, len {}, {}", property->type,
596                property->len, fmt::ptr(property->val));
597 
598   switch (property->type) {
599     case BT_PROPERTY_BDNAME: {
600       char bd_name[BD_NAME_LEN + 1];
601       uint16_t name_len =
602           property->len > BD_NAME_LEN ? BD_NAME_LEN : property->len;
603       memcpy(bd_name, property->val, name_len);
604       bd_name[name_len] = '\0';
605 
606       log::verbose("set property name : {}", (char*)bd_name);
607 
608       BTA_DmSetDeviceName((const char*)bd_name);
609 
610       btif_core_storage_adapter_write(property);
611     } break;
612 
613     case BT_PROPERTY_ADAPTER_SCAN_MODE: {
614       bt_scan_mode_t mode = *(bt_scan_mode_t*)property->val;
615       log::verbose("set property scan mode : {:x}", mode);
616 
617       if (BTA_DmSetVisibility(mode)) {
618         btif_core_storage_adapter_write(property);
619       }
620     } break;
621     case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: {
622       /* Nothing to do beside store the value in NV.  Java
623          will change the SCAN_MODE property after setting timeout,
624          if required */
625       btif_core_storage_adapter_write(property);
626     } break;
627     default:
628       break;
629   }
630 }
631 
632 /*******************************************************************************
633  *
634  * Function         btif_get_remote_device_property
635  *
636  * Description      Fetches the remote device property from the NVRAM
637  *
638  ******************************************************************************/
btif_get_remote_device_property(RawAddress remote_addr,bt_property_type_t type)639 void btif_get_remote_device_property(RawAddress remote_addr,
640                                      bt_property_type_t type) {
641   char buf[1024];
642   bt_property_t prop;
643   prop.type = type;
644   prop.val = (void*)buf;
645   prop.len = sizeof(buf);
646 
647   bt_status_t status =
648       btif_storage_get_remote_device_property(&remote_addr, &prop);
649   GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
650       status, remote_addr, 1, &prop);
651 }
652 
653 /*******************************************************************************
654  *
655  * Function         btif_get_remote_device_properties
656  *
657  * Description      Fetches all the remote device properties from NVRAM
658  *
659  ******************************************************************************/
btif_get_remote_device_properties(RawAddress remote_addr)660 void btif_get_remote_device_properties(RawAddress remote_addr) {
661   btif_in_get_remote_device_properties(&remote_addr);
662 }
663 
664 /*******************************************************************************
665  *
666  * Function         btif_set_remote_device_property
667  *
668  * Description      Writes the remote device property to NVRAM.
669  *                  Currently, BT_PROPERTY_REMOTE_FRIENDLY_NAME is the only
670  *                  remote device property that can be set
671  *
672  ******************************************************************************/
btif_set_remote_device_property(RawAddress * remote_addr,bt_property_t * property)673 void btif_set_remote_device_property(RawAddress* remote_addr,
674                                      bt_property_t* property) {
675   btif_storage_set_remote_device_property(remote_addr, property);
676 }
677 
678 /*******************************************************************************
679  *
680  * Function         btif_get_enabled_services_mask
681  *
682  * Description      Fetches currently enabled services
683  *
684  * Returns          tBTA_SERVICE_MASK
685  *
686  ******************************************************************************/
687 
btif_get_enabled_services_mask(void)688 tBTA_SERVICE_MASK btif_get_enabled_services_mask(void) {
689   return btif_enabled_services;
690 }
691 
692 /*******************************************************************************
693  *
694  * Function         btif_enable_service
695  *
696  * Description      Enables the service 'service_ID' to the service_mask.
697  *                  Upon BT enable, BTIF core shall invoke the BTA APIs to
698  *                  enable the profiles
699  *
700  ******************************************************************************/
btif_enable_service(tBTA_SERVICE_ID service_id)701 void btif_enable_service(tBTA_SERVICE_ID service_id) {
702   btif_enabled_services |= (1 << service_id);
703 
704   log::verbose("current services:0x{:x}", btif_enabled_services);
705 
706   if (btif_is_enabled()) {
707     btif_dm_enable_service(service_id, true);
708   }
709 }
710 /*******************************************************************************
711  *
712  * Function         btif_disable_service
713  *
714  * Description      Disables the service 'service_ID' to the service_mask.
715  *                  Upon BT disable, BTIF core shall invoke the BTA APIs to
716  *                  disable the profiles
717  *
718  ******************************************************************************/
btif_disable_service(tBTA_SERVICE_ID service_id)719 void btif_disable_service(tBTA_SERVICE_ID service_id) {
720   btif_enabled_services &= (tBTA_SERVICE_MASK)(~(1 << service_id));
721 
722   log::verbose("Current Services:0x{:x}", btif_enabled_services);
723 
724   if (btif_is_enabled()) {
725     btif_dm_enable_service(service_id, false);
726   }
727 }
728 
btif_set_dynamic_audio_buffer_size(int codec,int size)729 bt_status_t btif_set_dynamic_audio_buffer_size(int codec, int size) {
730   log::verbose("");
731 
732   tBTM_BLE_VSC_CB cmn_vsc_cb;
733   BTM_BleGetVendorCapabilities(&cmn_vsc_cb);
734 
735   if (!GetInterfaceToProfiles()->config->isA2DPOffloadEnabled()) {
736     log::verbose("Set buffer size ({}) for A2DP software encoding", size);
737     GetInterfaceToProfiles()
738         ->profileSpecific_HACK->btif_av_set_dynamic_audio_buffer_size(
739             uint8_t(size));
740   } else {
741     if (cmn_vsc_cb.dynamic_audio_buffer_support != 0) {
742       log::verbose("Set buffer size ({}) for A2DP offload", size);
743       uint16_t firmware_tx_buffer_length_byte;
744       firmware_tx_buffer_length_byte = static_cast<uint16_t>(size);
745       log::info("firmware_tx_buffer_length_byte: {}",
746                 firmware_tx_buffer_length_byte);
747       bluetooth::shim::GetController()->SetDabAudioBufferTime(
748           firmware_tx_buffer_length_byte);
749     }
750   }
751 
752   return BT_STATUS_SUCCESS;
753 }
754