• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2003-2014 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains the action functions for device manager state
22  *  machine.
23  *
24  ******************************************************************************/
25 
26 #define LOG_TAG "bt_bta_dm"
27 
28 #include <base/logging.h>
29 #ifdef __ANDROID__
30 #include <bta.sysprop.h>
31 #endif
32 
33 #include <cstdint>
34 
35 #include "bta/dm/bta_dm_int.h"
36 #include "bta/gatt/bta_gattc_int.h"
37 #include "bta/include/bta_dm_ci.h"
38 #include "bta_sdp_api.h"
39 #include "btif/include/btif_config.h"
40 #include "btif/include/btif_dm.h"
41 #include "btif/include/btif_storage.h"
42 #include "btif/include/stack_manager.h"
43 #include "device/include/controller.h"
44 #include "device/include/interop.h"
45 #include "gd/common/init_flags.h"
46 #include "main/shim/acl_api.h"
47 #include "main/shim/btm_api.h"
48 #include "main/shim/dumpsys.h"
49 #include "main/shim/shim.h"
50 #include "osi/include/allocator.h"
51 #include "osi/include/compat.h"
52 #include "osi/include/fixed_queue.h"
53 #include "osi/include/log.h"
54 #include "osi/include/osi.h"
55 #include "osi/include/properties.h"
56 #include "sdp_api.h"
57 #include "stack/btm/btm_ble_int.h"
58 #include "stack/btm/btm_dev.h"
59 #include "stack/btm/btm_sec.h"
60 #include "stack/btm/neighbor_inquiry.h"
61 #include "stack/gatt/connection_manager.h"
62 #include "stack/include/acl_api.h"
63 #include "stack/include/avrc_api.h"
64 #include "stack/include/bt_hdr.h"
65 #include "stack/include/bt_octets.h"
66 #include "stack/include/bt_types.h"
67 #include "stack/include/btm_client_interface.h"
68 #include "stack/include/btm_log_history.h"
69 #include "stack/include/btu.h"       // do_in_main_thread
70 #include "stack/include/srvc_api.h"  // DIS_ReadDISInfo
71 #include "stack/sdp/sdpint.h"
72 #include "types/bluetooth/uuid.h"
73 #include "types/raw_address.h"
74 
75 #if (GAP_INCLUDED == TRUE)
76 #include "gap_api.h"
77 #endif
78 
79 using bluetooth::Uuid;
80 
81 namespace {
82 constexpr char kBtmLogTag[] = "SDP";
83 }
84 
85 void BTIF_dm_disable();
86 void BTIF_dm_enable();
87 void btm_ble_adv_init(void);
88 void btm_ble_scanner_init(void);
89 
90 static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status);
91 static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir,
92                                   uint16_t eir_len);
93 static void bta_dm_inq_cmpl_cb(void* p_result);
94 static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr,
95                                                 DEV_CLASS dc,
96                                                 tBTM_BD_NAME bd_name);
97 static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p);
98 static void bta_dm_find_services(const RawAddress& bd_addr);
99 static void bta_dm_discover_next_device(void);
100 static void bta_dm_sdp_callback(tSDP_STATUS sdp_status);
101 static uint8_t bta_dm_pin_cback(const RawAddress& bd_addr, DEV_CLASS dev_class,
102                                 const tBTM_BD_NAME bd_name, bool min_16_digit);
103 static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr,
104                                          DEV_CLASS dev_class,
105                                          tBTM_BD_NAME bd_name,
106                                          const LinkKey& key, uint8_t key_type,
107                                          bool is_ctkd);
108 static void bta_dm_authentication_complete_cback(const RawAddress& bd_addr,
109                                                  DEV_CLASS dev_class,
110                                                  tBTM_BD_NAME bd_name,
111                                                  tHCI_REASON result);
112 static void bta_dm_local_name_cback(void* p_name);
113 static void bta_dm_check_av();
114 
115 void BTA_dm_update_policy(tBTA_SYS_CONN_STATUS status, uint8_t id,
116                           uint8_t app_id, const RawAddress& peer_addr);
117 
118 /* Extended Inquiry Response */
119 static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data);
120 
121 static void bta_dm_set_eir(char* local_name);
122 
123 static void bta_dm_search_timer_cback(void* data);
124 static void bta_dm_disable_conn_down_timer_cback(void* data);
125 void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id,
126                      const RawAddress& peer_addr);
127 static void bta_dm_adjust_roles(bool delay_role_switch);
128 static char* bta_dm_get_remname(void);
129 static void bta_dm_bond_cancel_complete_cback(tBTM_STATUS result);
130 
131 static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr,
132                                            tBT_TRANSPORT transport);
133 static void bta_dm_discover_device(const RawAddress& remote_bd_addr);
134 
135 static void bta_dm_disable_search_and_disc(void);
136 
137 static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, const RawAddress& bda,
138                                     tBTM_LE_EVT_DATA* p_data);
139 static void bta_dm_ble_id_key_cback(uint8_t key_type,
140                                     tBTM_BLE_LOCAL_KEYS* p_key);
141 static void bta_dm_gattc_register(void);
142 static void btm_dm_start_gatt_discovery(const RawAddress& bd_addr);
143 static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data);
144 tBTM_CONTRL_STATE bta_dm_pm_obtain_controller_state(void);
145 #if (BLE_VND_INCLUDED == TRUE)
146 static void bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result);
147 #endif
148 
149 #ifndef BTA_DM_BLE_ADV_CHNL_MAP
150 #define BTA_DM_BLE_ADV_CHNL_MAP \
151   (BTM_BLE_ADV_CHNL_37 | BTM_BLE_ADV_CHNL_38 | BTM_BLE_ADV_CHNL_39)
152 #endif
153 
154 /* Disable timer interval (in milliseconds) */
155 #ifndef BTA_DM_DISABLE_TIMER_MS
156 #define BTA_DM_DISABLE_TIMER_MS (2000)
157 #endif
158 
159 /* Disable timer retrial interval (in milliseconds) */
160 #ifndef BTA_DM_DISABLE_TIMER_RETRIAL_MS
161 #define BTA_DM_DISABLE_TIMER_RETRIAL_MS 1500
162 #endif
163 
164 /* Disable connection down timer (in milliseconds) */
165 #ifndef BTA_DM_DISABLE_CONN_DOWN_TIMER_MS
166 #define BTA_DM_DISABLE_CONN_DOWN_TIMER_MS 100
167 #endif
168 
169 /* Switch delay timer (in milliseconds) */
170 #ifndef BTA_DM_SWITCH_DELAY_TIMER_MS
171 #define BTA_DM_SWITCH_DELAY_TIMER_MS 500
172 #endif
173 
174 /* Sysprop path for page timeout */
175 #ifndef PROPERTY_PAGE_TIMEOUT
176 #define PROPERTY_PAGE_TIMEOUT "bluetooth.core.classic.page_timeout"
177 #endif
178 
179 // Time to wait after receiving shutdown request to delay the actual shutdown
180 // process. This time may be zero which invokes immediate shutdown.
get_DisableDelayTimerInMs()181 static uint64_t get_DisableDelayTimerInMs() {
182 #ifndef __ANDROID__
183   return 200;
184 #else
185   static const uint64_t kDisableDelayTimerInMs =
186       android::sysprop::bluetooth::Bta::disable_delay().value_or(200);
187   return kDisableDelayTimerInMs;
188 #endif
189 }
190 namespace {
191 
192 struct WaitForAllAclConnectionsToDrain {
193   uint64_t time_to_wait_in_ms;
TimeToWaitInMs__anondf0e788b0211::WaitForAllAclConnectionsToDrain194   unsigned long TimeToWaitInMs() const {
195     return static_cast<unsigned long>(time_to_wait_in_ms);
196   }
AlarmCallbackData__anondf0e788b0211::WaitForAllAclConnectionsToDrain197   void* AlarmCallbackData() const {
198     return const_cast<void*>(static_cast<const void*>(this));
199   }
200 
201   static const WaitForAllAclConnectionsToDrain* FromAlarmCallbackData(
202       void* data);
203   static bool IsFirstPass(const WaitForAllAclConnectionsToDrain*);
204 } first_pass =
205     {
206         .time_to_wait_in_ms = static_cast<uint64_t>(BTA_DM_DISABLE_TIMER_MS),
207 },
208   second_pass = {
209       .time_to_wait_in_ms =
210           static_cast<uint64_t>(BTA_DM_DISABLE_TIMER_RETRIAL_MS),
211 };
212 
IsFirstPass(const WaitForAllAclConnectionsToDrain * pass)213 bool WaitForAllAclConnectionsToDrain::IsFirstPass(
214     const WaitForAllAclConnectionsToDrain* pass) {
215   return pass == &first_pass;
216 }
217 
218 const WaitForAllAclConnectionsToDrain*
FromAlarmCallbackData(void * data)219 WaitForAllAclConnectionsToDrain::FromAlarmCallbackData(void* data) {
220   return const_cast<const WaitForAllAclConnectionsToDrain*>(
221       static_cast<WaitForAllAclConnectionsToDrain*>(data));
222 }
223 
224 }  // namespace
225 
226 static void bta_dm_reset_sec_dev_pending(const RawAddress& remote_bd_addr);
227 static void bta_dm_remove_sec_dev_entry(const RawAddress& remote_bd_addr);
228 static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq,
229                                       const uint8_t* p_eir, uint16_t eir_len);
230 static void bta_dm_observe_cmpl_cb(void* p_result);
231 static void bta_dm_delay_role_switch_cback(void* data);
232 static void bta_dm_wait_for_acl_to_drain_cback(void* data);
233 
234 const uint16_t bta_service_id_to_uuid_lkup_tbl[BTA_MAX_SERVICE_ID] = {
235     UUID_SERVCLASS_PNP_INFORMATION,       /* Reserved */
236     UUID_SERVCLASS_SERIAL_PORT,           /* BTA_SPP_SERVICE_ID */
237     UUID_SERVCLASS_DIALUP_NETWORKING,     /* BTA_DUN_SERVICE_ID */
238     UUID_SERVCLASS_AUDIO_SOURCE,          /* BTA_A2DP_SOURCE_SERVICE_ID */
239     UUID_SERVCLASS_LAN_ACCESS_USING_PPP,  /* BTA_LAP_SERVICE_ID */
240     UUID_SERVCLASS_HEADSET,               /* BTA_HSP_HS_SERVICE_ID */
241     UUID_SERVCLASS_HF_HANDSFREE,          /* BTA_HFP_HS_SERVICE_ID */
242     UUID_SERVCLASS_OBEX_OBJECT_PUSH,      /* BTA_OPP_SERVICE_ID */
243     UUID_SERVCLASS_OBEX_FILE_TRANSFER,    /* BTA_FTP_SERVICE_ID */
244     UUID_SERVCLASS_CORDLESS_TELEPHONY,    /* BTA_CTP_SERVICE_ID */
245     UUID_SERVCLASS_INTERCOM,              /* BTA_ICP_SERVICE_ID */
246     UUID_SERVCLASS_IRMC_SYNC,             /* BTA_SYNC_SERVICE_ID */
247     UUID_SERVCLASS_DIRECT_PRINTING,       /* BTA_BPP_SERVICE_ID */
248     UUID_SERVCLASS_IMAGING_RESPONDER,     /* BTA_BIP_SERVICE_ID */
249     UUID_SERVCLASS_PANU,                  /* BTA_PANU_SERVICE_ID */
250     UUID_SERVCLASS_NAP,                   /* BTA_NAP_SERVICE_ID */
251     UUID_SERVCLASS_GN,                    /* BTA_GN_SERVICE_ID */
252     UUID_SERVCLASS_SAP,                   /* BTA_SAP_SERVICE_ID */
253     UUID_SERVCLASS_AUDIO_SINK,            /* BTA_A2DP_SERVICE_ID */
254     UUID_SERVCLASS_AV_REMOTE_CONTROL,     /* BTA_AVRCP_SERVICE_ID */
255     UUID_SERVCLASS_HUMAN_INTERFACE,       /* BTA_HID_SERVICE_ID */
256     UUID_SERVCLASS_VIDEO_SINK,            /* BTA_VDP_SERVICE_ID */
257     UUID_SERVCLASS_PBAP_PSE,              /* BTA_PBAP_SERVICE_ID */
258     UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTA_HSP_SERVICE_ID */
259     UUID_SERVCLASS_AG_HANDSFREE,          /* BTA_HFP_SERVICE_ID */
260     UUID_SERVCLASS_MESSAGE_ACCESS,        /* BTA_MAP_SERVICE_ID */
261     UUID_SERVCLASS_MESSAGE_NOTIFICATION,  /* BTA_MN_SERVICE_ID */
262     UUID_SERVCLASS_HDP_PROFILE,           /* BTA_HDP_SERVICE_ID */
263     UUID_SERVCLASS_PBAP_PCE,              /* BTA_PCE_SERVICE_ID */
264     UUID_PROTOCOL_ATT                     /* BTA_GATT_SERVICE_ID */
265 };
266 
267 /* bta security callback */
268 const tBTM_APPL_INFO bta_security = {
269     .p_pin_callback = &bta_dm_pin_cback,
270     .p_link_key_callback = &bta_dm_new_link_key_cback,
271     .p_auth_complete_callback = &bta_dm_authentication_complete_cback,
272     .p_bond_cancel_cmpl_callback = &bta_dm_bond_cancel_complete_cback,
273     .p_sp_callback = &bta_dm_sp_cback,
274     .p_le_callback = &bta_dm_ble_smp_cback,
275     .p_le_key_callback = &bta_dm_ble_id_key_cback};
276 
277 #define MAX_DISC_RAW_DATA_BUF (4096)
278 uint8_t g_disc_raw_data_buf[MAX_DISC_RAW_DATA_BUF];
279 
280 // Stores the local Input/Output Capabilities of the Bluetooth device.
281 static uint8_t btm_local_io_caps;
282 
283 /** Initialises the BT device manager */
bta_dm_enable(tBTA_DM_SEC_CBACK * p_sec_cback)284 void bta_dm_enable(tBTA_DM_SEC_CBACK* p_sec_cback) {
285   /* make sure security callback is saved - if no callback, do not erase the
286   previous one,
287   it could be an error recovery mechanism */
288   if (p_sec_cback != NULL) bta_dm_cb.p_sec_cback = p_sec_cback;
289 
290   btm_local_io_caps = btif_storage_get_local_io_caps();
291 }
292 
bta_dm_search_set_state(tBTA_DM_STATE state)293 void bta_dm_search_set_state(tBTA_DM_STATE state) {
294   bta_dm_search_cb.state = state;
295 }
bta_dm_search_get_state()296 tBTA_DM_STATE bta_dm_search_get_state() { return bta_dm_search_cb.state; }
297 
298 /*******************************************************************************
299  *
300  * Function         bta_dm_init_cb
301  *
302  * Description      Initializes the bta_dm_cb control block
303  *
304  *
305  * Returns          void
306  *
307  ******************************************************************************/
bta_dm_init_cb(void)308 void bta_dm_init_cb(void) {
309   bta_dm_cb = {};
310   bta_dm_cb.disable_timer = alarm_new("bta_dm.disable_timer");
311   bta_dm_cb.switch_delay_timer = alarm_new("bta_dm.switch_delay_timer");
312   for (size_t i = 0; i < BTA_DM_NUM_PM_TIMER; i++) {
313     for (size_t j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) {
314       bta_dm_cb.pm_timer[i].timer[j] = alarm_new("bta_dm.pm_timer");
315     }
316   }
317 }
318 
319 /*******************************************************************************
320  *
321  * Function         bta_dm_deinit_cb
322  *
323  * Description      De-initializes the bta_dm_cb control block
324  *
325  *
326  * Returns          void
327  *
328  ******************************************************************************/
bta_dm_deinit_cb(void)329 void bta_dm_deinit_cb(void) {
330   /*
331    * TODO: Should alarm_free() the bta_dm_cb timers during graceful
332    * shutdown.
333    */
334   alarm_free(bta_dm_cb.disable_timer);
335   alarm_free(bta_dm_cb.switch_delay_timer);
336   for (size_t i = 0; i < BTA_DM_NUM_PM_TIMER; i++) {
337     for (size_t j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) {
338       alarm_free(bta_dm_cb.pm_timer[i].timer[j]);
339     }
340   }
341   bta_dm_cb = {};
342 }
343 
BTA_dm_on_hw_off()344 void BTA_dm_on_hw_off() {
345   BTIF_dm_disable();
346 
347   /* reinitialize the control block */
348   bta_dm_deinit_cb();
349 
350   /* hw is ready, go on with BTA DM initialization */
351   alarm_free(bta_dm_search_cb.search_timer);
352   alarm_free(bta_dm_search_cb.gatt_close_timer);
353   osi_free_and_reset((void**)&bta_dm_search_cb.p_pending_search);
354   fixed_queue_free(bta_dm_search_cb.pending_discovery_queue, osi_free);
355   bta_dm_search_cb = {};
356 }
357 
BTA_dm_on_hw_on()358 void BTA_dm_on_hw_on() {
359   DEV_CLASS dev_class;
360   tBTA_DM_SEC_CBACK* temp_cback;
361   uint8_t key_mask = 0;
362   tBTA_BLE_LOCAL_ID_KEYS id_key;
363 
364   /* save security callback */
365   temp_cback = bta_dm_cb.p_sec_cback;
366   /* make sure the control block is properly initialized */
367   bta_dm_init_cb();
368   /* and retrieve the callback */
369   bta_dm_cb.p_sec_cback = temp_cback;
370 
371   /* hw is ready, go on with BTA DM initialization */
372   alarm_free(bta_dm_search_cb.search_timer);
373   alarm_free(bta_dm_search_cb.gatt_close_timer);
374   osi_free_and_reset((void**)&bta_dm_search_cb.p_pending_search);
375   fixed_queue_free(bta_dm_search_cb.pending_discovery_queue, osi_free);
376   bta_dm_search_cb = {};
377   /*
378    * TODO: Should alarm_free() the bta_dm_search_cb timers during
379    * graceful shutdown.
380    */
381   bta_dm_search_cb.search_timer = alarm_new("bta_dm_search.search_timer");
382   bool delay_close_gatt =
383       osi_property_get_bool("bluetooth.gatt.delay_close.enabled", true);
384   bta_dm_search_cb.gatt_close_timer =
385       delay_close_gatt ? alarm_new("bta_dm_search.gatt_close_timer") : nullptr;
386   bta_dm_search_cb.pending_discovery_queue = fixed_queue_new(SIZE_MAX);
387 
388   memset(&bta_dm_conn_srvcs, 0, sizeof(bta_dm_conn_srvcs));
389   memset(&bta_dm_di_cb, 0, sizeof(tBTA_DM_DI_CB));
390 
391   btif_dm_get_local_class_of_device(dev_class);
392   LOG_INFO("%s: Read default class of device {0x%x, 0x%x, 0x%x}", __func__,
393       dev_class[0], dev_class[1], dev_class[2]);
394 
395   BTM_SetDeviceClass(dev_class);
396 
397   /* load BLE local information: ID keys, ER if available */
398   Octet16 er;
399   btif_dm_get_ble_local_keys(&key_mask, &er, &id_key);
400 
401   if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ER) {
402     get_btm_client_interface().ble.BTM_BleLoadLocalKeys(
403         BTA_BLE_LOCAL_KEY_TYPE_ER, (tBTM_BLE_LOCAL_KEYS*)&er);
404   }
405   if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ID) {
406     get_btm_client_interface().ble.BTM_BleLoadLocalKeys(
407         BTA_BLE_LOCAL_KEY_TYPE_ID, (tBTM_BLE_LOCAL_KEYS*)&id_key);
408   }
409   bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
410 
411   get_btm_client_interface().security.BTM_SecRegister(&bta_security);
412 
413   BTM_WritePageTimeout(osi_property_get_int32(PROPERTY_PAGE_TIMEOUT,
414                                               p_bta_dm_cfg->page_timeout));
415 
416 #if (BLE_VND_INCLUDED == TRUE)
417   BTM_BleReadControllerFeatures(bta_dm_ctrl_features_rd_cmpl_cback);
418 #else
419   /* If VSC multi adv commands are available, advertising will be initialized
420    * when capabilities are read. If they are not available, initialize
421    * advertising here */
422   btm_ble_adv_init();
423   /* Set controller features even if vendor support is not included */
424   if (bta_dm_cb.p_sec_cback)
425     bta_dm_cb.p_sec_cback(BTA_DM_LE_FEATURES_READ, NULL);
426 #endif
427 
428   btm_ble_scanner_init();
429 
430   /* Earlier, we used to invoke BTM_ReadLocalAddr which was just copying the
431      bd_addr
432      from the control block and invoking the callback which was sending the
433      DM_ENABLE_EVT.
434      But then we have a few HCI commands being invoked above which were still
435      in progress
436      when the ENABLE_EVT was sent. So modified this to fetch the local name
437      which forces
438      the DM_ENABLE_EVT to be sent only after all the init steps are complete
439      */
440   get_btm_client_interface().local.BTM_ReadLocalDeviceNameFromController(
441       bta_dm_local_name_cback);
442 
443   bta_sys_rm_register(bta_dm_rm_cback);
444 
445   /* initialize bluetooth low power manager */
446   bta_dm_init_pm();
447 
448   bta_dm_gattc_register();
449 }
450 
451 /** Disables the BT device manager */
bta_dm_disable()452 void bta_dm_disable() {
453   /* Set l2cap idle timeout to 0 (so BTE immediately disconnects ACL link after
454    * last channel is closed) */
455   L2CA_SetIdleTimeoutByBdAddr(RawAddress::kAny, 0, BT_TRANSPORT_BR_EDR);
456   L2CA_SetIdleTimeoutByBdAddr(RawAddress::kAny, 0, BT_TRANSPORT_LE);
457 
458   /* disable all active subsystems */
459   bta_sys_disable();
460 
461   BTM_SetDiscoverability(BTM_NON_DISCOVERABLE);
462   BTM_SetConnectability(BTM_NON_CONNECTABLE);
463 
464   bta_dm_disable_pm();
465   bta_dm_disable_search_and_disc();
466   bta_dm_cb.disabling = true;
467 
468   connection_manager::reset(false);
469 
470   if (BTM_GetNumAclLinks() == 0) {
471     // We can shut down faster if there are no ACL links
472     switch (get_DisableDelayTimerInMs()) {
473       case 0:
474         LOG_DEBUG("Immediately disabling device manager");
475         bta_dm_disable_conn_down_timer_cback(nullptr);
476         break;
477       default:
478         LOG_DEBUG("Set timer to delay disable initiation:%lu ms",
479                   static_cast<unsigned long>(get_DisableDelayTimerInMs()));
480         alarm_set_on_mloop(bta_dm_cb.disable_timer, get_DisableDelayTimerInMs(),
481                            bta_dm_disable_conn_down_timer_cback, nullptr);
482     }
483   } else {
484     LOG_DEBUG("Set timer to wait for all ACL connections to close:%lu ms",
485               first_pass.TimeToWaitInMs());
486     alarm_set_on_mloop(bta_dm_cb.disable_timer, first_pass.time_to_wait_in_ms,
487                        bta_dm_wait_for_acl_to_drain_cback,
488                        first_pass.AlarmCallbackData());
489   }
490 }
491 
bta_dm_consolidate(const RawAddress & identity_addr,const RawAddress & rpa)492 void bta_dm_consolidate(const RawAddress& identity_addr,
493                         const RawAddress& rpa) {
494   for (auto i = 0; i < bta_dm_cb.device_list.count; i++) {
495     if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr != rpa) continue;
496 
497     LOG_INFO("consolidating bda_dm_cb record %s -> %s",
498              ADDRESS_TO_LOGGABLE_CSTR(rpa),
499              ADDRESS_TO_LOGGABLE_CSTR(identity_addr));
500     bta_dm_cb.device_list.peer_device[i].peer_bdaddr = identity_addr;
501   }
502 }
503 
504 /*******************************************************************************
505  *
506  * Function         bta_dm_wait_for_all_acl_to_drain
507  *
508  * Description      Called if the disable timer expires
509  *                  Used to close ACL connections which are still active
510  *
511  * Returns          true if there is a device being forcefully disconnected
512  *
513  ******************************************************************************/
force_disconnect_all_acl_connections()514 static bool force_disconnect_all_acl_connections() {
515   const bool is_force_disconnect_needed = (bta_dm_cb.device_list.count > 0);
516 
517   for (auto i = 0; i < bta_dm_cb.device_list.count; i++) {
518     btm_remove_acl(bta_dm_cb.device_list.peer_device[i].peer_bdaddr,
519                    bta_dm_cb.device_list.peer_device[i].transport);
520   }
521   return is_force_disconnect_needed;
522 }
523 
bta_dm_wait_for_acl_to_drain_cback(void * data)524 static void bta_dm_wait_for_acl_to_drain_cback(void* data) {
525   ASSERT(data != nullptr);
526   const WaitForAllAclConnectionsToDrain* pass =
527       WaitForAllAclConnectionsToDrain::FromAlarmCallbackData(data);
528 
529   if (BTM_GetNumAclLinks() && force_disconnect_all_acl_connections() &&
530       WaitForAllAclConnectionsToDrain::IsFirstPass(pass)) {
531     /* DISABLE_EVT still need to be sent out to avoid java layer disable timeout
532      */
533     LOG_DEBUG(
534         "Set timer for second pass to wait for all ACL connections to "
535         "close:%lu ms ",
536         second_pass.TimeToWaitInMs());
537     alarm_set_on_mloop(bta_dm_cb.disable_timer, second_pass.time_to_wait_in_ms,
538                        bta_dm_wait_for_acl_to_drain_cback,
539                        second_pass.AlarmCallbackData());
540   } else {
541     // No ACL links to close were up or is second pass at ACL closure
542     LOG_INFO("Ensuring all ACL connections have been properly flushed");
543     bluetooth::shim::ACL_Shutdown();
544 
545     bta_dm_cb.disabling = false;
546 
547     bta_sys_remove_uuid(UUID_SERVCLASS_PNP_INFORMATION);
548     BTIF_dm_disable();
549   }
550 }
551 
552 /** Sets local device name */
bta_dm_set_dev_name(const std::vector<uint8_t> & name)553 void bta_dm_set_dev_name(const std::vector<uint8_t>& name) {
554   BTM_SetLocalDeviceName((const char*)name.data());
555   bta_dm_set_eir((char*)name.data());
556 }
557 
558 /** Sets discoverability, connectability and pairability */
BTA_DmSetVisibility(bt_scan_mode_t mode)559 bool BTA_DmSetVisibility(bt_scan_mode_t mode) {
560   tBTA_DM_DISC disc_mode_param;
561   tBTA_DM_CONN conn_mode_param;
562 
563   switch (mode) {
564     case BT_SCAN_MODE_NONE:
565       disc_mode_param = BTA_DM_NON_DISC;
566       conn_mode_param = BTA_DM_NON_CONN;
567       break;
568 
569     case BT_SCAN_MODE_CONNECTABLE:
570       disc_mode_param = BTA_DM_NON_DISC;
571       conn_mode_param = BTA_DM_CONN;
572       break;
573 
574     case BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE:
575       disc_mode_param = BTA_DM_GENERAL_DISC;
576       conn_mode_param = BTA_DM_CONN;
577       break;
578 
579     case BT_SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE:
580       disc_mode_param = BTA_DM_LIMITED_DISC;
581       conn_mode_param = BTA_DM_CONN;
582       break;
583 
584     default:
585       return false;
586   }
587 
588   BTM_SetDiscoverability(disc_mode_param);
589   BTM_SetConnectability(conn_mode_param);
590   return true;
591 }
592 
bta_dm_process_remove_device_no_callback(const RawAddress & bd_addr)593 static void bta_dm_process_remove_device_no_callback(
594     const RawAddress& bd_addr) {
595   /* need to remove all pending background connection before unpair */
596   BTA_GATTC_CancelOpen(0, bd_addr, false);
597 
598   BTM_SecDeleteDevice(bd_addr);
599 
600   /* remove all cached GATT information */
601   BTA_GATTC_Refresh(bd_addr);
602 }
603 
bta_dm_process_remove_device(const RawAddress & bd_addr)604 void bta_dm_process_remove_device(const RawAddress& bd_addr) {
605   bta_dm_process_remove_device_no_callback(bd_addr);
606 
607   /* Conclude service search if it was pending */
608   if (bta_dm_search_cb.state == BTA_DM_DISCOVER_ACTIVE &&
609       bta_dm_search_cb.peer_bdaddr == bd_addr) {
610     LOG_INFO(
611         "Device removed while service discovery was pending, "
612         "conclude the service disvovery");
613     bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID,
614                               (tGATT_STATUS)GATT_ERROR);
615   }
616 
617   if (bta_dm_cb.p_sec_cback) {
618     tBTA_DM_SEC sec_event;
619     sec_event.link_down.bd_addr = bd_addr;
620     bta_dm_cb.p_sec_cback(BTA_DM_DEV_UNPAIRED_EVT, &sec_event);
621   }
622 }
623 
624 /** Removes device, disconnects ACL link if required */
bta_dm_remove_device(const RawAddress & bd_addr)625 void bta_dm_remove_device(const RawAddress& bd_addr) {
626   /* If ACL exists for the device in the remove_bond message*/
627   bool is_bd_addr_connected =
628       BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE) ||
629       BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_BR_EDR);
630 
631   tBT_TRANSPORT other_transport = BT_TRANSPORT_AUTO;
632   if (is_bd_addr_connected) {
633     APPL_TRACE_DEBUG("%s: ACL Up count: %d", __func__,
634                      bta_dm_cb.device_list.count);
635 
636     /* Take the link down first, and mark the device for removal when
637      * disconnected */
638     for (int i = 0; i < bta_dm_cb.device_list.count; i++) {
639       auto& peer_device = bta_dm_cb.device_list.peer_device[i];
640       if (peer_device.peer_bdaddr == bd_addr) {
641         peer_device.conn_state = BTA_DM_UNPAIRING;
642 
643         /* Make sure device is not in acceptlist before we disconnect */
644         GATT_CancelConnect(0, bd_addr, false);
645 
646         btm_remove_acl(bd_addr, peer_device.transport);
647         APPL_TRACE_DEBUG("%s: transport: %d", __func__, peer_device.transport);
648 
649         /* save the other transport to check if device is connected on
650          * other_transport */
651         if (peer_device.transport == BT_TRANSPORT_LE)
652           other_transport = BT_TRANSPORT_BR_EDR;
653         else
654           other_transport = BT_TRANSPORT_LE;
655 
656         break;
657       }
658     }
659   }
660 
661   RawAddress other_address = bd_addr;
662   RawAddress other_address2 = bd_addr;
663 
664   // If it is DUMO device and device is paired as different address, unpair that
665   // device
666   bool other_address_connected =
667       (other_transport)
668           ? BTM_ReadConnectedTransportAddress(&other_address, other_transport)
669           : (BTM_ReadConnectedTransportAddress(&other_address,
670                                                BT_TRANSPORT_BR_EDR) ||
671              BTM_ReadConnectedTransportAddress(&other_address2,
672                                                BT_TRANSPORT_LE));
673   if (other_address == bd_addr) other_address = other_address2;
674 
675   if (other_address_connected) {
676     // Get real transport
677     if (other_transport == BT_TRANSPORT_AUTO) {
678       bool connected_with_br_edr =
679           BTM_IsAclConnectionUp(other_address, BT_TRANSPORT_BR_EDR);
680       other_transport =
681           connected_with_br_edr ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE;
682     }
683     LOG_INFO("other_address %s with transport %d connected",
684              ADDRESS_TO_LOGGABLE_CSTR(other_address), other_transport);
685     /* Take the link down first, and mark the device for removal when
686      * disconnected */
687     for (int i = 0; i < bta_dm_cb.device_list.count; i++) {
688       auto& peer_device = bta_dm_cb.device_list.peer_device[i];
689       if (peer_device.peer_bdaddr == other_address &&
690           peer_device.transport == other_transport) {
691         peer_device.conn_state = BTA_DM_UNPAIRING;
692         LOG_INFO("Remove ACL of address %s", ADDRESS_TO_LOGGABLE_CSTR(other_address));
693 
694         /* Make sure device is not in acceptlist before we disconnect */
695         GATT_CancelConnect(0, bd_addr, false);
696 
697         btm_remove_acl(other_address, peer_device.transport);
698         break;
699       }
700     }
701   }
702 
703   /* Delete the device mentioned in the msg */
704   if (!is_bd_addr_connected) {
705     bta_dm_process_remove_device(bd_addr);
706   }
707 
708   /* Delete the other paired device too */
709   if (!other_address_connected && !other_address.IsEmpty()) {
710     bta_dm_process_remove_device(other_address);
711   }
712 }
713 
714 /*******************************************************************************
715  *
716  * Function         bta_dm_add_device
717  *
718  * Description      This function adds a Link Key to an security database entry.
719  *                  It is normally called during host startup to restore all
720  *                  required information stored in the NVRAM.
721  ******************************************************************************/
bta_dm_add_device(std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg)722 void bta_dm_add_device(std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg) {
723   uint8_t* p_dc = NULL;
724   LinkKey* p_lc = NULL;
725 
726   /* If not all zeros, the device class has been specified */
727   if (msg->dc_known) p_dc = (uint8_t*)msg->dc;
728 
729   if (msg->link_key_known) p_lc = &msg->link_key;
730 
731     auto add_result =
732         BTM_SecAddDevice(msg->bd_addr, p_dc, msg->bd_name, nullptr, p_lc,
733                          msg->key_type, msg->pin_length);
734     if (!add_result) {
735       LOG(ERROR) << "BTA_DM: Error adding device "
736                  << ADDRESS_TO_LOGGABLE_STR(msg->bd_addr);
737     }
738 }
739 
740 /** This function forces to close the connection to a remote device and
741  * optionaly remove the device from security database if required. */
bta_dm_close_acl(const RawAddress & bd_addr,bool remove_dev,tBT_TRANSPORT transport)742 void bta_dm_close_acl(const RawAddress& bd_addr, bool remove_dev,
743                       tBT_TRANSPORT transport) {
744   uint8_t index;
745 
746   APPL_TRACE_DEBUG("bta_dm_close_acl");
747 
748   if (BTM_IsAclConnectionUp(bd_addr, transport)) {
749     for (index = 0; index < bta_dm_cb.device_list.count; index++) {
750       if (bta_dm_cb.device_list.peer_device[index].peer_bdaddr == bd_addr)
751         break;
752     }
753     if (index != bta_dm_cb.device_list.count) {
754       if (remove_dev)
755         bta_dm_cb.device_list.peer_device[index].remove_dev_pending = true;
756     } else {
757       APPL_TRACE_ERROR("unknown device, remove ACL failed");
758     }
759 
760     /* Make sure device is not in acceptlist before we disconnect */
761     GATT_CancelConnect(0, bd_addr, false);
762 
763     /* Disconnect the ACL link */
764     btm_remove_acl(bd_addr, transport);
765   }
766   /* if to remove the device from security database ? do it now */
767   else if (remove_dev) {
768     bta_dm_process_remove_device_no_callback(bd_addr);
769   }
770   /* otherwise, no action needed */
771 }
772 
773 /** Bonds with peer device */
bta_dm_bond(const RawAddress & bd_addr,tBLE_ADDR_TYPE addr_type,tBT_TRANSPORT transport,tBT_DEVICE_TYPE device_type)774 void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type,
775                  tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) {
776   LOG_DEBUG("Bonding with peer device:%s type:%s transport:%s type:%s",
777             ADDRESS_TO_LOGGABLE_CSTR(bd_addr), AddressTypeText(addr_type).c_str(),
778             bt_transport_text(transport).c_str(),
779             DeviceTypeText(device_type).c_str());
780 
781   tBTA_DM_SEC sec_event;
782   char* p_name;
783 
784   tBTM_STATUS status =
785       BTM_SecBond(bd_addr, addr_type, transport, device_type, 0, NULL);
786 
787   if (bta_dm_cb.p_sec_cback && (status != BTM_CMD_STARTED)) {
788     memset(&sec_event, 0, sizeof(tBTA_DM_SEC));
789     sec_event.auth_cmpl.bd_addr = bd_addr;
790     p_name = BTM_SecReadDevName(bd_addr);
791     if (p_name != NULL) {
792       memcpy(sec_event.auth_cmpl.bd_name, p_name, BD_NAME_LEN);
793       sec_event.auth_cmpl.bd_name[BD_NAME_LEN] = 0;
794     }
795 
796     /*      taken care of by memset [above]
797             sec_event.auth_cmpl.key_present = false;
798             sec_event.auth_cmpl.success = false;
799     */
800     sec_event.auth_cmpl.fail_reason = HCI_ERR_ILLEGAL_COMMAND;
801     if (status == BTM_SUCCESS) {
802       sec_event.auth_cmpl.success = true;
803     } else {
804       /* delete this device entry from Sec Dev DB */
805       bta_dm_remove_sec_dev_entry(bd_addr);
806     }
807     bta_dm_cb.p_sec_cback(BTA_DM_AUTH_CMPL_EVT, &sec_event);
808   }
809 }
810 
811 /** Cancels bonding with a peer device */
bta_dm_bond_cancel(const RawAddress & bd_addr)812 void bta_dm_bond_cancel(const RawAddress& bd_addr) {
813   tBTM_STATUS status;
814   tBTA_DM_SEC sec_event;
815 
816   APPL_TRACE_EVENT(" bta_dm_bond_cancel ");
817 
818   status = BTM_SecBondCancel(bd_addr);
819 
820   if (bta_dm_cb.p_sec_cback &&
821       (status != BTM_CMD_STARTED && status != BTM_SUCCESS)) {
822     sec_event.bond_cancel_cmpl.result = BTA_FAILURE;
823 
824     bta_dm_cb.p_sec_cback(BTA_DM_BOND_CANCEL_CMPL_EVT, &sec_event);
825   }
826 }
827 
828 /** Send the pin_reply to a request from BTM */
bta_dm_pin_reply(std::unique_ptr<tBTA_DM_API_PIN_REPLY> msg)829 void bta_dm_pin_reply(std::unique_ptr<tBTA_DM_API_PIN_REPLY> msg) {
830   if (msg->accept) {
831     BTM_PINCodeReply(msg->bd_addr, BTM_SUCCESS, msg->pin_len, msg->p_pin);
832   } else {
833     BTM_PINCodeReply(msg->bd_addr, BTM_NOT_AUTHORIZED, 0, NULL);
834   }
835 }
836 
837 /** Send the user confirm request reply in response to a request from BTM */
bta_dm_confirm(const RawAddress & bd_addr,bool accept)838 void bta_dm_confirm(const RawAddress& bd_addr, bool accept) {
839   BTM_ConfirmReqReply(accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, bd_addr);
840 }
841 
842 /** respond to the OOB data request for the remote device from BTM */
bta_dm_ci_rmt_oob_act(std::unique_ptr<tBTA_DM_CI_RMT_OOB> msg)843 void bta_dm_ci_rmt_oob_act(std::unique_ptr<tBTA_DM_CI_RMT_OOB> msg) {
844   BTM_RemoteOobDataReply(msg->accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED,
845                          msg->bd_addr, msg->c, msg->r);
846 }
847 
848 /*******************************************************************************
849  *
850  * Function         bta_dm_search_start
851  *
852  * Description      Starts an inquiry
853  *
854  *
855  * Returns          void
856  *
857  ******************************************************************************/
bta_dm_search_start(tBTA_DM_MSG * p_data)858 void bta_dm_search_start(tBTA_DM_MSG* p_data) {
859   bta_dm_gattc_register();
860 
861   APPL_TRACE_DEBUG("%s avoid_scatter=%d", __func__,
862                    p_bta_dm_cfg->avoid_scatter);
863 
864   BTM_ClearInqDb(nullptr);
865   /* save search params */
866   bta_dm_search_cb.p_search_cback = p_data->search.p_cback;
867   bta_dm_search_cb.services = p_data->search.services;
868 
869   const tBTM_STATUS btm_status =
870       BTM_StartInquiry(bta_dm_inq_results_cb, bta_dm_inq_cmpl_cb);
871   switch (btm_status) {
872     case BTM_CMD_STARTED:
873       // Completion callback will be executed when controller inquiry
874       // timer pops or is cancelled by the user
875       break;
876     default:
877       LOG_WARN("Unable to start device discovery search btm_status:%s",
878                btm_status_text(btm_status).c_str());
879       // Not started so completion callback is executed now
880       bta_dm_inq_cmpl(0);
881       break;
882   }
883 }
884 
885 /*******************************************************************************
886  *
887  * Function         bta_dm_search_cancel
888  *
889  * Description      Cancels an ongoing search for devices
890  *
891  *
892  * Returns          void
893  *
894  ******************************************************************************/
bta_dm_search_cancel()895 void bta_dm_search_cancel() {
896   if (BTM_IsInquiryActive()) {
897     BTM_CancelInquiry();
898     bta_dm_search_cancel_notify();
899     bta_dm_search_cmpl();
900   }
901   /* If no Service Search going on then issue cancel remote name in case it is
902      active */
903   else if (!bta_dm_search_cb.name_discover_done) {
904     BTM_CancelRemoteDeviceName();
905     bta_dm_search_cmpl();
906   } else {
907     bta_dm_inq_cmpl(0);
908   }
909 }
910 
911 /*******************************************************************************
912  *
913  * Function         bta_dm_discover
914  *
915  * Description      Discovers services on a remote device
916  *
917  *
918  * Returns          void
919  *
920  ******************************************************************************/
bta_dm_discover(tBTA_DM_MSG * p_data)921 void bta_dm_discover(tBTA_DM_MSG* p_data) {
922   /* save the search condition */
923   bta_dm_search_cb.services = BTA_ALL_SERVICE_MASK;
924 
925   bta_dm_gattc_register();
926 
927   bta_dm_search_cb.p_search_cback = p_data->discover.p_cback;
928   bta_dm_search_cb.services_to_search = bta_dm_search_cb.services;
929   bta_dm_search_cb.service_index = 0;
930   bta_dm_search_cb.services_found = 0;
931   bta_dm_search_cb.peer_name[0] = 0;
932   bta_dm_search_cb.p_btm_inq_info = BTM_InqDbRead(p_data->discover.bd_addr);
933   bta_dm_search_cb.transport = p_data->discover.transport;
934 
935   bta_dm_search_cb.name_discover_done = false;
936 
937   LOG_INFO("bta_dm_discovery: starting service discovery to %s , transport: %s",
938            ADDRESS_TO_LOGGABLE_CSTR(p_data->discover.bd_addr),
939            bt_transport_text(p_data->discover.transport).c_str());
940   bta_dm_discover_device(p_data->discover.bd_addr);
941 }
942 
943 /*******************************************************************************
944  *
945  * Function         bta_dm_disable_search_and_disc
946  *
947  * Description      Cancels an ongoing search or discovery for devices in case
948  *                  of a Bluetooth disable
949  *
950  * Returns          void
951  *
952  ******************************************************************************/
bta_dm_disable_search_and_disc(void)953 static void bta_dm_disable_search_and_disc(void) {
954   switch (bta_dm_search_get_state()) {
955     case BTA_DM_SEARCH_IDLE:
956       break;
957     case BTA_DM_SEARCH_ACTIVE:
958     case BTA_DM_SEARCH_CANCELLING:
959     case BTA_DM_DISCOVER_ACTIVE:
960     default:
961       LOG_DEBUG(
962           "Search state machine is not idle so issuing search cancel current "
963           "state:%s",
964           bta_dm_state_text(bta_dm_search_get_state()).c_str());
965       bta_dm_search_cancel();
966   }
967 }
968 
969 /*******************************************************************************
970  *
971  * Function         bta_dm_read_remote_device_name
972  *
973  * Description      Initiate to get remote device name
974  *
975  * Returns          true if started to get remote name
976  *
977  ******************************************************************************/
bta_dm_read_remote_device_name(const RawAddress & bd_addr,tBT_TRANSPORT transport)978 static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr,
979                                            tBT_TRANSPORT transport) {
980   tBTM_STATUS btm_status;
981 
982   APPL_TRACE_DEBUG("%s", __func__);
983 
984   bta_dm_search_cb.peer_bdaddr = bd_addr;
985   bta_dm_search_cb.peer_name[0] = 0;
986 
987   btm_status = BTM_ReadRemoteDeviceName(bta_dm_search_cb.peer_bdaddr,
988                                         bta_dm_remname_cback, transport);
989 
990   if (btm_status == BTM_CMD_STARTED) {
991     APPL_TRACE_DEBUG("%s: BTM_ReadRemoteDeviceName is started", __func__);
992 
993     return (true);
994   } else if (btm_status == BTM_BUSY) {
995     APPL_TRACE_DEBUG("%s: BTM_ReadRemoteDeviceName is busy", __func__);
996 
997     /* Remote name discovery is on going now so BTM cannot notify through
998      * "bta_dm_remname_cback" */
999     /* adding callback to get notified that current reading remote name done */
1000 
1001     BTM_SecAddRmtNameNotifyCallback(&bta_dm_service_search_remname_cback);
1002 
1003     return (true);
1004   } else {
1005     APPL_TRACE_WARNING("%s: BTM_ReadRemoteDeviceName returns 0x%02X", __func__,
1006                        btm_status);
1007 
1008     return (false);
1009   }
1010 }
1011 
1012 /*******************************************************************************
1013  *
1014  * Function         bta_dm_inq_cmpl
1015  *
1016  * Description      Process the inquiry complete event from BTM
1017  *
1018  * Returns          void
1019  *
1020  ******************************************************************************/
bta_dm_inq_cmpl(uint8_t num)1021 void bta_dm_inq_cmpl(uint8_t num) {
1022   if (bta_dm_search_get_state() == BTA_DM_SEARCH_CANCELLING) {
1023     bta_dm_search_set_state(BTA_DM_SEARCH_IDLE);
1024     bta_dm_execute_queued_request();
1025     return;
1026   }
1027 
1028   if (bta_dm_search_get_state() != BTA_DM_SEARCH_ACTIVE) {
1029     return;
1030   }
1031 
1032   tBTA_DM_SEARCH data;
1033 
1034   APPL_TRACE_DEBUG("bta_dm_inq_cmpl");
1035 
1036   data.inq_cmpl.num_resps = num;
1037   bta_dm_search_cb.p_search_cback(BTA_DM_INQ_CMPL_EVT, &data);
1038 
1039   bta_dm_search_cb.p_btm_inq_info = BTM_InqDbFirst();
1040   if (bta_dm_search_cb.p_btm_inq_info != NULL) {
1041     /* start name and service discovery from the first device on inquiry result
1042      */
1043     bta_dm_search_cb.name_discover_done = false;
1044     bta_dm_search_cb.peer_name[0] = 0;
1045     bta_dm_discover_device(
1046         bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr);
1047   } else {
1048     bta_dm_search_cb.services = 0;
1049     bta_dm_search_cmpl();
1050   }
1051 }
1052 
1053 /*******************************************************************************
1054  *
1055  * Function         bta_dm_rmt_name
1056  *
1057  * Description      Process the remote name result from BTM
1058  *
1059  * Returns          void
1060  *
1061  ******************************************************************************/
bta_dm_rmt_name(tBTA_DM_MSG * p_data)1062 void bta_dm_rmt_name(tBTA_DM_MSG* p_data) {
1063   APPL_TRACE_DEBUG("bta_dm_rmt_name");
1064 
1065   if (p_data->rem_name.result.disc_res.bd_name[0] &&
1066       bta_dm_search_cb.p_btm_inq_info) {
1067     bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name = true;
1068   }
1069 
1070   bta_dm_discover_device(bta_dm_search_cb.peer_bdaddr);
1071 }
1072 
1073 /*******************************************************************************
1074  *
1075  * Function         bta_dm_disc_rmt_name
1076  *
1077  * Description      Process the remote name result from BTM when application
1078  *                  wants to find the name for a bdaddr
1079  *
1080  * Returns          void
1081  *
1082  ******************************************************************************/
bta_dm_disc_rmt_name(tBTA_DM_MSG * p_data)1083 void bta_dm_disc_rmt_name(tBTA_DM_MSG* p_data) {
1084   CHECK(p_data != nullptr);
1085 
1086   APPL_TRACE_DEBUG("bta_dm_disc_rmt_name");
1087 
1088   const tBTA_DM_DISC_RES* disc_res = &p_data->rem_name.result.disc_res;
1089 
1090   BTM_LogHistory(
1091       kBtmLogTag, disc_res->bd_addr, "Remote name completed",
1092       base::StringPrintf(
1093           "status:%s name:\"%s\" service:0x%x device_type:%s num_uuids:%zu",
1094           hci_status_code_text(disc_res->hci_status).c_str(), disc_res->bd_name,
1095           disc_res->services, DeviceTypeText(disc_res->device_type).c_str(),
1096           disc_res->num_uuids));
1097 
1098   tBTM_INQ_INFO* p_btm_inq_info =
1099       BTM_InqDbRead(p_data->rem_name.result.disc_res.bd_addr);
1100   if (p_btm_inq_info) {
1101     if (p_data->rem_name.result.disc_res.bd_name[0]) {
1102       p_btm_inq_info->appl_knows_rem_name = true;
1103     }
1104   }
1105 
1106   bta_dm_discover_device(p_data->rem_name.result.disc_res.bd_addr);
1107 }
1108 
store_avrcp_profile_feature(tSDP_DISC_REC * sdp_rec)1109 static void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) {
1110   tSDP_DISC_ATTR* p_attr =
1111       SDP_FindAttributeInRec(sdp_rec, ATTR_ID_SUPPORTED_FEATURES);
1112   if (p_attr == NULL ||
1113       SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != UINT_DESC_TYPE ||
1114       SDP_DISC_ATTR_LEN(p_attr->attr_len_type) < 2) {
1115     return;
1116   }
1117 
1118   uint16_t avrcp_features = p_attr->attr_value.v.u16;
1119   if (avrcp_features == 0) {
1120     return;
1121   }
1122 
1123   if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(),
1124                           AV_REM_CTRL_FEATURES_CONFIG_KEY,
1125                           (const uint8_t*)&avrcp_features,
1126                           sizeof(avrcp_features))) {
1127     LOG_INFO("Saving avrcp_features: 0x%x", avrcp_features);
1128   } else {
1129     LOG_INFO("Failed to store avrcp_features 0x%x for %s", avrcp_features,
1130              ADDRESS_TO_LOGGABLE_CSTR(sdp_rec->remote_bd_addr));
1131   }
1132 }
1133 
bta_dm_store_audio_profiles_version()1134 static void bta_dm_store_audio_profiles_version() {
1135   struct AudioProfile {
1136     const uint16_t servclass_uuid;
1137     const uint16_t btprofile_uuid;
1138     const char* profile_key;
1139     void (*store_audio_profile_feature)(tSDP_DISC_REC*);
1140   };
1141 
1142   std::array<AudioProfile, 1> audio_profiles = {{
1143       {
1144           .servclass_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL,
1145           .btprofile_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL,
1146           .profile_key = AVRCP_CONTROLLER_VERSION_CONFIG_KEY,
1147           .store_audio_profile_feature = store_avrcp_profile_feature,
1148       },
1149   }};
1150 
1151   for (const auto& audio_profile : audio_profiles) {
1152     tSDP_DISC_REC* sdp_rec = SDP_FindServiceInDb(
1153         bta_dm_search_cb.p_sdp_db, audio_profile.servclass_uuid, NULL);
1154     if (sdp_rec == NULL) continue;
1155 
1156     if (SDP_FindAttributeInRec(sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST) == NULL)
1157       continue;
1158 
1159     uint16_t profile_version = 0;
1160     /* get profile version (if failure, version parameter is not updated) */
1161     SDP_FindProfileVersionInRec(sdp_rec, audio_profile.btprofile_uuid,
1162                                 &profile_version);
1163     if (profile_version != 0) {
1164       if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(),
1165                               audio_profile.profile_key,
1166                               (const uint8_t*)&profile_version,
1167                               sizeof(profile_version))) {
1168       } else {
1169         LOG_INFO("Failed to store peer profile version for %s",
1170                  ADDRESS_TO_LOGGABLE_CSTR(sdp_rec->remote_bd_addr));
1171       }
1172     }
1173     audio_profile.store_audio_profile_feature(sdp_rec);
1174   }
1175 }
1176 
1177 /*******************************************************************************
1178  *
1179  * Function         bta_dm_sdp_result
1180  *
1181  * Description      Process the discovery result from sdp
1182  *
1183  * Returns          void
1184  *
1185  ******************************************************************************/
bta_dm_sdp_result(tBTA_DM_MSG * p_data)1186 void bta_dm_sdp_result(tBTA_DM_MSG* p_data) {
1187   tSDP_DISC_REC* p_sdp_rec = NULL;
1188   tBTA_DM_MSG* p_msg;
1189   bool scn_found = false;
1190   uint16_t service = 0xFFFF;
1191   tSDP_PROTOCOL_ELEM pe;
1192 
1193   std::vector<Uuid> uuid_list;
1194 
1195   const tSDP_RESULT sdp_result = p_data->sdp_event.sdp_result;
1196 
1197   if ((p_data->sdp_event.sdp_result == SDP_SUCCESS) ||
1198       (p_data->sdp_event.sdp_result == SDP_NO_RECS_MATCH) ||
1199       (p_data->sdp_event.sdp_result == SDP_DB_FULL)) {
1200     APPL_TRACE_DEBUG("sdp_result::0x%x", p_data->sdp_event.sdp_result);
1201     do {
1202       p_sdp_rec = NULL;
1203       if (bta_dm_search_cb.service_index == (BTA_USER_SERVICE_ID + 1)) {
1204         if (p_sdp_rec && SDP_FindProtocolListElemInRec(
1205                              p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) {
1206           bta_dm_search_cb.peer_scn = (uint8_t)pe.params[0];
1207           scn_found = true;
1208         }
1209       } else {
1210         service =
1211             bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - 1];
1212         p_sdp_rec =
1213             SDP_FindServiceInDb(bta_dm_search_cb.p_sdp_db, service, p_sdp_rec);
1214       }
1215       /* finished with BR/EDR services, now we check the result for GATT based
1216        * service UUID */
1217       if (bta_dm_search_cb.service_index == BTA_MAX_SERVICE_ID) {
1218         /* all GATT based services */
1219 
1220         std::vector<Uuid> gatt_uuids;
1221 
1222         do {
1223           /* find a service record, report it */
1224           p_sdp_rec =
1225               SDP_FindServiceInDb(bta_dm_search_cb.p_sdp_db, 0, p_sdp_rec);
1226           if (p_sdp_rec) {
1227             Uuid service_uuid;
1228             if (SDP_FindServiceUUIDInRec(p_sdp_rec, &service_uuid)) {
1229               gatt_uuids.push_back(service_uuid);
1230             }
1231           }
1232         } while (p_sdp_rec);
1233 
1234         if (!gatt_uuids.empty()) {
1235           LOG_INFO("GATT services discovered using SDP");
1236 
1237           // send all result back to app
1238           tBTA_DM_SEARCH result;
1239           result.disc_ble_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
1240           strlcpy((char*)result.disc_ble_res.bd_name, bta_dm_get_remname(),
1241                   BD_NAME_LEN + 1);
1242 
1243           result.disc_ble_res.services = &gatt_uuids;
1244           bta_dm_search_cb.p_search_cback(BTA_DM_GATT_OVER_SDP_RES_EVT,
1245                                           &result);
1246         }
1247       } else {
1248         /* SDP_DB_FULL means some records with the
1249            required attributes were received */
1250         if (((p_data->sdp_event.sdp_result == SDP_DB_FULL) &&
1251              bta_dm_search_cb.services != BTA_ALL_SERVICE_MASK) ||
1252             (p_sdp_rec != NULL)) {
1253           if (service != UUID_SERVCLASS_PNP_INFORMATION) {
1254             bta_dm_search_cb.services_found |=
1255                 (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(
1256                     bta_dm_search_cb.service_index - 1));
1257             uint16_t tmp_svc =
1258                 bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index -
1259                                                 1];
1260             /* Add to the list of UUIDs */
1261             uuid_list.push_back(Uuid::From16Bit(tmp_svc));
1262           }
1263         }
1264       }
1265 
1266       if (bta_dm_search_cb.services == BTA_ALL_SERVICE_MASK &&
1267           bta_dm_search_cb.services_to_search == 0) {
1268         bta_dm_search_cb.service_index++;
1269       } else /* regular one service per search or PNP search */
1270         break;
1271 
1272     } while (bta_dm_search_cb.service_index <= BTA_MAX_SERVICE_ID);
1273 
1274     APPL_TRACE_DEBUG("%s services_found = %04x", __func__,
1275                      bta_dm_search_cb.services_found);
1276 
1277     /* Collect the 128-bit services here and put them into the list */
1278     if (bta_dm_search_cb.services == BTA_ALL_SERVICE_MASK) {
1279       p_sdp_rec = NULL;
1280       do {
1281         /* find a service record, report it */
1282         p_sdp_rec =
1283             SDP_FindServiceInDb_128bit(bta_dm_search_cb.p_sdp_db, p_sdp_rec);
1284         if (p_sdp_rec) {
1285           // SDP_FindServiceUUIDInRec_128bit is used only once, refactor?
1286           Uuid temp_uuid;
1287           if (SDP_FindServiceUUIDInRec_128bit(p_sdp_rec, &temp_uuid)) {
1288             uuid_list.push_back(temp_uuid);
1289           }
1290         }
1291       } while (p_sdp_rec);
1292     }
1293 
1294     if (bluetooth::common::init_flags::
1295             dynamic_avrcp_version_enhancement_is_enabled() &&
1296         bta_dm_search_cb.services_to_search == 0) {
1297       bta_dm_store_audio_profiles_version();
1298     }
1299 
1300 #if TARGET_FLOSS
1301     tSDP_DI_GET_RECORD di_record;
1302     if (SDP_GetDiRecord(1, &di_record, bta_dm_search_cb.p_sdp_db) ==
1303         SDP_SUCCESS) {
1304       tBTA_DM_SEARCH result;
1305       result.did_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
1306       result.did_res.vendor_id_src = di_record.rec.vendor_id_source;
1307       result.did_res.vendor_id = di_record.rec.vendor;
1308       result.did_res.product_id = di_record.rec.product;
1309       result.did_res.version = di_record.rec.version;
1310       bta_dm_search_cb.p_search_cback(BTA_DM_DID_RES_EVT, &result);
1311     }
1312 #endif
1313 
1314     /* if there are more services to search for */
1315     if (bta_dm_search_cb.services_to_search) {
1316       /* Free up the p_sdp_db before checking the next one */
1317       bta_dm_free_sdp_db();
1318       bta_dm_find_services(bta_dm_search_cb.peer_bdaddr);
1319     } else {
1320       /* callbacks */
1321       /* start next bd_addr if necessary */
1322 
1323       BTM_SecDeleteRmtNameNotifyCallback(&bta_dm_service_search_remname_cback);
1324 
1325       BTM_LogHistory(
1326           kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery completed",
1327           base::StringPrintf("Result:%s services_found:0x%x service_index:0x%d",
1328                              sdp_result_text(sdp_result).c_str(),
1329                              bta_dm_search_cb.services_found,
1330                              bta_dm_search_cb.service_index));
1331 
1332       p_msg = (tBTA_DM_MSG*)osi_calloc(sizeof(tBTA_DM_MSG));
1333       p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT;
1334       p_msg->disc_result.result.disc_res.result = BTA_SUCCESS;
1335       p_msg->disc_result.result.disc_res.num_uuids = uuid_list.size();
1336       p_msg->disc_result.result.disc_res.p_uuid_list = NULL;
1337       if (uuid_list.size() > 0) {
1338         // TODO(jpawlowski): make p_uuid_list into vector, and just copy
1339         // vectors, but first get rid of bta_sys_sendmsg below.
1340         p_msg->disc_result.result.disc_res.p_uuid_list =
1341             (Uuid*)osi_calloc(uuid_list.size() * sizeof(Uuid));
1342         memcpy(p_msg->disc_result.result.disc_res.p_uuid_list, uuid_list.data(),
1343                uuid_list.size() * sizeof(Uuid));
1344       }
1345       // Copy the raw_data to the discovery result structure
1346       if (bta_dm_search_cb.p_sdp_db != NULL &&
1347           bta_dm_search_cb.p_sdp_db->raw_used != 0 &&
1348           bta_dm_search_cb.p_sdp_db->raw_data != NULL) {
1349         APPL_TRACE_DEBUG("%s raw_data used = 0x%x raw_data_ptr = 0x%x",
1350                          __func__, bta_dm_search_cb.p_sdp_db->raw_used,
1351                          bta_dm_search_cb.p_sdp_db->raw_data);
1352 
1353         bta_dm_search_cb.p_sdp_db->raw_data =
1354             NULL;  // no need to free this - it is a global assigned.
1355         bta_dm_search_cb.p_sdp_db->raw_used = 0;
1356         bta_dm_search_cb.p_sdp_db->raw_size = 0;
1357       } else {
1358         APPL_TRACE_DEBUG("%s raw data size is 0 or raw_data is null!!",
1359                          __func__);
1360       }
1361       /* Done with p_sdp_db. Free it */
1362       bta_dm_free_sdp_db();
1363       p_msg->disc_result.result.disc_res.services =
1364           bta_dm_search_cb.services_found;
1365 
1366       // Piggy back the SCN over result field
1367       if (scn_found) {
1368         p_msg->disc_result.result.disc_res.result =
1369             static_cast<tBTA_STATUS>((3 + bta_dm_search_cb.peer_scn));
1370         p_msg->disc_result.result.disc_res.services |= BTA_USER_SERVICE_MASK;
1371 
1372         APPL_TRACE_EVENT(" Piggy back the SCN over result field  SCN=%d",
1373                          bta_dm_search_cb.peer_scn);
1374       }
1375       p_msg->disc_result.result.disc_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
1376       strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name,
1377               bta_dm_get_remname(), BD_NAME_LEN + 1);
1378 
1379       bta_sys_sendmsg(p_msg);
1380     }
1381   } else {
1382     BTM_LogHistory(
1383         kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery failed",
1384         base::StringPrintf("Result:%s", sdp_result_text(sdp_result).c_str()));
1385     LOG_ERROR("SDP connection failed %s", sdp_status_text(sdp_result).c_str());
1386     if (p_data->sdp_event.sdp_result == SDP_CONN_FAILED)
1387       bta_dm_search_cb.wait_disc = false;
1388 
1389     /* not able to connect go to next device */
1390     if (bta_dm_search_cb.p_sdp_db)
1391       osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db);
1392 
1393     BTM_SecDeleteRmtNameNotifyCallback(&bta_dm_service_search_remname_cback);
1394 
1395     p_msg = (tBTA_DM_MSG*)osi_calloc(sizeof(tBTA_DM_MSG));
1396     p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT;
1397     p_msg->disc_result.result.disc_res.result = BTA_FAILURE;
1398     p_msg->disc_result.result.disc_res.services =
1399         bta_dm_search_cb.services_found;
1400     p_msg->disc_result.result.disc_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
1401     strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name,
1402             bta_dm_get_remname(), BD_NAME_LEN + 1);
1403 
1404     bta_sys_sendmsg(p_msg);
1405   }
1406 }
1407 
1408 /** Callback of peer's DIS reply. This is only called for floss */
1409 #if TARGET_FLOSS
bta_dm_read_dis_cmpl(const RawAddress & addr,tDIS_VALUE * p_dis_value)1410 static void bta_dm_read_dis_cmpl(const RawAddress& addr,
1411                                  tDIS_VALUE* p_dis_value) {
1412   if (!p_dis_value) {
1413     LOG_WARN("read DIS failed");
1414   } else {
1415     tBTA_DM_SEARCH result;
1416     result.did_res.bd_addr = addr;
1417     result.did_res.vendor_id_src = p_dis_value->pnp_id.vendor_id_src;
1418     result.did_res.vendor_id = p_dis_value->pnp_id.vendor_id;
1419     result.did_res.product_id = p_dis_value->pnp_id.product_id;
1420     result.did_res.version = p_dis_value->pnp_id.product_version;
1421     bta_dm_search_cb.p_search_cback(BTA_DM_DID_RES_EVT, &result);
1422   }
1423 
1424   bta_dm_execute_queued_request();
1425 }
1426 #endif
1427 
1428 /*******************************************************************************
1429  *
1430  * Function         bta_dm_search_cmpl
1431  *
1432  * Description      Sends event to application
1433  *
1434  * Returns          void
1435  *
1436  ******************************************************************************/
bta_dm_search_cmpl()1437 void bta_dm_search_cmpl() {
1438   bta_dm_search_set_state(BTA_DM_SEARCH_IDLE);
1439 
1440   uint16_t conn_id = bta_dm_search_cb.conn_id;
1441 
1442   tBTA_DM_SEARCH result;
1443   std::vector<Uuid> gatt_services;
1444   result.disc_ble_res.services = &gatt_services;
1445   result.disc_ble_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
1446   strlcpy((char*)result.disc_ble_res.bd_name, bta_dm_get_remname(),
1447           BD_NAME_LEN + 1);
1448 
1449   bool send_gatt_results =
1450       bluetooth::common::init_flags::
1451               always_send_services_if_gatt_disc_done_is_enabled()
1452           ? bta_dm_search_cb.gatt_disc_active
1453           : false;
1454 
1455   /* no BLE connection, i.e. Classic service discovery end */
1456   if (conn_id == GATT_INVALID_CONN_ID) {
1457     if (bta_dm_search_cb.gatt_disc_active) {
1458       LOG_WARN(
1459           "GATT active but no BLE connection, likely disconnected midway "
1460           "through");
1461     } else {
1462       LOG_INFO("No BLE connection, processing classic results");
1463     }
1464   } else {
1465     btgatt_db_element_t* db = NULL;
1466     int count = 0;
1467     BTA_GATTC_GetGattDb(conn_id, 0x0000, 0xFFFF, &db, &count);
1468     if (count != 0) {
1469       for (int i = 0; i < count; i++) {
1470         // we process service entries only
1471         if (db[i].type == BTGATT_DB_PRIMARY_SERVICE) {
1472           gatt_services.push_back(db[i].uuid);
1473         }
1474       }
1475       osi_free(db);
1476       LOG_INFO(
1477           "GATT services discovered using LE Transport, will always send to "
1478           "upper layer");
1479       send_gatt_results = true;
1480     } else {
1481       LOG_WARN("Empty GATT database - no BLE services discovered");
1482     }
1483   }
1484 
1485   // send all result back to app
1486   if (send_gatt_results) {
1487     LOG_INFO("Sending GATT results to upper layer");
1488     bta_dm_search_cb.p_search_cback(BTA_DM_GATT_OVER_LE_RES_EVT, &result);
1489   }
1490 
1491   bta_dm_search_cb.p_search_cback(BTA_DM_DISC_CMPL_EVT, nullptr);
1492   bta_dm_search_cb.gatt_disc_active = false;
1493 
1494 #if TARGET_FLOSS
1495   if (DIS_ReadDISInfo(bta_dm_search_cb.peer_bdaddr, bta_dm_read_dis_cmpl,
1496                       DIS_ATTR_PNP_ID_BIT)) {
1497     return;
1498   }
1499 #endif
1500 
1501   bta_dm_execute_queued_request();
1502 }
1503 
1504 /*******************************************************************************
1505  *
1506  * Function         bta_dm_disc_result
1507  *
1508  * Description      Service discovery result when discovering services on a
1509  *                  device
1510  *
1511  * Returns          void
1512  *
1513  ******************************************************************************/
bta_dm_disc_result(tBTA_DM_MSG * p_data)1514 void bta_dm_disc_result(tBTA_DM_MSG* p_data) {
1515   APPL_TRACE_EVENT("%s", __func__);
1516 
1517   /* disc_res.device_type is set only when GATT discovery is finished in
1518    * bta_dm_gatt_disc_complete */
1519   bool is_gatt_over_ble = ((p_data->disc_result.result.disc_res.device_type &
1520                             BT_DEVICE_TYPE_BLE) != 0);
1521 
1522   /* if any BR/EDR service discovery has been done, report the event */
1523   if (!is_gatt_over_ble && (bta_dm_search_cb.services &
1524                             ((BTA_ALL_SERVICE_MASK | BTA_USER_SERVICE_MASK) &
1525                              ~BTA_BLE_SERVICE_MASK)))
1526     bta_dm_search_cb.p_search_cback(BTA_DM_DISC_RES_EVT,
1527                                     &p_data->disc_result.result);
1528 
1529   bta_dm_search_cmpl();
1530 }
1531 
1532 /*******************************************************************************
1533  *
1534  * Function         bta_dm_search_result
1535  *
1536  * Description      Service discovery result while searching for devices
1537  *
1538  * Returns          void
1539  *
1540  ******************************************************************************/
bta_dm_search_result(tBTA_DM_MSG * p_data)1541 void bta_dm_search_result(tBTA_DM_MSG* p_data) {
1542   APPL_TRACE_DEBUG("%s searching:0x%04x, result:0x%04x", __func__,
1543                    bta_dm_search_cb.services,
1544                    p_data->disc_result.result.disc_res.services);
1545 
1546   /* call back if application wants name discovery or found services that
1547    * application is searching */
1548   if ((!bta_dm_search_cb.services) ||
1549       ((bta_dm_search_cb.services) &&
1550        (p_data->disc_result.result.disc_res.services))) {
1551     bta_dm_search_cb.p_search_cback(BTA_DM_DISC_RES_EVT,
1552                                     &p_data->disc_result.result);
1553   }
1554 
1555   /* if searching did not initiate to create link */
1556   if (!bta_dm_search_cb.wait_disc) {
1557     /* if service searching is done with EIR, don't search next device */
1558     if (bta_dm_search_cb.p_btm_inq_info) bta_dm_discover_next_device();
1559   } else {
1560     /* wait until link is disconnected or timeout */
1561     bta_dm_search_cb.sdp_results = true;
1562     alarm_set_on_mloop(bta_dm_search_cb.search_timer,
1563                        1000 * (L2CAP_LINK_INACTIVITY_TOUT + 1),
1564                        bta_dm_search_timer_cback, NULL);
1565   }
1566 }
1567 
1568 /*******************************************************************************
1569  *
1570  * Function         bta_dm_search_timer_cback
1571  *
1572  * Description      Called when ACL disconnect time is over
1573  *
1574  *
1575  * Returns          void
1576  *
1577  ******************************************************************************/
bta_dm_search_timer_cback(UNUSED_ATTR void * data)1578 static void bta_dm_search_timer_cback(UNUSED_ATTR void* data) {
1579   APPL_TRACE_EVENT("%s", __func__);
1580   bta_dm_search_cb.wait_disc = false;
1581 
1582   /* proceed with next device */
1583   bta_dm_discover_next_device();
1584 }
1585 
1586 /*******************************************************************************
1587  *
1588  * Function         bta_dm_free_sdp_db
1589  *
1590  * Description      Frees SDP data base
1591  *
1592  * Returns          void
1593  *
1594  ******************************************************************************/
bta_dm_free_sdp_db()1595 void bta_dm_free_sdp_db() {
1596   osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db);
1597 }
1598 
1599 /*******************************************************************************
1600  *
1601  * Function         bta_dm_queue_search
1602  *
1603  * Description      Queues search command
1604  *
1605  * Returns          void
1606  *
1607  ******************************************************************************/
bta_dm_queue_search(tBTA_DM_MSG * p_data)1608 void bta_dm_queue_search(tBTA_DM_MSG* p_data) {
1609   if (bta_dm_search_cb.p_pending_search) {
1610     LOG_WARN("Overwrote previous device discovery inquiry scan request");
1611   }
1612   osi_free_and_reset((void**)&bta_dm_search_cb.p_pending_search);
1613   bta_dm_search_cb.p_pending_search =
1614       (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_API_SEARCH));
1615   memcpy(bta_dm_search_cb.p_pending_search, p_data, sizeof(tBTA_DM_API_SEARCH));
1616   LOG_INFO("Queued device discovery inquiry scan request");
1617 }
1618 
1619 /*******************************************************************************
1620  *
1621  * Function         bta_dm_queue_disc
1622  *
1623  * Description      Queues discovery command
1624  *
1625  * Returns          void
1626  *
1627  ******************************************************************************/
bta_dm_queue_disc(tBTA_DM_MSG * p_data)1628 void bta_dm_queue_disc(tBTA_DM_MSG* p_data) {
1629   tBTA_DM_MSG* p_pending_discovery =
1630       (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_API_DISCOVER));
1631   memcpy(p_pending_discovery, p_data, sizeof(tBTA_DM_API_DISCOVER));
1632 
1633   LOG_INFO("bta_dm_discovery: queuing service discovery to %s",
1634            ADDRESS_TO_LOGGABLE_CSTR(p_pending_discovery->discover.bd_addr));
1635   fixed_queue_enqueue(bta_dm_search_cb.pending_discovery_queue,
1636                       p_pending_discovery);
1637 }
1638 
1639 /*******************************************************************************
1640  *
1641  * Function         bta_dm_execute_queued_request
1642  *
1643  * Description      Executes queued request if one exists
1644  *
1645  * Returns          void
1646  *
1647  ******************************************************************************/
bta_dm_execute_queued_request()1648 void bta_dm_execute_queued_request() {
1649   tBTA_DM_MSG* p_pending_discovery = (tBTA_DM_MSG*)fixed_queue_try_dequeue(
1650       bta_dm_search_cb.pending_discovery_queue);
1651   if (p_pending_discovery) {
1652     LOG_INFO("%s Start pending discovery", __func__);
1653     bta_sys_sendmsg(p_pending_discovery);
1654   } else if (bta_dm_search_cb.p_pending_search) {
1655     LOG_INFO("%s Start pending search", __func__);
1656     bta_sys_sendmsg(bta_dm_search_cb.p_pending_search);
1657     bta_dm_search_cb.p_pending_search = NULL;
1658   }
1659 }
1660 
1661 /*******************************************************************************
1662  *
1663  * Function         bta_dm_is_search_request_queued
1664  *
1665  * Description      Checks if there is a queued search request
1666  *
1667  * Returns          bool
1668  *
1669  ******************************************************************************/
bta_dm_is_search_request_queued()1670 bool bta_dm_is_search_request_queued() {
1671   return bta_dm_search_cb.p_pending_search != NULL;
1672 }
1673 
1674 /*******************************************************************************
1675  *
1676  * Function         bta_dm_search_clear_queue
1677  *
1678  * Description      Clears the queue if API search cancel is called
1679  *
1680  * Returns          void
1681  *
1682  ******************************************************************************/
bta_dm_search_clear_queue()1683 void bta_dm_search_clear_queue() {
1684   osi_free_and_reset((void**)&bta_dm_search_cb.p_pending_search);
1685   if (bluetooth::common::InitFlags::
1686           IsBtmDmFlushDiscoveryQueueOnSearchCancel()) {
1687     fixed_queue_flush(bta_dm_search_cb.pending_discovery_queue, osi_free);
1688   }
1689 }
1690 
1691 /*******************************************************************************
1692  *
1693  * Function         bta_dm_search_cancel_notify
1694  *
1695  * Description      Notify application that search has been cancelled
1696  *
1697  * Returns          void
1698  *
1699  ******************************************************************************/
bta_dm_search_cancel_notify()1700 void bta_dm_search_cancel_notify() {
1701   if (bta_dm_search_cb.p_search_cback) {
1702     bta_dm_search_cb.p_search_cback(BTA_DM_SEARCH_CANCEL_CMPL_EVT, NULL);
1703   }
1704   switch (bta_dm_search_get_state()) {
1705     case BTA_DM_SEARCH_ACTIVE:
1706     case BTA_DM_SEARCH_CANCELLING:
1707       if (!bta_dm_search_cb.name_discover_done) {
1708         BTM_CancelRemoteDeviceName();
1709       }
1710       break;
1711     case BTA_DM_SEARCH_IDLE:
1712     case BTA_DM_DISCOVER_ACTIVE:
1713       // Nothing to do
1714       break;
1715   }
1716 }
1717 
1718 /*******************************************************************************
1719  *
1720  * Function         bta_dm_find_services
1721  *
1722  * Description      Starts discovery on a device
1723  *
1724  * Returns          void
1725  *
1726  ******************************************************************************/
bta_dm_find_services(const RawAddress & bd_addr)1727 static void bta_dm_find_services(const RawAddress& bd_addr) {
1728   while (bta_dm_search_cb.service_index < BTA_MAX_SERVICE_ID) {
1729     Uuid uuid = Uuid::kEmpty;
1730     if (bta_dm_search_cb.services_to_search &
1731         (tBTA_SERVICE_MASK)(
1732             BTA_SERVICE_ID_TO_SERVICE_MASK(bta_dm_search_cb.service_index))) {
1733       bta_dm_search_cb.p_sdp_db =
1734           (tSDP_DISCOVERY_DB*)osi_malloc(BTA_DM_SDP_DB_SIZE);
1735       APPL_TRACE_DEBUG("bta_dm_search_cb.services = %04x***********",
1736                        bta_dm_search_cb.services);
1737       /* try to search all services by search based on L2CAP UUID */
1738       if (bta_dm_search_cb.services == BTA_ALL_SERVICE_MASK) {
1739         LOG_INFO("%s services_to_search=%08x", __func__,
1740                  bta_dm_search_cb.services_to_search);
1741         if (bta_dm_search_cb.services_to_search & BTA_RES_SERVICE_MASK) {
1742           uuid = Uuid::From16Bit(bta_service_id_to_uuid_lkup_tbl[0]);
1743           bta_dm_search_cb.services_to_search &= ~BTA_RES_SERVICE_MASK;
1744         } else {
1745           uuid = Uuid::From16Bit(UUID_PROTOCOL_L2CAP);
1746           bta_dm_search_cb.services_to_search = 0;
1747         }
1748       } else {
1749         /* for LE only profile */
1750         if (bta_dm_search_cb.service_index == BTA_BLE_SERVICE_ID) {
1751           uuid = Uuid::From16Bit(
1752               bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index]);
1753 
1754           bta_dm_search_cb.services_to_search &= (tBTA_SERVICE_MASK)(~(
1755               BTA_SERVICE_ID_TO_SERVICE_MASK(bta_dm_search_cb.service_index)));
1756         } else {
1757           /* remove the service from services to be searched  */
1758           bta_dm_search_cb.services_to_search &= (tBTA_SERVICE_MASK)(~(
1759               BTA_SERVICE_ID_TO_SERVICE_MASK(bta_dm_search_cb.service_index)));
1760           uuid = Uuid::From16Bit(
1761               bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index]);
1762         }
1763       }
1764 
1765       LOG_INFO("%s search UUID = %s", __func__, uuid.ToString().c_str());
1766       SDP_InitDiscoveryDb(bta_dm_search_cb.p_sdp_db, BTA_DM_SDP_DB_SIZE, 1,
1767                           &uuid, 0, NULL);
1768 
1769       memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf));
1770       bta_dm_search_cb.p_sdp_db->raw_data = g_disc_raw_data_buf;
1771 
1772       bta_dm_search_cb.p_sdp_db->raw_size = MAX_DISC_RAW_DATA_BUF;
1773 
1774       if (!SDP_ServiceSearchAttributeRequest(bd_addr, bta_dm_search_cb.p_sdp_db,
1775                                              &bta_dm_sdp_callback)) {
1776         /*
1777          * If discovery is not successful with this device, then
1778          * proceed with the next one.
1779          */
1780         osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db);
1781         bta_dm_search_cb.service_index = BTA_MAX_SERVICE_ID;
1782 
1783       } else {
1784         if (uuid == Uuid::From16Bit(UUID_PROTOCOL_L2CAP)) {
1785           if (!is_sdp_pbap_pce_disabled(bd_addr)) {
1786             LOG_DEBUG("SDP search for PBAP Client ");
1787             BTA_SdpSearch(bd_addr, Uuid::From16Bit(UUID_SERVCLASS_PBAP_PCE));
1788           }
1789         }
1790         bta_dm_search_cb.service_index++;
1791         return;
1792       }
1793     }
1794 
1795     bta_dm_search_cb.service_index++;
1796   }
1797 
1798   /* no more services to be discovered */
1799   if (bta_dm_search_cb.service_index >= BTA_MAX_SERVICE_ID) {
1800     tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG));
1801     /* initialize the data structure */
1802     memset(&(p_msg->disc_result.result), 0, sizeof(tBTA_DM_DISC_RES));
1803     p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT;
1804     p_msg->disc_result.result.disc_res.services =
1805         bta_dm_search_cb.services_found;
1806     p_msg->disc_result.result.disc_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
1807     strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name,
1808             bta_dm_get_remname(), BD_NAME_LEN + 1);
1809 
1810     bta_sys_sendmsg(p_msg);
1811   }
1812 }
1813 
1814 /*******************************************************************************
1815  *
1816  * Function         bta_dm_discover_next_device
1817  *
1818  * Description      Starts discovery on the next device in Inquiry data base
1819  *
1820  * Returns          void
1821  *
1822  ******************************************************************************/
bta_dm_discover_next_device(void)1823 static void bta_dm_discover_next_device(void) {
1824   APPL_TRACE_DEBUG("bta_dm_discover_next_device");
1825 
1826   /* searching next device on inquiry result */
1827   bta_dm_search_cb.p_btm_inq_info =
1828       BTM_InqDbNext(bta_dm_search_cb.p_btm_inq_info);
1829   if (bta_dm_search_cb.p_btm_inq_info != NULL) {
1830     bta_dm_search_cb.name_discover_done = false;
1831     bta_dm_search_cb.peer_name[0] = 0;
1832     bta_dm_discover_device(
1833         bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr);
1834   } else {
1835     tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG));
1836 
1837     /* no devices, search complete */
1838     bta_dm_search_cb.services = 0;
1839 
1840     p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT;
1841     bta_sys_sendmsg(p_msg);
1842   }
1843 }
1844 
1845 /*******************************************************************************
1846  *
1847  * Function         bta_dm_discover_device
1848  *
1849  * Description      Starts name and service discovery on the device
1850  *
1851  * Returns          void
1852  *
1853  ******************************************************************************/
bta_dm_determine_discovery_transport(const RawAddress & remote_bd_addr)1854 static tBT_TRANSPORT bta_dm_determine_discovery_transport(
1855     const RawAddress& remote_bd_addr) {
1856   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1857   if (bta_dm_search_cb.transport == BT_TRANSPORT_AUTO) {
1858     tBT_DEVICE_TYPE dev_type;
1859     tBLE_ADDR_TYPE addr_type;
1860 
1861     BTM_ReadDevInfo(remote_bd_addr, &dev_type, &addr_type);
1862     if (dev_type == BT_DEVICE_TYPE_BLE || addr_type == BLE_ADDR_RANDOM) {
1863       transport = BT_TRANSPORT_LE;
1864     }
1865   } else {
1866     transport = bta_dm_search_cb.transport;
1867   }
1868   return transport;
1869 }
1870 
bta_dm_discover_device(const RawAddress & remote_bd_addr)1871 static void bta_dm_discover_device(const RawAddress& remote_bd_addr) {
1872   const tBT_TRANSPORT transport =
1873       bta_dm_determine_discovery_transport(remote_bd_addr);
1874 
1875   VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(remote_bd_addr);
1876 
1877   bta_dm_search_cb.peer_bdaddr = remote_bd_addr;
1878 
1879   APPL_TRACE_DEBUG(
1880       "%s name_discover_done = %d p_btm_inq_info 0x%x state = %d, transport=%d",
1881       __func__, bta_dm_search_cb.name_discover_done,
1882       bta_dm_search_cb.p_btm_inq_info, bta_dm_search_get_state(), transport);
1883 
1884   if (bta_dm_search_cb.p_btm_inq_info) {
1885     APPL_TRACE_DEBUG("%s appl_knows_rem_name %d", __func__,
1886                      bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name);
1887   }
1888   if (((bta_dm_search_cb.p_btm_inq_info) &&
1889        (bta_dm_search_cb.p_btm_inq_info->results.device_type ==
1890         BT_DEVICE_TYPE_BLE) &&
1891        (bta_dm_search_get_state() == BTA_DM_SEARCH_ACTIVE)) ||
1892       (transport == BT_TRANSPORT_LE &&
1893        interop_match_addr(INTEROP_DISABLE_NAME_REQUEST,
1894                           &bta_dm_search_cb.peer_bdaddr))) {
1895     /* Do not perform RNR for LE devices at inquiry complete*/
1896     bta_dm_search_cb.name_discover_done = true;
1897   }
1898   // If we already have the name we can skip getting the name
1899   if (BTM_IsRemoteNameKnown(remote_bd_addr, transport) &&
1900       bluetooth::common::init_flags::sdp_skip_rnr_if_known_is_enabled()) {
1901     LOG_DEBUG("Security record already known skipping read remote name peer:%s",
1902               ADDRESS_TO_LOGGABLE_CSTR(remote_bd_addr));
1903     bta_dm_search_cb.name_discover_done = true;
1904   }
1905 
1906   /* if name discovery is not done and application needs remote name */
1907   if ((!bta_dm_search_cb.name_discover_done) &&
1908       ((bta_dm_search_cb.p_btm_inq_info == NULL) ||
1909        (bta_dm_search_cb.p_btm_inq_info &&
1910         (!bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name)))) {
1911     if (bta_dm_read_remote_device_name(bta_dm_search_cb.peer_bdaddr,
1912                                        transport)) {
1913       if (bta_dm_search_get_state() != BTA_DM_DISCOVER_ACTIVE) {
1914         LOG_DEBUG("Reset transport state for next discovery");
1915         bta_dm_search_cb.transport = BT_TRANSPORT_AUTO;
1916       }
1917       BTM_LogHistory(kBtmLogTag, bta_dm_search_cb.peer_bdaddr,
1918                      "Read remote name",
1919                      base::StringPrintf("Transport:%s",
1920                                         bt_transport_text(transport).c_str()));
1921       return;
1922     } else {
1923       LOG_ERROR("Unable to start read remote device name");
1924     }
1925 
1926     /* starting name discovery failed */
1927     bta_dm_search_cb.name_discover_done = true;
1928   }
1929 
1930   /* Reset transport state for next discovery */
1931   bta_dm_search_cb.transport = BT_TRANSPORT_AUTO;
1932 
1933   /* if application wants to discover service */
1934   if (bta_dm_search_cb.services) {
1935     BTM_LogHistory(kBtmLogTag, remote_bd_addr, "Discovery started ",
1936                    base::StringPrintf("Transport:%s",
1937                                       bt_transport_text(transport).c_str()));
1938 
1939     /* initialize variables */
1940     bta_dm_search_cb.service_index = 0;
1941     bta_dm_search_cb.services_found = 0;
1942     bta_dm_search_cb.services_to_search = bta_dm_search_cb.services;
1943 
1944     /* if seaching with EIR is not completed */
1945     if (bta_dm_search_cb.services_to_search) {
1946       /* check whether connection already exists to the device
1947          if connection exists, we don't have to wait for ACL
1948          link to go down to start search on next device */
1949       if (transport == BT_TRANSPORT_BR_EDR) {
1950         if (BTM_IsAclConnectionUp(bta_dm_search_cb.peer_bdaddr,
1951                                   BT_TRANSPORT_BR_EDR))
1952           bta_dm_search_cb.wait_disc = false;
1953         else
1954           bta_dm_search_cb.wait_disc = true;
1955       }
1956       if (bta_dm_search_cb.p_btm_inq_info) {
1957         APPL_TRACE_DEBUG(
1958             "%s p_btm_inq_info 0x%x results.device_type 0x%x "
1959             "services_to_search 0x%x",
1960             __func__, bta_dm_search_cb.p_btm_inq_info,
1961             bta_dm_search_cb.p_btm_inq_info->results.device_type,
1962             bta_dm_search_cb.services_to_search);
1963       }
1964 
1965       if (transport == BT_TRANSPORT_LE) {
1966         if (bta_dm_search_cb.services_to_search & BTA_BLE_SERVICE_MASK) {
1967           LOG_INFO("bta_dm_discovery: starting GATT discovery on %s",
1968                    ADDRESS_TO_LOGGABLE_CSTR(bta_dm_search_cb.peer_bdaddr));
1969           // set the raw data buffer here
1970           memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf));
1971           /* start GATT for service discovery */
1972           btm_dm_start_gatt_discovery(bta_dm_search_cb.peer_bdaddr);
1973           return;
1974         }
1975       } else {
1976         LOG_INFO("bta_dm_discovery: starting SDP discovery on %s",
1977                  ADDRESS_TO_LOGGABLE_CSTR(bta_dm_search_cb.peer_bdaddr));
1978         bta_dm_search_cb.sdp_results = false;
1979         bta_dm_find_services(bta_dm_search_cb.peer_bdaddr);
1980         return;
1981       }
1982     }
1983   }
1984 
1985   /* name discovery and service discovery are done for this device */
1986   tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG));
1987   p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT;
1988   /* initialize the data structure */
1989   memset(&(p_msg->disc_result.result), 0, sizeof(tBTA_DM_DISC_RES));
1990   p_msg->disc_result.result.disc_res.result = BTA_SUCCESS;
1991   p_msg->disc_result.result.disc_res.services = bta_dm_search_cb.services_found;
1992   p_msg->disc_result.result.disc_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
1993   strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name,
1994           bta_dm_get_remname(), BD_NAME_LEN + 1);
1995 
1996   bta_sys_sendmsg(p_msg);
1997 }
1998 
1999 /*******************************************************************************
2000  *
2001  * Function         bta_dm_sdp_callback
2002  *
2003  * Description      Callback from sdp with discovery status
2004  *
2005  * Returns          void
2006  *
2007  ******************************************************************************/
bta_dm_sdp_callback(tSDP_STATUS sdp_status)2008 static void bta_dm_sdp_callback(tSDP_STATUS sdp_status) {
2009   tBTA_DM_SDP_RESULT* p_msg =
2010       (tBTA_DM_SDP_RESULT*)osi_malloc(sizeof(tBTA_DM_SDP_RESULT));
2011 
2012   p_msg->hdr.event = BTA_DM_SDP_RESULT_EVT;
2013   p_msg->sdp_result = sdp_status;
2014 
2015   bta_sys_sendmsg(p_msg);
2016 }
2017 
2018 /*******************************************************************************
2019  *
2020  * Function         bta_dm_inq_results_cb
2021  *
2022  * Description      Inquiry results callback from BTM
2023  *
2024  * Returns          void
2025  *
2026  ******************************************************************************/
bta_dm_inq_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)2027 static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir,
2028                                   uint16_t eir_len) {
2029   tBTA_DM_SEARCH result;
2030   tBTM_INQ_INFO* p_inq_info;
2031   uint16_t service_class;
2032 
2033   result.inq_res.bd_addr = p_inq->remote_bd_addr;
2034 
2035   // Pass the original address to GattService#onScanResult
2036   result.inq_res.original_bda = p_inq->original_bda;
2037 
2038   memcpy(result.inq_res.dev_class, p_inq->dev_class, DEV_CLASS_LEN);
2039   BTM_COD_SERVICE_CLASS(service_class, p_inq->dev_class);
2040   result.inq_res.is_limited =
2041       (service_class & BTM_COD_SERVICE_LMTD_DISCOVER) ? true : false;
2042   result.inq_res.rssi = p_inq->rssi;
2043 
2044   result.inq_res.ble_addr_type = p_inq->ble_addr_type;
2045   result.inq_res.inq_result_type = p_inq->inq_result_type;
2046   result.inq_res.device_type = p_inq->device_type;
2047   result.inq_res.flag = p_inq->flag;
2048   result.inq_res.include_rsi = p_inq->include_rsi;
2049 
2050   /* application will parse EIR to find out remote device name */
2051   result.inq_res.p_eir = const_cast<uint8_t*>(p_eir);
2052   result.inq_res.eir_len = eir_len;
2053 
2054   result.inq_res.ble_evt_type = p_inq->ble_evt_type;
2055 
2056   p_inq_info = BTM_InqDbRead(p_inq->remote_bd_addr);
2057   if (p_inq_info != NULL) {
2058     /* initialize remt_name_not_required to false so that we get the name by
2059      * default */
2060     result.inq_res.remt_name_not_required = false;
2061   }
2062 
2063   if (bta_dm_search_cb.p_search_cback)
2064     bta_dm_search_cb.p_search_cback(BTA_DM_INQ_RES_EVT, &result);
2065 
2066   if (p_inq_info) {
2067     /* application indicates if it knows the remote name, inside the callback
2068      copy that to the inquiry data base*/
2069     if (result.inq_res.remt_name_not_required)
2070       p_inq_info->appl_knows_rem_name = true;
2071   }
2072 }
2073 
2074 /*******************************************************************************
2075  *
2076  * Function         bta_dm_inq_cmpl_cb
2077  *
2078  * Description      Inquiry complete callback from BTM
2079  *
2080  * Returns          void
2081  *
2082  ******************************************************************************/
bta_dm_inq_cmpl_cb(void * p_result)2083 static void bta_dm_inq_cmpl_cb(void* p_result) {
2084   APPL_TRACE_DEBUG("%s", __func__);
2085 
2086   bta_dm_inq_cmpl(((tBTM_INQUIRY_CMPL*)p_result)->num_resp);
2087 }
2088 
2089 /*******************************************************************************
2090  *
2091  * Function         bta_dm_service_search_remname_cback
2092  *
2093  * Description      Remote name call back from BTM during service discovery
2094  *
2095  * Returns          void
2096  *
2097  ******************************************************************************/
bta_dm_service_search_remname_cback(const RawAddress & bd_addr,UNUSED_ATTR DEV_CLASS dc,tBTM_BD_NAME bd_name)2098 static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr,
2099                                                 UNUSED_ATTR DEV_CLASS dc,
2100                                                 tBTM_BD_NAME bd_name) {
2101   tBTM_REMOTE_DEV_NAME rem_name = {};
2102   tBTM_STATUS btm_status;
2103 
2104   APPL_TRACE_DEBUG("%s name=<%s>", __func__, bd_name);
2105 
2106 
2107   /* if this is what we are looking for */
2108   if (bta_dm_search_cb.peer_bdaddr == bd_addr) {
2109     rem_name.bd_addr = bd_addr;
2110     rem_name.length = strlcpy((char*)rem_name.remote_bd_name, (char*)bd_name,
2111                               BD_NAME_LEN + 1);
2112     if (rem_name.length > BD_NAME_LEN) {
2113       rem_name.length = BD_NAME_LEN;
2114     }
2115     rem_name.status = BTM_SUCCESS;
2116     rem_name.hci_status = HCI_SUCCESS;
2117     bta_dm_remname_cback(&rem_name);
2118   } else {
2119     /* get name of device */
2120     btm_status =
2121         BTM_ReadRemoteDeviceName(bta_dm_search_cb.peer_bdaddr,
2122                                  bta_dm_remname_cback, BT_TRANSPORT_BR_EDR);
2123     if (btm_status == BTM_BUSY) {
2124       /* wait for next chance(notification of remote name discovery done) */
2125       APPL_TRACE_DEBUG("%s: BTM_ReadRemoteDeviceName is busy", __func__);
2126     } else if (btm_status != BTM_CMD_STARTED) {
2127       /* if failed to start getting remote name then continue */
2128       APPL_TRACE_WARNING("%s: BTM_ReadRemoteDeviceName returns 0x%02X",
2129                          __func__, btm_status);
2130 
2131       // needed so our response is not ignored, since this corresponds to the
2132       // actual peer_bdaddr
2133       rem_name.bd_addr = bta_dm_search_cb.peer_bdaddr;
2134       rem_name.length = 0;
2135       rem_name.remote_bd_name[0] = 0;
2136       rem_name.status = btm_status;
2137       rem_name.hci_status = HCI_SUCCESS;
2138       bta_dm_remname_cback(&rem_name);
2139     }
2140   }
2141 }
2142 
2143 /*******************************************************************************
2144  *
2145  * Function         bta_dm_remname_cback
2146  *
2147  * Description      Remote name complete call back from BTM
2148  *
2149  * Returns          void
2150  *
2151  ******************************************************************************/
bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME * p)2152 static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p) {
2153   CHECK(p != nullptr);
2154 
2155   tBTM_REMOTE_DEV_NAME* p_remote_name = (tBTM_REMOTE_DEV_NAME*)p;
2156   LOG_INFO(
2157       "Remote name request complete peer:%s btm_status:%s hci_status:%s "
2158       "name[0]:%c length:%hu",
2159       ADDRESS_TO_LOGGABLE_CSTR(p_remote_name->bd_addr),
2160       btm_status_text(p_remote_name->status).c_str(),
2161       hci_error_code_text(p_remote_name->hci_status).c_str(),
2162       p_remote_name->remote_bd_name[0], p_remote_name->length);
2163 
2164   if (bta_dm_search_cb.peer_bdaddr == p_remote_name->bd_addr) {
2165     BTM_SecDeleteRmtNameNotifyCallback(&bta_dm_service_search_remname_cback);
2166   } else {
2167     // if we got a different response, maybe ignore it
2168     // we will have made a request directly from BTM_ReadRemoteDeviceName so we
2169     // expect a dedicated response for us
2170     if (p_remote_name->hci_status == HCI_ERR_CONNECTION_EXISTS) {
2171       BTM_SecDeleteRmtNameNotifyCallback(&bta_dm_service_search_remname_cback);
2172       LOG_INFO(
2173           "Assume command failed due to disconnection hci_status:%s peer:%s",
2174           hci_error_code_text(p_remote_name->hci_status).c_str(),
2175           ADDRESS_TO_LOGGABLE_CSTR(p_remote_name->bd_addr));
2176     } else {
2177       LOG_INFO(
2178           "Ignored remote name response for the wrong address exp:%s act:%s",
2179           ADDRESS_TO_LOGGABLE_CSTR(bta_dm_search_cb.peer_bdaddr),
2180           ADDRESS_TO_LOGGABLE_CSTR(p_remote_name->bd_addr));
2181       return;
2182     }
2183   }
2184 
2185   /* remote name discovery is done but it could be failed */
2186   bta_dm_search_cb.name_discover_done = true;
2187   strlcpy((char*)bta_dm_search_cb.peer_name,
2188           (char*)p_remote_name->remote_bd_name, BD_NAME_LEN + 1);
2189 
2190   if (bta_dm_search_cb.transport == BT_TRANSPORT_LE) {
2191     GAP_BleReadPeerPrefConnParams(bta_dm_search_cb.peer_bdaddr);
2192   }
2193 
2194   tBTA_DM_REM_NAME* p_msg =
2195       (tBTA_DM_REM_NAME*)osi_malloc(sizeof(tBTA_DM_REM_NAME));
2196   p_msg->result.disc_res.hci_status = p->hci_status;
2197   p_msg->result.disc_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
2198   strlcpy((char*)p_msg->result.disc_res.bd_name,
2199           (char*)p_remote_name->remote_bd_name, BD_NAME_LEN + 1);
2200   p_msg->hdr.event = BTA_DM_REMT_NAME_EVT;
2201 
2202   bta_sys_sendmsg(p_msg);
2203 }
2204 
2205 /*******************************************************************************
2206  *
2207  * Function         bta_dm_pinname_cback
2208  *
2209  * Description      Callback requesting pin_key
2210  *
2211  * Returns          void
2212  *
2213  ******************************************************************************/
bta_dm_pinname_cback(const tBTM_REMOTE_DEV_NAME * p_data)2214 static void bta_dm_pinname_cback(const tBTM_REMOTE_DEV_NAME* p_data) {
2215   tBTM_REMOTE_DEV_NAME* p_result = (tBTM_REMOTE_DEV_NAME*)p_data;
2216   tBTA_DM_SEC sec_event;
2217   uint32_t bytes_to_copy;
2218   tBTA_DM_SEC_EVT event = bta_dm_cb.pin_evt;
2219 
2220   if (BTA_DM_SP_CFM_REQ_EVT == event) {
2221     /* Retrieved saved device class and bd_addr */
2222     sec_event.cfm_req.bd_addr = bta_dm_cb.pin_bd_addr;
2223     BTA_COPY_DEVICE_CLASS(sec_event.cfm_req.dev_class, bta_dm_cb.pin_dev_class);
2224 
2225     if (p_result && p_result->status == BTM_SUCCESS) {
2226       bytes_to_copy =
2227           (p_result->length < BD_NAME_LEN) ? p_result->length : BD_NAME_LEN;
2228       memcpy(sec_event.cfm_req.bd_name, p_result->remote_bd_name,
2229              bytes_to_copy);
2230       sec_event.pin_req.bd_name[BD_NAME_LEN] = 0;
2231     } else /* No name found */
2232       sec_event.cfm_req.bd_name[0] = 0;
2233 
2234     sec_event.key_notif.passkey =
2235         bta_dm_cb.num_val; /* get PIN code numeric number */
2236 
2237     /* 1 additional event data fields for this event */
2238     sec_event.cfm_req.just_works = bta_dm_cb.just_works;
2239     /* retrieve the loc and rmt caps */
2240     sec_event.cfm_req.loc_io_caps = bta_dm_cb.loc_io_caps;
2241     sec_event.cfm_req.rmt_io_caps = bta_dm_cb.rmt_io_caps;
2242     sec_event.cfm_req.loc_auth_req = bta_dm_cb.loc_auth_req;
2243     sec_event.cfm_req.rmt_auth_req = bta_dm_cb.rmt_auth_req;
2244 
2245   } else {
2246     /* Retrieved saved device class and bd_addr */
2247     sec_event.pin_req.bd_addr = bta_dm_cb.pin_bd_addr;
2248     BTA_COPY_DEVICE_CLASS(sec_event.pin_req.dev_class, bta_dm_cb.pin_dev_class);
2249 
2250     if (p_result && p_result->status == BTM_SUCCESS) {
2251       bytes_to_copy = (p_result->length < BD_NAME_LEN) ? p_result->length
2252                                                        : (BD_NAME_LEN - 1);
2253       memcpy(sec_event.pin_req.bd_name, p_result->remote_bd_name,
2254              bytes_to_copy);
2255       sec_event.pin_req.bd_name[BD_NAME_LEN] = 0;
2256     } else /* No name found */
2257       sec_event.pin_req.bd_name[0] = 0;
2258 
2259     event = bta_dm_cb.pin_evt;
2260     sec_event.key_notif.passkey =
2261         bta_dm_cb.num_val; /* get PIN code numeric number */
2262   }
2263 
2264   if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(event, &sec_event);
2265 }
2266 
2267 /*******************************************************************************
2268  *
2269  * Function         bta_dm_pin_cback
2270  *
2271  * Description      Callback requesting pin_key
2272  *
2273  * Returns          void
2274  *
2275  ******************************************************************************/
bta_dm_pin_cback(const RawAddress & bd_addr,DEV_CLASS dev_class,const tBTM_BD_NAME bd_name,bool min_16_digit)2276 static uint8_t bta_dm_pin_cback(const RawAddress& bd_addr, DEV_CLASS dev_class,
2277                                 const tBTM_BD_NAME bd_name, bool min_16_digit) {
2278   if (!bta_dm_cb.p_sec_cback) return BTM_NOT_AUTHORIZED;
2279 
2280   /* If the device name is not known, save bdaddr and devclass and initiate a
2281    * name request */
2282   if (bd_name[0] == 0) {
2283     bta_dm_cb.pin_evt = BTA_DM_PIN_REQ_EVT;
2284     bta_dm_cb.pin_bd_addr = bd_addr;
2285     BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class, dev_class);
2286     if ((BTM_ReadRemoteDeviceName(bd_addr, bta_dm_pinname_cback,
2287                                   BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED)
2288       return BTM_CMD_STARTED;
2289 
2290     APPL_TRACE_WARNING(
2291         " bta_dm_pin_cback() -> Failed to start Remote Name Request  ");
2292   }
2293 
2294   tBTA_DM_SEC sec_event = {.pin_req = {
2295                                .bd_addr = bd_addr,
2296                            }};
2297   BTA_COPY_DEVICE_CLASS(sec_event.pin_req.dev_class, dev_class);
2298   strlcpy((char*)sec_event.pin_req.bd_name, (char*)bd_name, BD_NAME_LEN + 1);
2299   sec_event.pin_req.min_16_digit = min_16_digit;
2300 
2301   bta_dm_cb.p_sec_cback(BTA_DM_PIN_REQ_EVT, &sec_event);
2302   return BTM_CMD_STARTED;
2303 }
2304 
2305 /*******************************************************************************
2306  *
2307  * Function         bta_dm_new_link_key_cback
2308  *
2309  * Description      Callback from BTM to notify new link key
2310  *
2311  * Returns          void
2312  *
2313  ******************************************************************************/
bta_dm_new_link_key_cback(const RawAddress & bd_addr,UNUSED_ATTR DEV_CLASS dev_class,tBTM_BD_NAME bd_name,const LinkKey & key,uint8_t key_type,bool is_ctkd)2314 static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr,
2315                                          UNUSED_ATTR DEV_CLASS dev_class,
2316                                          tBTM_BD_NAME bd_name,
2317                                          const LinkKey& key, uint8_t key_type,
2318                                          bool is_ctkd) {
2319   tBTA_DM_SEC sec_event;
2320   tBTA_DM_AUTH_CMPL* p_auth_cmpl;
2321   tBTA_DM_SEC_EVT event = BTA_DM_AUTH_CMPL_EVT;
2322 
2323   memset(&sec_event, 0, sizeof(tBTA_DM_SEC));
2324 
2325   p_auth_cmpl = &sec_event.auth_cmpl;
2326 
2327   p_auth_cmpl->bd_addr = bd_addr;
2328 
2329   memcpy(p_auth_cmpl->bd_name, bd_name, BD_NAME_LEN);
2330   p_auth_cmpl->bd_name[BD_NAME_LEN] = 0;
2331   p_auth_cmpl->key_present = true;
2332   p_auth_cmpl->key_type = key_type;
2333   p_auth_cmpl->success = true;
2334   p_auth_cmpl->key = key;
2335   p_auth_cmpl->is_ctkd = is_ctkd;
2336 
2337   sec_event.auth_cmpl.fail_reason = HCI_SUCCESS;
2338 
2339   // Report the BR link key based on the BR/EDR address and type
2340   BTM_ReadDevInfo(bd_addr, &sec_event.auth_cmpl.dev_type,
2341                   &sec_event.auth_cmpl.addr_type);
2342   if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(event, &sec_event);
2343 
2344   // Setting remove_dev_pending flag to false, where it will avoid deleting
2345   // the
2346   // security device record when the ACL connection link goes down in case of
2347   // reconnection.
2348   if (bta_dm_cb.device_list.count)
2349     bta_dm_reset_sec_dev_pending(p_auth_cmpl->bd_addr);
2350 
2351   return BTM_CMD_STARTED;
2352 }
2353 
2354 /*******************************************************************************
2355  *
2356  * Function         bta_dm_authentication_complete_cback
2357  *
2358  * Description      Authentication complete callback from BTM
2359  *
2360  * Returns          void
2361  *
2362  ******************************************************************************/
bta_dm_authentication_complete_cback(const RawAddress & bd_addr,UNUSED_ATTR DEV_CLASS dev_class,tBTM_BD_NAME bd_name,tHCI_REASON reason)2363 static void bta_dm_authentication_complete_cback(
2364     const RawAddress& bd_addr, UNUSED_ATTR DEV_CLASS dev_class,
2365     tBTM_BD_NAME bd_name, tHCI_REASON reason) {
2366   if (reason != HCI_SUCCESS) {
2367     if (bta_dm_cb.p_sec_cback) {
2368       // Build out the security event data structure
2369       tBTA_DM_SEC sec_event = {
2370           .auth_cmpl =
2371               {
2372                   .bd_addr = bd_addr,
2373               },
2374       };
2375       memcpy(sec_event.auth_cmpl.bd_name, bd_name, BD_NAME_LEN);
2376       sec_event.auth_cmpl.bd_name[BD_NAME_LEN] = 0;
2377 
2378       // Report the BR link key based on the BR/EDR address and type
2379       BTM_ReadDevInfo(bd_addr, &sec_event.auth_cmpl.dev_type,
2380                       &sec_event.auth_cmpl.addr_type);
2381       sec_event.auth_cmpl.fail_reason = reason;
2382 
2383       bta_dm_cb.p_sec_cback(BTA_DM_AUTH_CMPL_EVT, &sec_event);
2384     }
2385 
2386     switch (reason) {
2387       case HCI_ERR_AUTH_FAILURE:
2388       case HCI_ERR_KEY_MISSING:
2389       case HCI_ERR_HOST_REJECT_SECURITY:
2390       case HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE:
2391         LOG_WARN(
2392             "Deleting device record as authentication failed entry:%s "
2393             "reason:%s",
2394             ADDRESS_TO_LOGGABLE_CSTR(bd_addr), hci_reason_code_text(reason).c_str());
2395         break;
2396 
2397       default:
2398         break;
2399     }
2400   }
2401 }
2402 
2403 /*******************************************************************************
2404  *
2405  * Function         bta_dm_sp_cback
2406  *
2407  * Description      simple pairing callback from BTM
2408  *
2409  * Returns          void
2410  *
2411  ******************************************************************************/
bta_dm_sp_cback(tBTM_SP_EVT event,tBTM_SP_EVT_DATA * p_data)2412 static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event,
2413                                    tBTM_SP_EVT_DATA* p_data) {
2414   tBTM_STATUS status = BTM_CMD_STARTED;
2415   tBTA_DM_SEC sec_event;
2416   tBTA_DM_SEC_EVT pin_evt = BTA_DM_SP_KEY_NOTIF_EVT;
2417 
2418   APPL_TRACE_EVENT("bta_dm_sp_cback: %d", event);
2419   if (!bta_dm_cb.p_sec_cback) return BTM_NOT_AUTHORIZED;
2420 
2421   bool sp_rmt_result = false;
2422   /* TODO_SP */
2423   switch (event) {
2424     case BTM_SP_IO_REQ_EVT:
2425       if (btm_local_io_caps != BTM_IO_CAP_NONE) {
2426         /* translate auth_req */
2427         btif_dm_set_oob_for_io_req(&p_data->io_req.oob_data);
2428         btif_dm_proc_io_req(&p_data->io_req.auth_req, p_data->io_req.is_orig);
2429       }
2430       APPL_TRACE_EVENT("io mitm: %d oob_data:%d", p_data->io_req.auth_req,
2431                        p_data->io_req.oob_data);
2432       break;
2433     case BTM_SP_IO_RSP_EVT:
2434       if (btm_local_io_caps != BTM_IO_CAP_NONE) {
2435         btif_dm_proc_io_rsp(p_data->io_rsp.bd_addr, p_data->io_rsp.io_cap,
2436                             p_data->io_rsp.oob_data, p_data->io_rsp.auth_req);
2437       }
2438       break;
2439 
2440     case BTM_SP_CFM_REQ_EVT:
2441       pin_evt = BTA_DM_SP_CFM_REQ_EVT;
2442       bta_dm_cb.just_works = sec_event.cfm_req.just_works =
2443           p_data->cfm_req.just_works;
2444       sec_event.cfm_req.loc_auth_req = p_data->cfm_req.loc_auth_req;
2445       sec_event.cfm_req.rmt_auth_req = p_data->cfm_req.rmt_auth_req;
2446       sec_event.cfm_req.loc_io_caps = p_data->cfm_req.loc_io_caps;
2447       sec_event.cfm_req.rmt_io_caps = p_data->cfm_req.rmt_io_caps;
2448 
2449       [[fallthrough]];
2450     /* Passkey entry mode, mobile device with output capability is very
2451         unlikely to receive key request, so skip this event */
2452     /*case BTM_SP_KEY_REQ_EVT: */
2453     case BTM_SP_KEY_NOTIF_EVT:
2454       if (btm_local_io_caps == BTM_IO_CAP_NONE &&
2455           BTM_SP_KEY_NOTIF_EVT == event) {
2456         status = BTM_NOT_AUTHORIZED;
2457         break;
2458       }
2459 
2460       bta_dm_cb.num_val = sec_event.key_notif.passkey =
2461           p_data->key_notif.passkey;
2462 
2463       if (BTM_SP_CFM_REQ_EVT == event) {
2464         /* Due to the switch case falling through below to BTM_SP_KEY_NOTIF_EVT,
2465            call remote name request using values from cfm_req */
2466         if (p_data->cfm_req.bd_name[0] == 0) {
2467           bta_dm_cb.pin_evt = pin_evt;
2468           bta_dm_cb.pin_bd_addr = p_data->cfm_req.bd_addr;
2469           bta_dm_cb.rmt_io_caps = sec_event.cfm_req.rmt_io_caps;
2470           bta_dm_cb.loc_io_caps = sec_event.cfm_req.loc_io_caps;
2471           bta_dm_cb.rmt_auth_req = sec_event.cfm_req.rmt_auth_req;
2472           bta_dm_cb.loc_auth_req = sec_event.cfm_req.loc_auth_req;
2473 
2474           BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class,
2475                                 p_data->cfm_req.dev_class);
2476           if ((BTM_ReadRemoteDeviceName(
2477                   p_data->cfm_req.bd_addr, bta_dm_pinname_cback,
2478                   BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED)
2479             return BTM_CMD_STARTED;
2480           APPL_TRACE_WARNING(
2481               " bta_dm_sp_cback() -> Failed to start Remote Name Request  ");
2482         } else {
2483           /* Due to the switch case falling through below to
2484              BTM_SP_KEY_NOTIF_EVT,
2485              copy these values into key_notif from cfm_req */
2486           sec_event.key_notif.bd_addr = p_data->cfm_req.bd_addr;
2487           BTA_COPY_DEVICE_CLASS(sec_event.key_notif.dev_class,
2488                                 p_data->cfm_req.dev_class);
2489           strlcpy((char*)sec_event.key_notif.bd_name,
2490                   (char*)p_data->cfm_req.bd_name, BD_NAME_LEN + 1);
2491         }
2492       }
2493 
2494       if (BTM_SP_KEY_NOTIF_EVT == event) {
2495         /* If the device name is not known, save bdaddr and devclass
2496            and initiate a name request with values from key_notif */
2497         if (p_data->key_notif.bd_name[0] == 0) {
2498           bta_dm_cb.pin_evt = pin_evt;
2499           bta_dm_cb.pin_bd_addr = p_data->key_notif.bd_addr;
2500           BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class,
2501                                 p_data->key_notif.dev_class);
2502           if ((BTM_ReadRemoteDeviceName(
2503                   p_data->key_notif.bd_addr, bta_dm_pinname_cback,
2504                   BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED)
2505             return BTM_CMD_STARTED;
2506           APPL_TRACE_WARNING(
2507               " bta_dm_sp_cback() -> Failed to start Remote Name Request  ");
2508         } else {
2509           sec_event.key_notif.bd_addr = p_data->key_notif.bd_addr;
2510           BTA_COPY_DEVICE_CLASS(sec_event.key_notif.dev_class,
2511                                 p_data->key_notif.dev_class);
2512           strlcpy((char*)sec_event.key_notif.bd_name,
2513                   (char*)p_data->key_notif.bd_name, BD_NAME_LEN + 1);
2514           sec_event.key_notif.bd_name[BD_NAME_LEN] = 0;
2515         }
2516       }
2517 
2518       bta_dm_cb.p_sec_cback(pin_evt, &sec_event);
2519 
2520       break;
2521 
2522     case BTM_SP_LOC_OOB_EVT:
2523 #ifdef BTIF_DM_OOB_TEST
2524       btif_dm_proc_loc_oob(BT_TRANSPORT_BR_EDR,
2525                            (bool)(p_data->loc_oob.status == BTM_SUCCESS),
2526                            p_data->loc_oob.c, p_data->loc_oob.r);
2527 #endif
2528       break;
2529 
2530     case BTM_SP_RMT_OOB_EVT: {
2531       Octet16 c;
2532       Octet16 r;
2533       sp_rmt_result = false;
2534 #ifdef BTIF_DM_OOB_TEST
2535       sp_rmt_result = btif_dm_proc_rmt_oob(p_data->rmt_oob.bd_addr, &c, &r);
2536 #endif
2537       BTIF_TRACE_DEBUG("bta_dm_ci_rmt_oob: result=%d", sp_rmt_result);
2538       bta_dm_ci_rmt_oob(sp_rmt_result, p_data->rmt_oob.bd_addr, c, r);
2539       break;
2540     }
2541 
2542     default:
2543       status = BTM_NOT_AUTHORIZED;
2544       break;
2545   }
2546   APPL_TRACE_EVENT("dm status: %d", status);
2547   return status;
2548 }
2549 
2550 /*******************************************************************************
2551  *
2552  * Function         bta_dm_local_name_cback
2553  *
2554  * Description      Callback from btm after local name is read
2555  *
2556  *
2557  * Returns          void
2558  *
2559  ******************************************************************************/
bta_dm_local_name_cback(UNUSED_ATTR void * p_name)2560 static void bta_dm_local_name_cback(UNUSED_ATTR void* p_name) {
2561   BTIF_dm_enable();
2562 }
2563 
handle_role_change(const RawAddress & bd_addr,tHCI_ROLE new_role,tHCI_STATUS hci_status)2564 static void handle_role_change(const RawAddress& bd_addr, tHCI_ROLE new_role,
2565                                tHCI_STATUS hci_status) {
2566   tBTA_DM_PEER_DEVICE* p_dev = bta_dm_find_peer_device(bd_addr);
2567   if (!p_dev) {
2568     LOG_WARN(
2569         "Unable to find device for role change peer:%s new_role:%s "
2570         "hci_status:%s",
2571         ADDRESS_TO_LOGGABLE_CSTR(bd_addr), RoleText(new_role).c_str(),
2572         hci_error_code_text(hci_status).c_str());
2573     return;
2574   }
2575 
2576   LOG_INFO(
2577       "Role change callback peer:%s info:0x%x new_role:%s dev count:%d "
2578       "hci_status:%s",
2579       ADDRESS_TO_LOGGABLE_CSTR(bd_addr), p_dev->Info(), RoleText(new_role).c_str(),
2580       bta_dm_cb.device_list.count, hci_error_code_text(hci_status).c_str());
2581 
2582   if (p_dev->Info() & BTA_DM_DI_AV_ACTIVE) {
2583     bool need_policy_change = false;
2584 
2585     /* there's AV activity on this link */
2586     if (new_role == HCI_ROLE_PERIPHERAL && bta_dm_cb.device_list.count > 1 &&
2587         hci_status == HCI_SUCCESS) {
2588       /* more than one connections and the AV connection is role switched
2589        * to peripheral
2590        * switch it back to central and remove the switch policy */
2591       BTM_SwitchRoleToCentral(bd_addr);
2592       need_policy_change = true;
2593     } else if (p_bta_dm_cfg->avoid_scatter && (new_role == HCI_ROLE_CENTRAL)) {
2594       /* if the link updated to be central include AV activities, remove
2595        * the switch policy */
2596       need_policy_change = true;
2597     }
2598 
2599     if (need_policy_change) {
2600       BTM_block_role_switch_for(p_dev->peer_bdaddr);
2601     }
2602   } else {
2603     /* there's AV no activity on this link and role switch happened
2604      * check if AV is active
2605      * if so, make sure the AV link is central */
2606     bta_dm_check_av();
2607   }
2608   bta_sys_notify_role_chg(bd_addr, new_role, hci_status);
2609 }
2610 
BTA_dm_report_role_change(const RawAddress bd_addr,tHCI_ROLE new_role,tHCI_STATUS hci_status)2611 void BTA_dm_report_role_change(const RawAddress bd_addr, tHCI_ROLE new_role,
2612                                tHCI_STATUS hci_status) {
2613   do_in_main_thread(
2614       FROM_HERE, base::Bind(handle_role_change, bd_addr, new_role, hci_status));
2615 }
2616 
handle_remote_features_complete(const RawAddress & bd_addr)2617 void handle_remote_features_complete(const RawAddress& bd_addr) {
2618   tBTA_DM_PEER_DEVICE* p_dev = bta_dm_find_peer_device(bd_addr);
2619   if (!p_dev) {
2620     LOG_WARN("Unable to find device peer:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
2621     return;
2622   }
2623 
2624   if (controller_get_interface()->supports_sniff_subrating() &&
2625       acl_peer_supports_sniff_subrating(bd_addr)) {
2626     LOG_DEBUG("Device supports sniff subrating peer:%s",
2627               ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
2628     p_dev->info = BTA_DM_DI_USE_SSR;
2629   } else {
2630     LOG_DEBUG("Device does NOT support sniff subrating peer:%s",
2631               ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
2632   }
2633 }
2634 
BTA_dm_notify_remote_features_complete(const RawAddress bd_addr)2635 void BTA_dm_notify_remote_features_complete(const RawAddress bd_addr) {
2636   do_in_main_thread(FROM_HERE,
2637                     base::Bind(handle_remote_features_complete, bd_addr));
2638 }
2639 
allocate_device_for(const RawAddress & bd_addr,tBT_TRANSPORT transport)2640 static tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr,
2641                                                 tBT_TRANSPORT transport) {
2642   for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) {
2643     auto device = &bta_dm_cb.device_list.peer_device[i];
2644     if (device->peer_bdaddr == bd_addr && device->transport == transport) {
2645       return device;
2646     }
2647   }
2648 
2649   if (bta_dm_cb.device_list.count < BTA_DM_NUM_PEER_DEVICE) {
2650     auto device =
2651         &bta_dm_cb.device_list.peer_device[bta_dm_cb.device_list.count];
2652     device->peer_bdaddr = bd_addr;
2653     bta_dm_cb.device_list.count++;
2654     if (transport == BT_TRANSPORT_LE) {
2655       bta_dm_cb.device_list.le_count++;
2656     }
2657     return device;
2658   }
2659   return nullptr;
2660 }
2661 
bta_dm_acl_up(const RawAddress & bd_addr,tBT_TRANSPORT transport,uint16_t acl_handle)2662 void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport,
2663                    uint16_t acl_handle) {
2664   auto device = allocate_device_for(bd_addr, transport);
2665   if (device == nullptr) {
2666     LOG_WARN("Unable to allocate device resources for new connection");
2667     return;
2668   }
2669   device->conn_state = BTA_DM_CONNECTED;
2670   device->pref_role = BTA_ANY_ROLE;
2671   device->info = BTA_DM_DI_NONE;
2672   device->transport = transport;
2673 
2674   if (controller_get_interface()->supports_sniff_subrating() &&
2675       acl_peer_supports_sniff_subrating(bd_addr)) {
2676     // NOTE: This callback assumes upon ACL connection that
2677     // the read remote features has completed and is valid.
2678     // The only guaranteed contract for valid read remote features
2679     // data is when the BTA_dm_notify_remote_features_complete()
2680     // callback has completed.  The below assignment is kept for
2681     // transitional informational purposes only.
2682     device->info = BTA_DM_DI_USE_SSR;
2683   }
2684 
2685   if (bta_dm_cb.p_sec_cback) {
2686     tBTA_DM_SEC conn;
2687     memset(&conn, 0, sizeof(tBTA_DM_SEC));
2688     conn.link_up.bd_addr = bd_addr;
2689     conn.link_up.transport_link_type = transport;
2690     conn.link_up.acl_handle = acl_handle;
2691 
2692     bta_dm_cb.p_sec_cback(BTA_DM_LINK_UP_EVT, &conn);
2693     LOG_DEBUG("Executed security callback for new connection available");
2694   }
2695   bta_dm_adjust_roles(true);
2696 }
2697 
BTA_dm_acl_up(const RawAddress bd_addr,tBT_TRANSPORT transport,uint16_t acl_handle)2698 void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport,
2699                    uint16_t acl_handle) {
2700   do_in_main_thread(FROM_HERE,
2701                     base::Bind(bta_dm_acl_up, bd_addr, transport, acl_handle));
2702 }
2703 
bta_dm_acl_up_failed(const RawAddress bd_addr,tBT_TRANSPORT transport,tHCI_STATUS status)2704 static void bta_dm_acl_up_failed(const RawAddress bd_addr,
2705                                  tBT_TRANSPORT transport, tHCI_STATUS status) {
2706   if (bta_dm_cb.p_sec_cback) {
2707     tBTA_DM_SEC conn = {};
2708     conn.link_up_failed.bd_addr = bd_addr;
2709     conn.link_up_failed.transport_link_type = transport;
2710     conn.link_up_failed.status = status;
2711     bta_dm_cb.p_sec_cback(BTA_DM_LINK_UP_FAILED_EVT, &conn);
2712   }
2713 }
2714 
BTA_dm_acl_up_failed(const RawAddress bd_addr,tBT_TRANSPORT transport,tHCI_STATUS status)2715 void BTA_dm_acl_up_failed(const RawAddress bd_addr, tBT_TRANSPORT transport,
2716                           tHCI_STATUS status) {
2717   do_in_main_thread(
2718       FROM_HERE, base::Bind(bta_dm_acl_up_failed, bd_addr, transport, status));
2719 }
2720 
bta_dm_acl_down(const RawAddress & bd_addr,tBT_TRANSPORT transport)2721 static void bta_dm_acl_down(const RawAddress& bd_addr,
2722                             tBT_TRANSPORT transport) {
2723   bool issue_unpair_cb = false;
2724   bool remove_device = false;
2725 
2726   for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) {
2727     auto device = &bta_dm_cb.device_list.peer_device[i];
2728     if (device->peer_bdaddr != bd_addr || device->transport != transport)
2729       continue;
2730 
2731     if (device->conn_state == BTA_DM_UNPAIRING) {
2732       issue_unpair_cb = BTM_SecDeleteDevice(device->peer_bdaddr);
2733 
2734       /* remove all cached GATT information */
2735       BTA_GATTC_Refresh(bd_addr);
2736 
2737       APPL_TRACE_DEBUG("%s: Unpairing: issue unpair CB = %d ", __func__,
2738                        issue_unpair_cb);
2739     }
2740 
2741     remove_device = device->remove_dev_pending;
2742 
2743     // Iterate to the one before the last when shrinking the list,
2744     // otherwise we memcpy garbage data into the record.
2745     // Then clear out the last item in the list since we are shrinking.
2746     for (; i < bta_dm_cb.device_list.count - 1; i++) {
2747       memcpy(&bta_dm_cb.device_list.peer_device[i],
2748              &bta_dm_cb.device_list.peer_device[i + 1],
2749              sizeof(bta_dm_cb.device_list.peer_device[i]));
2750     }
2751     if (bta_dm_cb.device_list.count > 0) {
2752       int clear_index = bta_dm_cb.device_list.count - 1;
2753       memset(&bta_dm_cb.device_list.peer_device[clear_index], 0,
2754              sizeof(bta_dm_cb.device_list.peer_device[clear_index]));
2755     }
2756     break;
2757   }
2758   if (bta_dm_cb.device_list.count) bta_dm_cb.device_list.count--;
2759   if ((transport == BT_TRANSPORT_LE) && (bta_dm_cb.device_list.le_count)) {
2760     bta_dm_cb.device_list.le_count--;
2761   }
2762 
2763   if ((transport == BT_TRANSPORT_BR_EDR) &&
2764       (bta_dm_search_cb.wait_disc && bta_dm_search_cb.peer_bdaddr == bd_addr)) {
2765     bta_dm_search_cb.wait_disc = false;
2766 
2767     if (bta_dm_search_cb.sdp_results) {
2768       APPL_TRACE_EVENT(" timer stopped  ");
2769       alarm_cancel(bta_dm_search_cb.search_timer);
2770       bta_dm_discover_next_device();
2771     }
2772   }
2773 
2774   if (bta_dm_cb.disabling) {
2775     if (!BTM_GetNumAclLinks()) {
2776       /*
2777        * Start a timer to make sure that the profiles
2778        * get the disconnect event.
2779        */
2780       alarm_set_on_mloop(bta_dm_cb.disable_timer,
2781                          BTA_DM_DISABLE_CONN_DOWN_TIMER_MS,
2782                          bta_dm_disable_conn_down_timer_cback, NULL);
2783     }
2784   }
2785   if (remove_device) {
2786     bta_dm_process_remove_device_no_callback(bd_addr);
2787   }
2788 
2789   if (bta_dm_cb.p_sec_cback) {
2790     tBTA_DM_SEC conn;
2791     memset(&conn, 0, sizeof(tBTA_DM_SEC));
2792     conn.link_down.bd_addr = bd_addr;
2793     conn.link_down.transport_link_type = transport;
2794 
2795     bta_dm_cb.p_sec_cback(BTA_DM_LINK_DOWN_EVT, &conn);
2796     if (issue_unpair_cb) bta_dm_cb.p_sec_cback(BTA_DM_DEV_UNPAIRED_EVT, &conn);
2797   }
2798 
2799   bta_dm_adjust_roles(true);
2800 }
2801 
BTA_dm_acl_down(const RawAddress bd_addr,tBT_TRANSPORT transport)2802 void BTA_dm_acl_down(const RawAddress bd_addr, tBT_TRANSPORT transport) {
2803   do_in_main_thread(FROM_HERE, base::Bind(bta_dm_acl_down, bd_addr, transport));
2804 }
2805 
2806 /*******************************************************************************
2807  *
2808  * Function         bta_dm_check_av
2809  *
2810  * Description      This function checks if AV is active
2811  *                  if yes, make sure the AV link is central
2812  *
2813  ******************************************************************************/
bta_dm_check_av()2814 static void bta_dm_check_av() {
2815   uint8_t i;
2816   tBTA_DM_PEER_DEVICE* p_dev;
2817 
2818   if (bta_dm_cb.cur_av_count) {
2819     LOG_INFO("av_count:%d", bta_dm_cb.cur_av_count);
2820     for (i = 0; i < bta_dm_cb.device_list.count; i++) {
2821       p_dev = &bta_dm_cb.device_list.peer_device[i];
2822       APPL_TRACE_WARNING("[%d]: state:%d, info:x%x", i, p_dev->conn_state,
2823                          p_dev->Info());
2824       if ((p_dev->conn_state == BTA_DM_CONNECTED) &&
2825           (p_dev->Info() & BTA_DM_DI_AV_ACTIVE)) {
2826         /* make central and take away the role switch policy */
2827         BTM_SwitchRoleToCentral(p_dev->peer_bdaddr);
2828         /* else either already central or can not switch for some reasons */
2829         BTM_block_role_switch_for(p_dev->peer_bdaddr);
2830         break;
2831       }
2832     }
2833   }
2834 }
2835 
2836 /*******************************************************************************
2837  *
2838  * Function         bta_dm_disable_conn_down_timer_cback
2839  *
2840  * Description      Sends disable event to application
2841  *
2842  *
2843  * Returns          void
2844  *
2845  ******************************************************************************/
bta_dm_disable_conn_down_timer_cback(UNUSED_ATTR void * data)2846 static void bta_dm_disable_conn_down_timer_cback(UNUSED_ATTR void* data) {
2847   /* disable the power managment module */
2848   bta_dm_disable_pm();
2849 
2850   bta_dm_cb.disabling = false;
2851   LOG_INFO("Stack device manager shutdown completed");
2852   future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
2853 }
2854 
2855 /*******************************************************************************
2856  *
2857  * Function         bta_dm_rm_cback
2858  *
2859  * Description      Role management callback from sys
2860  *
2861  *
2862  * Returns          void
2863  *
2864  ******************************************************************************/
bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status,uint8_t id,uint8_t app_id,const RawAddress & peer_addr)2865 void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id,
2866                      const RawAddress& peer_addr) {
2867   uint8_t j;
2868   tBTA_PREF_ROLES role;
2869   tBTA_DM_PEER_DEVICE* p_dev;
2870 
2871   LOG_DEBUG("BTA Role management callback count:%d status:%s peer:%s",
2872             bta_dm_cb.cur_av_count, bta_sys_conn_status_text(status).c_str(),
2873             ADDRESS_TO_LOGGABLE_CSTR(peer_addr));
2874 
2875   p_dev = bta_dm_find_peer_device(peer_addr);
2876   if (status == BTA_SYS_CONN_OPEN) {
2877     if (p_dev) {
2878       /* Do not set to connected if we are in the middle of unpairing. When AV
2879        * stream is
2880        * started it fakes out a SYS_CONN_OPEN to potentially trigger a role
2881        * switch command.
2882        * But this should not be done if we are in the middle of unpairing.
2883        */
2884       if (p_dev->conn_state != BTA_DM_UNPAIRING)
2885         p_dev->conn_state = BTA_DM_CONNECTED;
2886 
2887       for (j = 1; j <= p_bta_dm_rm_cfg[0].app_id; j++) {
2888         if (((p_bta_dm_rm_cfg[j].app_id == app_id) ||
2889              (p_bta_dm_rm_cfg[j].app_id == BTA_ALL_APP_ID)) &&
2890             (p_bta_dm_rm_cfg[j].id == id)) {
2891           ASSERT_LOG(p_bta_dm_rm_cfg[j].cfg <= BTA_PERIPHERAL_ROLE_ONLY,
2892                      "Passing illegal preferred role:0x%02x [0x%02x<=>0x%02x]",
2893                      p_bta_dm_rm_cfg[j].cfg, BTA_ANY_ROLE,
2894                      BTA_PERIPHERAL_ROLE_ONLY);
2895           role = static_cast<tBTA_PREF_ROLES>(p_bta_dm_rm_cfg[j].cfg);
2896           if (role > p_dev->pref_role) p_dev->pref_role = role;
2897           break;
2898         }
2899       }
2900     }
2901   }
2902 
2903   if (BTA_ID_AV == id) {
2904     if (status == BTA_SYS_CONN_BUSY) {
2905       if (p_dev) p_dev->info |= BTA_DM_DI_AV_ACTIVE;
2906       /* AV calls bta_sys_conn_open with the A2DP stream count as app_id */
2907       if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count();
2908     } else if (status == BTA_SYS_CONN_IDLE) {
2909       if (p_dev) p_dev->info &= ~BTA_DM_DI_AV_ACTIVE;
2910 
2911       /* get cur_av_count from connected services */
2912       if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count();
2913     }
2914   }
2915 
2916   /* Don't adjust roles for each busy/idle state transition to avoid
2917      excessive switch requests when individual profile busy/idle status
2918      changes */
2919   if ((status != BTA_SYS_CONN_BUSY) && (status != BTA_SYS_CONN_IDLE))
2920     bta_dm_adjust_roles(false);
2921 }
2922 
2923 /*******************************************************************************
2924  *
2925  * Function         bta_dm_delay_role_switch_cback
2926  *
2927  * Description      Callback from btm to delay a role switch
2928  *
2929  * Returns          void
2930  *
2931  ******************************************************************************/
bta_dm_delay_role_switch_cback(UNUSED_ATTR void * data)2932 static void bta_dm_delay_role_switch_cback(UNUSED_ATTR void* data) {
2933   APPL_TRACE_EVENT("%s: initiating Delayed RS", __func__);
2934   bta_dm_adjust_roles(false);
2935 }
2936 
2937 /*******************************************************************************
2938  *
2939  * Function         bta_dm_reset_sec_dev_pending
2940  *
2941  * Description      Setting the remove device pending status to false from
2942  *                  security device DB, when the link key notification
2943  *                  event comes.
2944  *
2945  * Returns          void
2946  *
2947  ******************************************************************************/
bta_dm_reset_sec_dev_pending(const RawAddress & remote_bd_addr)2948 static void bta_dm_reset_sec_dev_pending(const RawAddress& remote_bd_addr) {
2949   for (size_t i = 0; i < bta_dm_cb.device_list.count; i++) {
2950     if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr == remote_bd_addr) {
2951       bta_dm_cb.device_list.peer_device[i].remove_dev_pending = false;
2952       return;
2953     }
2954   }
2955 }
2956 
2957 /*******************************************************************************
2958  *
2959  * Function         bta_dm_remove_sec_dev_entry
2960  *
2961  * Description      Removes device entry from Security device DB if ACL
2962  connection with
2963  *                  remtoe device does not exist, else schedule for dev entry
2964  removal upon
2965                      ACL close
2966  *
2967  * Returns          void
2968  *
2969  ******************************************************************************/
bta_dm_remove_sec_dev_entry(const RawAddress & remote_bd_addr)2970 static void bta_dm_remove_sec_dev_entry(const RawAddress& remote_bd_addr) {
2971   if (BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_LE) ||
2972       BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_BR_EDR)) {
2973     APPL_TRACE_DEBUG(
2974         "%s ACL is not down. Schedule for  Dev Removal when ACL closes",
2975         __func__);
2976     BTM_SecClearSecurityFlags(remote_bd_addr);
2977     for (int i = 0; i < bta_dm_cb.device_list.count; i++) {
2978       if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr == remote_bd_addr) {
2979         bta_dm_cb.device_list.peer_device[i].remove_dev_pending = TRUE;
2980         break;
2981       }
2982     }
2983   } else {
2984     // remote_bd_addr comes from security record, which is removed in
2985     // BTM_SecDeleteDevice.
2986     RawAddress addr_copy = remote_bd_addr;
2987     bta_dm_process_remove_device_no_callback(addr_copy);
2988   }
2989 }
2990 
2991 /*******************************************************************************
2992  *
2993  * Function         bta_dm_adjust_roles
2994  *
2995  * Description      Adjust roles
2996  *
2997  *
2998  * Returns          void
2999  *
3000  ******************************************************************************/
bta_dm_adjust_roles(bool delay_role_switch)3001 static void bta_dm_adjust_roles(bool delay_role_switch) {
3002   uint8_t i;
3003   uint8_t link_count = bta_dm_cb.device_list.count;
3004   if (link_count) {
3005     for (i = 0; i < bta_dm_cb.device_list.count; i++) {
3006       if (bta_dm_cb.device_list.peer_device[i].conn_state == BTA_DM_CONNECTED &&
3007           bta_dm_cb.device_list.peer_device[i].transport ==
3008               BT_TRANSPORT_BR_EDR) {
3009         if ((bta_dm_cb.device_list.peer_device[i].pref_role ==
3010              BTA_CENTRAL_ROLE_ONLY) ||
3011             (link_count > 1)) {
3012           /* Initiating immediate role switch with certain remote devices
3013             has caused issues due to role  switch colliding with link encryption
3014             setup and
3015             causing encryption (and in turn the link) to fail .  These device .
3016             Firmware
3017             versions are stored in a rejectlist and role switch with these
3018             devices are
3019             delayed to avoid the collision with link encryption setup */
3020 
3021           if (bta_dm_cb.device_list.peer_device[i].pref_role !=
3022                   BTA_PERIPHERAL_ROLE_ONLY &&
3023               !delay_role_switch) {
3024             BTM_SwitchRoleToCentral(
3025                 bta_dm_cb.device_list.peer_device[i].peer_bdaddr);
3026           } else {
3027             alarm_set_on_mloop(bta_dm_cb.switch_delay_timer,
3028                                BTA_DM_SWITCH_DELAY_TIMER_MS,
3029                                bta_dm_delay_role_switch_cback, NULL);
3030           }
3031         }
3032       }
3033     }
3034   }
3035 }
3036 
3037 /*******************************************************************************
3038  *
3039  * Function         bta_dm_get_remname
3040  *
3041  * Description      Returns a pointer to the remote name stored in the DM
3042  *                  control block if it exists, or from the BTM memory.
3043  *
3044  * Returns          char * - Pointer to the remote device name
3045  ******************************************************************************/
bta_dm_get_remname(void)3046 static char* bta_dm_get_remname(void) {
3047   char* p_name = (char*)bta_dm_search_cb.peer_name;
3048   char* p_temp;
3049 
3050   /* If the name isn't already stored, try retrieving from BTM */
3051   if (*p_name == '\0') {
3052     p_temp = BTM_SecReadDevName(bta_dm_search_cb.peer_bdaddr);
3053     if (p_temp != NULL) p_name = p_temp;
3054   }
3055 
3056   return p_name;
3057 }
3058 
3059 /*******************************************************************************
3060  *
3061  * Function         bta_dm_bond_cancel_complete_cback
3062  *
3063  * Description      Authentication complete callback from BTM
3064  *
3065  * Returns          void
3066  *
3067  ******************************************************************************/
bta_dm_bond_cancel_complete_cback(tBTM_STATUS result)3068 static void bta_dm_bond_cancel_complete_cback(tBTM_STATUS result) {
3069   tBTA_DM_SEC sec_event;
3070 
3071   if (result == BTM_SUCCESS)
3072     sec_event.bond_cancel_cmpl.result = BTA_SUCCESS;
3073   else
3074     sec_event.bond_cancel_cmpl.result = BTA_FAILURE;
3075 
3076   if (bta_dm_cb.p_sec_cback) {
3077     bta_dm_cb.p_sec_cback(BTA_DM_BOND_CANCEL_CMPL_EVT, &sec_event);
3078   }
3079 }
3080 
3081 /*******************************************************************************
3082  *
3083  * Function         find_utf8_char_boundary
3084  *
3085  * Description      This function checks a UTF8 string |utf8str| starting at
3086  *                  |offset|, moving backwards and returns the offset of the
3087  *                  next valid UTF8 character boundary found.
3088  *
3089  * Returns          Offset of UTF8 character boundary
3090  *
3091  ******************************************************************************/
find_utf8_char_boundary(const char * utf8str,size_t offset)3092 static size_t find_utf8_char_boundary(const char* utf8str, size_t offset) {
3093   CHECK(utf8str);
3094   CHECK(offset > 0);
3095 
3096   while (--offset) {
3097     uint8_t ch = (uint8_t)utf8str[offset];
3098     if ((ch & 0x80) == 0x00)  // ASCII
3099       return offset + 1;
3100     if ((ch & 0xC0) == 0xC0)  // Multi-byte sequence start
3101       return offset;
3102   }
3103 
3104   return 0;
3105 }
3106 
3107 /*******************************************************************************
3108  *
3109  * Function         bta_dm_set_eir
3110  *
3111  * Description      This function creates EIR tagged data and writes it to
3112  *                  controller.
3113  *
3114  * Returns          None
3115  *
3116  ******************************************************************************/
bta_dm_set_eir(char * local_name)3117 static void bta_dm_set_eir(char* local_name) {
3118   uint8_t* p;
3119   uint8_t* p_length;
3120 #if (BTA_EIR_CANNED_UUID_LIST != TRUE)
3121   uint8_t* p_type;
3122   uint8_t max_num_uuid;
3123 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
3124   uint8_t custom_uuid_idx;
3125 #endif  // BTA_EIR_SERVER_NUM_CUSTOM_UUID
3126 #endif  // BTA_EIR_CANNED_UUID_LIST
3127 #if (BTM_EIR_DEFAULT_FEC_REQUIRED == FALSE)
3128   uint8_t free_eir_length = HCI_EXT_INQ_RESPONSE_LEN;
3129 #else  // BTM_EIR_DEFAULT_FEC_REQUIRED
3130   uint8_t free_eir_length = HCI_DM5_PACKET_SIZE;
3131 #endif  // BTM_EIR_DEFAULT_FEC_REQUIRED
3132   uint8_t num_uuid;
3133   uint8_t data_type;
3134   uint8_t local_name_len;
3135 
3136   /* wait until complete to disable */
3137   if (alarm_is_scheduled(bta_dm_cb.disable_timer)) return;
3138 
3139 #if (BTA_EIR_CANNED_UUID_LIST != TRUE)
3140   /* if local name is not provided, get it from controller */
3141   if (local_name == NULL) {
3142     if (BTM_ReadLocalDeviceName((const char**)&local_name) != BTM_SUCCESS) {
3143       APPL_TRACE_ERROR("Fail to read local device name for EIR");
3144     }
3145   }
3146 #endif  // BTA_EIR_CANNED_UUID_LIST
3147 
3148   /* Allocate a buffer to hold HCI command */
3149   BT_HDR* p_buf = (BT_HDR*)osi_malloc(BTM_CMD_BUF_SIZE);
3150   ASSERT(p_buf != nullptr);
3151   p = (uint8_t*)p_buf + BTM_HCI_EIR_OFFSET;
3152 
3153   memset(p, 0x00, HCI_EXT_INQ_RESPONSE_LEN);
3154 
3155   LOG_INFO("Generating extended inquiry response packet EIR");
3156 
3157   if (local_name)
3158     local_name_len = strlen(local_name);
3159   else
3160     local_name_len = 0;
3161 
3162   data_type = HCI_EIR_COMPLETE_LOCAL_NAME_TYPE;
3163   /* if local name is longer than minimum length of shortened name */
3164   /* check whether it needs to be shortened or not */
3165   if (local_name_len > p_bta_dm_eir_cfg->bta_dm_eir_min_name_len) {
3166 /* get number of UUID 16-bit list */
3167 #if (BTA_EIR_CANNED_UUID_LIST == TRUE)
3168     num_uuid = p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len / Uuid::kNumBytes16;
3169 #else   // BTA_EIR_CANNED_UUID_LIST
3170     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes16;
3171     data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices(
3172         bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid);
3173     p = (uint8_t*)p_buf + BTM_HCI_EIR_OFFSET; /* reset p */
3174 #endif  // BTA_EIR_CANNED_UUID_LIST
3175 
3176     /* if UUID doesn't fit remaing space, shorten local name */
3177     if (local_name_len > (free_eir_length - 4 - num_uuid * Uuid::kNumBytes16)) {
3178       local_name_len = find_utf8_char_boundary(
3179           local_name, p_bta_dm_eir_cfg->bta_dm_eir_min_name_len);
3180       APPL_TRACE_WARNING("%s local name is shortened (%d)", __func__,
3181                          local_name_len);
3182       data_type = HCI_EIR_SHORTENED_LOCAL_NAME_TYPE;
3183     } else {
3184       data_type = HCI_EIR_COMPLETE_LOCAL_NAME_TYPE;
3185     }
3186   }
3187 
3188   UINT8_TO_STREAM(p, local_name_len + 1);
3189   UINT8_TO_STREAM(p, data_type);
3190 
3191   if (local_name != NULL) {
3192     memcpy(p, local_name, local_name_len);
3193     p += local_name_len;
3194   }
3195   free_eir_length -= local_name_len + 2;
3196 
3197 #if (BTA_EIR_CANNED_UUID_LIST == TRUE)
3198   /* if UUID list is provided as static data in configuration */
3199   if ((p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len > 0) &&
3200       (p_bta_dm_eir_cfg->bta_dm_eir_uuid16)) {
3201     if (free_eir_length > Uuid::kNumBytes16 + 2) {
3202       free_eir_length -= 2;
3203 
3204       if (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len) {
3205         num_uuid = p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len / Uuid::kNumBytes16;
3206         data_type = HCI_EIR_COMPLETE_16BITS_UUID_TYPE;
3207       } else /* not enough room for all UUIDs */
3208       {
3209         APPL_TRACE_WARNING("BTA EIR: UUID 16-bit list is truncated");
3210         num_uuid = free_eir_length / Uuid::kNumBytes16;
3211         data_type = HCI_EIR_MORE_16BITS_UUID_TYPE;
3212       }
3213       UINT8_TO_STREAM(p, num_uuid * Uuid::kNumBytes16 + 1);
3214       UINT8_TO_STREAM(p, data_type);
3215       memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_uuid16,
3216              num_uuid * Uuid::kNumBytes16);
3217       p += num_uuid * Uuid::kNumBytes16;
3218       free_eir_length -= num_uuid * Uuid::kNumBytes16;
3219     }
3220   }
3221 #else /* (BTA_EIR_CANNED_UUID_LIST == TRUE) */
3222   /* if UUID list is dynamic */
3223   if (free_eir_length >= 2) {
3224     p_length = p++;
3225     p_type = p++;
3226     num_uuid = 0;
3227 
3228     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes16;
3229     data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices(
3230         bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid);
3231 
3232     if (data_type == HCI_EIR_MORE_16BITS_UUID_TYPE) {
3233       APPL_TRACE_WARNING("BTA EIR: UUID 16-bit list is truncated");
3234     }
3235 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
3236     else {
3237       for (custom_uuid_idx = 0;
3238            custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID;
3239            custom_uuid_idx++) {
3240         const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid;
3241         if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes16) {
3242           if (num_uuid < max_num_uuid) {
3243             UINT16_TO_STREAM(p, curr.As16Bit());
3244             num_uuid++;
3245           } else {
3246             data_type = HCI_EIR_MORE_16BITS_UUID_TYPE;
3247             APPL_TRACE_WARNING("BTA EIR: UUID 16-bit list is truncated");
3248             break;
3249           }
3250         }
3251       }
3252     }
3253 #endif /* (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) */
3254 
3255     UINT8_TO_STREAM(p_length, num_uuid * Uuid::kNumBytes16 + 1);
3256     UINT8_TO_STREAM(p_type, data_type);
3257     free_eir_length -= num_uuid * Uuid::kNumBytes16 + 2;
3258   }
3259 #endif /* (BTA_EIR_CANNED_UUID_LIST == TRUE) */
3260 
3261 #if (BTA_EIR_CANNED_UUID_LIST != TRUE && BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
3262   /* Adding 32-bit UUID list */
3263   if (free_eir_length >= 2) {
3264     p_length = p++;
3265     p_type = p++;
3266     num_uuid = 0;
3267     data_type = HCI_EIR_COMPLETE_32BITS_UUID_TYPE;
3268 
3269     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes32;
3270 
3271     for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID;
3272          custom_uuid_idx++) {
3273       const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid;
3274       if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes32) {
3275         if (num_uuid < max_num_uuid) {
3276           UINT32_TO_STREAM(p, curr.As32Bit());
3277           num_uuid++;
3278         } else {
3279           data_type = HCI_EIR_MORE_32BITS_UUID_TYPE;
3280           APPL_TRACE_WARNING("BTA EIR: UUID 32-bit list is truncated");
3281           break;
3282         }
3283       }
3284     }
3285 
3286     UINT8_TO_STREAM(p_length, num_uuid * Uuid::kNumBytes32 + 1);
3287     UINT8_TO_STREAM(p_type, data_type);
3288     free_eir_length -= num_uuid * Uuid::kNumBytes32 + 2;
3289   }
3290 
3291   /* Adding 128-bit UUID list */
3292   if (free_eir_length >= 2) {
3293     p_length = p++;
3294     p_type = p++;
3295     num_uuid = 0;
3296     data_type = HCI_EIR_COMPLETE_128BITS_UUID_TYPE;
3297 
3298     max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes128;
3299 
3300     for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID;
3301          custom_uuid_idx++) {
3302       const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid;
3303       if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes128) {
3304         if (num_uuid < max_num_uuid) {
3305           ARRAY16_TO_STREAM(p, curr.To128BitBE().data());
3306           num_uuid++;
3307         } else {
3308           data_type = HCI_EIR_MORE_128BITS_UUID_TYPE;
3309           APPL_TRACE_WARNING("BTA EIR: UUID 128-bit list is truncated");
3310           break;
3311         }
3312       }
3313     }
3314 
3315     UINT8_TO_STREAM(p_length, num_uuid * Uuid::kNumBytes128 + 1);
3316     UINT8_TO_STREAM(p_type, data_type);
3317     free_eir_length -= num_uuid * Uuid::kNumBytes128 + 2;
3318   }
3319 #endif /* ( BTA_EIR_CANNED_UUID_LIST != TRUE \
3320           )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) */
3321 
3322   /* if Flags are provided in configuration */
3323   if ((p_bta_dm_eir_cfg->bta_dm_eir_flag_len > 0) &&
3324       (p_bta_dm_eir_cfg->bta_dm_eir_flags) &&
3325       (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2)) {
3326     UINT8_TO_STREAM(p, p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 1);
3327     UINT8_TO_STREAM(p, HCI_EIR_FLAGS_TYPE);
3328     memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_flags,
3329            p_bta_dm_eir_cfg->bta_dm_eir_flag_len);
3330     p += p_bta_dm_eir_cfg->bta_dm_eir_flag_len;
3331     free_eir_length -= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2;
3332   }
3333 
3334   /* if Manufacturer Specific are provided in configuration */
3335   if ((p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len > 0) &&
3336       (p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec) &&
3337       (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 2)) {
3338     p_length = p;
3339 
3340     UINT8_TO_STREAM(p, p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 1);
3341     UINT8_TO_STREAM(p, HCI_EIR_MANUFACTURER_SPECIFIC_TYPE);
3342     memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec,
3343            p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len);
3344     p += p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len;
3345     free_eir_length -= p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 2;
3346 
3347   } else {
3348     p_length = NULL;
3349   }
3350 
3351   /* if Inquiry Tx Resp Power compiled */
3352   if ((p_bta_dm_eir_cfg->bta_dm_eir_inq_tx_power) && (free_eir_length >= 3)) {
3353     UINT8_TO_STREAM(p, 2); /* Length field */
3354     UINT8_TO_STREAM(p, HCI_EIR_TX_POWER_LEVEL_TYPE);
3355     UINT8_TO_STREAM(p, *(p_bta_dm_eir_cfg->bta_dm_eir_inq_tx_power));
3356     free_eir_length -= 3;
3357   }
3358 
3359   if (free_eir_length)
3360     UINT8_TO_STREAM(p, 0); /* terminator of significant part */
3361 
3362   get_btm_client_interface().eir.BTM_WriteEIR(p_buf);
3363 }
3364 
3365 #if (BTA_EIR_CANNED_UUID_LIST != TRUE)
3366 /*******************************************************************************
3367  *
3368  * Function         bta_dm_get_cust_uuid_index
3369  *
3370  * Description      Get index of custom uuid from list
3371  *                  Note, handle equals to 0 means to find a vacant
3372  *                  from list.
3373  *
3374  * Returns          Index of array
3375  *                  bta_dm_cb.bta_custom_uuid[BTA_EIR_SERVER_NUM_CUSTOM_UUID]
3376  *
3377  ******************************************************************************/
bta_dm_get_cust_uuid_index(uint32_t handle)3378 static uint8_t bta_dm_get_cust_uuid_index(uint32_t handle) {
3379 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
3380   uint8_t c_uu_idx = 0;
3381 
3382   while(c_uu_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID &&
3383       bta_dm_cb.bta_custom_uuid[c_uu_idx].handle != handle) {
3384     c_uu_idx++;
3385   }
3386 
3387   return c_uu_idx;
3388 #else
3389   return 0;
3390 #endif
3391 }
3392 
3393 /*******************************************************************************
3394  *
3395  * Function         bta_dm_update_cust_uuid
3396  *
3397  * Description      Update custom uuid with given value
3398  *
3399  * Returns          None
3400  *
3401  ******************************************************************************/
bta_dm_update_cust_uuid(uint8_t c_uu_idx,const Uuid & uuid,uint32_t handle)3402 static void bta_dm_update_cust_uuid(uint8_t c_uu_idx, const Uuid& uuid, uint32_t handle) {
3403 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
3404   if (c_uu_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID) {
3405     tBTA_CUSTOM_UUID& curr = bta_dm_cb.bta_custom_uuid[c_uu_idx];
3406     curr.custom_uuid.UpdateUuid(uuid);
3407     curr.handle = handle;
3408   } else {
3409     APPL_TRACE_ERROR("%s invalid uuid index %d", __func__, c_uu_idx);
3410   }
3411 #endif
3412 }
3413 
3414 /*******************************************************************************
3415  *
3416  * Function         bta_dm_eir_update_cust_uuid
3417  *
3418  * Description      This function adds or removes custom service UUID in EIR database.
3419  *
3420  * Returns          None
3421  *
3422  ******************************************************************************/
bta_dm_eir_update_cust_uuid(const tBTA_CUSTOM_UUID & curr,bool adding)3423 void bta_dm_eir_update_cust_uuid(const tBTA_CUSTOM_UUID& curr, bool adding) {
3424   APPL_TRACE_DEBUG("%s", __func__);
3425 #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0)
3426   uint8_t c_uu_idx = 0;
3427   if (adding) {
3428     c_uu_idx = bta_dm_get_cust_uuid_index(0); /* find a vacant from uuid list */
3429     bta_dm_update_cust_uuid(c_uu_idx, curr.custom_uuid, curr.handle);
3430   } else {
3431     c_uu_idx = bta_dm_get_cust_uuid_index(curr.handle); /* find the uuid from uuid list */
3432     bta_dm_update_cust_uuid(c_uu_idx, curr.custom_uuid, 0);
3433   }
3434 
3435   /* Update EIR when UUIDs are changed */
3436   if (c_uu_idx <= BTA_EIR_SERVER_NUM_CUSTOM_UUID) {
3437     bta_dm_set_eir(NULL);
3438   }
3439 #endif
3440 }
3441 
3442 /*******************************************************************************
3443  *
3444  * Function         bta_dm_eir_update_uuid
3445  *
3446  * Description      This function adds or removes service UUID in EIR database.
3447  *
3448  * Returns          None
3449  *
3450  ******************************************************************************/
bta_dm_eir_update_uuid(uint16_t uuid16,bool adding)3451 void bta_dm_eir_update_uuid(uint16_t uuid16, bool adding) {
3452   /* if this UUID is not advertised in EIR */
3453   if (!BTM_HasEirService(p_bta_dm_eir_cfg->uuid_mask, uuid16)) return;
3454 
3455   if (adding) {
3456     LOG_INFO("EIR Adding UUID=0x%04X into extended inquiry response", uuid16);
3457 
3458     BTM_AddEirService(bta_dm_cb.eir_uuid, uuid16);
3459   } else {
3460     LOG_INFO("EIR Removing UUID=0x%04X from extended inquiry response", uuid16);
3461 
3462     get_btm_client_interface().eir.BTM_RemoveEirService(bta_dm_cb.eir_uuid,
3463                                                         uuid16);
3464   }
3465 
3466   bta_dm_set_eir(NULL);
3467 }
3468 #endif
3469 
find_connected_device(const RawAddress & bd_addr,UNUSED_ATTR tBT_TRANSPORT transport)3470 static tBTA_DM_PEER_DEVICE* find_connected_device(
3471     const RawAddress& bd_addr, UNUSED_ATTR tBT_TRANSPORT transport) {
3472   for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) {
3473     if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr == bd_addr &&
3474         bta_dm_cb.device_list.peer_device[i].conn_state == BTA_DM_CONNECTED)
3475       return &bta_dm_cb.device_list.peer_device[i];
3476   }
3477   return nullptr;
3478 }
3479 
3480 /*******************************************************************************
3481  *
3482  * Function         bta_dm_encrypt_cback
3483  *
3484  * Description      link encryption complete callback.
3485  *
3486  * Returns         None
3487  *
3488  ******************************************************************************/
bta_dm_encrypt_cback(const RawAddress * bd_addr,tBT_TRANSPORT transport,UNUSED_ATTR void * p_ref_data,tBTM_STATUS result)3489 void bta_dm_encrypt_cback(const RawAddress* bd_addr, tBT_TRANSPORT transport,
3490                           UNUSED_ATTR void* p_ref_data, tBTM_STATUS result) {
3491   tBTA_DM_ENCRYPT_CBACK* p_callback = nullptr;
3492   tBTA_DM_PEER_DEVICE* device = find_connected_device(*bd_addr, transport);
3493   if (device != nullptr) {
3494     p_callback = device->p_encrypt_cback;
3495     device->p_encrypt_cback = nullptr;
3496   }
3497 
3498   tBTA_STATUS bta_status = BTA_SUCCESS;
3499   switch (result) {
3500     case BTM_SUCCESS:
3501       LOG_WARN("Encrypted link peer:%s transport:%s status:%s callback:%c",
3502                ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)),
3503                bt_transport_text(transport).c_str(),
3504                btm_status_text(result).c_str(), (p_callback) ? 'T' : 'F');
3505       break;
3506     case BTM_WRONG_MODE:
3507       LOG_WARN(
3508           "Unable to encrypt link peer:%s transport:%s status:%s callback:%c",
3509           ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)), bt_transport_text(transport).c_str(),
3510           btm_status_text(result).c_str(), (p_callback) ? 'T' : 'F');
3511       bta_status = BTA_WRONG_MODE;
3512       break;
3513     case BTM_NO_RESOURCES:
3514       LOG_WARN(
3515           "Unable to encrypt link peer:%s transport:%s status:%s callback:%c",
3516           ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)), bt_transport_text(transport).c_str(),
3517           btm_status_text(result).c_str(), (p_callback) ? 'T' : 'F');
3518       bta_status = BTA_NO_RESOURCES;
3519       break;
3520     case BTM_BUSY:
3521       LOG_WARN(
3522           "Unable to encrypt link peer:%s transport:%s status:%s callback:%c",
3523           ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)), bt_transport_text(transport).c_str(),
3524           btm_status_text(result).c_str(), (p_callback) ? 'T' : 'F');
3525       bta_status = BTA_BUSY;
3526       break;
3527     default:
3528       LOG_ERROR(
3529           "Failed to encrypt link peer:%s transport:%s status:%s callback:%c",
3530           ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)), bt_transport_text(transport).c_str(),
3531           btm_status_text(result).c_str(), (p_callback) ? 'T' : 'F');
3532       bta_status = BTA_FAILURE;
3533       break;
3534   }
3535   if (p_callback) {
3536     (*p_callback)(*bd_addr, transport, bta_status);
3537   }
3538 }
3539 
3540 /**This function to encrypt the link */
bta_dm_set_encryption(const RawAddress & bd_addr,tBT_TRANSPORT transport,tBTA_DM_ENCRYPT_CBACK * p_callback,tBTM_BLE_SEC_ACT sec_act)3541 void bta_dm_set_encryption(const RawAddress& bd_addr, tBT_TRANSPORT transport,
3542                            tBTA_DM_ENCRYPT_CBACK* p_callback,
3543                            tBTM_BLE_SEC_ACT sec_act) {
3544   if (p_callback == nullptr) {
3545     LOG_ERROR("bta_dm_set_encryption callback is not provided");
3546     return;
3547   }
3548 
3549   tBTA_DM_PEER_DEVICE* device = find_connected_device(bd_addr, transport);
3550   if (device == nullptr) {
3551     LOG_ERROR("Unable to find active ACL connection device:%s transport:%s",
3552               ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
3553     return;
3554   }
3555 
3556   if (device->p_encrypt_cback) {
3557     LOG_ERROR(
3558         "Unable to start encryption as already in progress peer:%s "
3559         "transport:%s",
3560         ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
3561     (*p_callback)(bd_addr, transport, BTA_BUSY);
3562     return;
3563   }
3564 
3565   if (BTM_SetEncryption(bd_addr, transport, bta_dm_encrypt_cback, NULL,
3566                         sec_act) == BTM_CMD_STARTED) {
3567     device->p_encrypt_cback = p_callback;
3568     LOG_DEBUG("Started encryption peer:%s transport:%s",
3569               ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
3570   } else {
3571     LOG_ERROR("Unable to start encryption process peer:%s transport:%s",
3572               ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
3573   }
3574 }
3575 
bta_dm_check_if_only_hd_connected(const RawAddress & peer_addr)3576 bool bta_dm_check_if_only_hd_connected(const RawAddress& peer_addr) {
3577   APPL_TRACE_DEBUG("%s: count(%d)", __func__, bta_dm_conn_srvcs.count);
3578 
3579   for (uint8_t j = 0; j < bta_dm_conn_srvcs.count; j++) {
3580     // Check if profiles other than hid are connected
3581     if ((bta_dm_conn_srvcs.conn_srvc[j].id != BTA_ID_HD) &&
3582         bta_dm_conn_srvcs.conn_srvc[j].peer_bdaddr == peer_addr) {
3583       APPL_TRACE_DEBUG("%s: Another profile (id=%d) is connected", __func__,
3584                        bta_dm_conn_srvcs.conn_srvc[j].id);
3585       return false;
3586     }
3587   }
3588 
3589   return true;
3590 }
3591 
3592 /*******************************************************************************
3593  *
3594  * Function         bta_dm_observe_results_cb
3595  *
3596  * Description      Callback for BLE Observe result
3597  *
3598  *
3599  * Returns          void
3600  *
3601  ******************************************************************************/
bta_dm_observe_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)3602 static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq,
3603                                       const uint8_t* p_eir, uint16_t eir_len) {
3604   tBTA_DM_SEARCH result;
3605   tBTM_INQ_INFO* p_inq_info;
3606   APPL_TRACE_DEBUG("bta_dm_observe_results_cb");
3607 
3608   result.inq_res.bd_addr = p_inq->remote_bd_addr;
3609   result.inq_res.original_bda = p_inq->original_bda;
3610   result.inq_res.rssi = p_inq->rssi;
3611   result.inq_res.ble_addr_type = p_inq->ble_addr_type;
3612   result.inq_res.inq_result_type = p_inq->inq_result_type;
3613   result.inq_res.device_type = p_inq->device_type;
3614   result.inq_res.flag = p_inq->flag;
3615   result.inq_res.ble_evt_type = p_inq->ble_evt_type;
3616   result.inq_res.ble_primary_phy = p_inq->ble_primary_phy;
3617   result.inq_res.ble_secondary_phy = p_inq->ble_secondary_phy;
3618   result.inq_res.ble_advertising_sid = p_inq->ble_advertising_sid;
3619   result.inq_res.ble_tx_power = p_inq->ble_tx_power;
3620   result.inq_res.ble_periodic_adv_int = p_inq->ble_periodic_adv_int;
3621 
3622   /* application will parse EIR to find out remote device name */
3623   result.inq_res.p_eir = const_cast<uint8_t*>(p_eir);
3624   result.inq_res.eir_len = eir_len;
3625 
3626   p_inq_info = BTM_InqDbRead(p_inq->remote_bd_addr);
3627   if (p_inq_info != NULL) {
3628     /* initialize remt_name_not_required to false so that we get the name by
3629      * default */
3630     result.inq_res.remt_name_not_required = false;
3631   }
3632 
3633   if (bta_dm_search_cb.p_scan_cback)
3634     bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_RES_EVT, &result);
3635 
3636   if (p_inq_info) {
3637     /* application indicates if it knows the remote name, inside the callback
3638      copy that to the inquiry data base*/
3639     if (result.inq_res.remt_name_not_required)
3640       p_inq_info->appl_knows_rem_name = true;
3641   }
3642 }
3643 
3644 /*******************************************************************************
3645  *
3646  * Function         bta_dm_opportunistic_observe_results_cb
3647  *
3648  * Description      Callback for BLE Observe result
3649  *
3650  *
3651  * Returns          void
3652  *
3653  ******************************************************************************/
bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)3654 static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq,
3655                                                     const uint8_t* p_eir,
3656                                                     uint16_t eir_len) {
3657   tBTA_DM_SEARCH result;
3658   tBTM_INQ_INFO* p_inq_info;
3659 
3660   result.inq_res.bd_addr = p_inq->remote_bd_addr;
3661   result.inq_res.rssi = p_inq->rssi;
3662   result.inq_res.ble_addr_type = p_inq->ble_addr_type;
3663   result.inq_res.inq_result_type = p_inq->inq_result_type;
3664   result.inq_res.device_type = p_inq->device_type;
3665   result.inq_res.flag = p_inq->flag;
3666   result.inq_res.ble_evt_type = p_inq->ble_evt_type;
3667   result.inq_res.ble_primary_phy = p_inq->ble_primary_phy;
3668   result.inq_res.ble_secondary_phy = p_inq->ble_secondary_phy;
3669   result.inq_res.ble_advertising_sid = p_inq->ble_advertising_sid;
3670   result.inq_res.ble_tx_power = p_inq->ble_tx_power;
3671   result.inq_res.ble_periodic_adv_int = p_inq->ble_periodic_adv_int;
3672 
3673   /* application will parse EIR to find out remote device name */
3674   result.inq_res.p_eir = const_cast<uint8_t*>(p_eir);
3675   result.inq_res.eir_len = eir_len;
3676 
3677   p_inq_info = BTM_InqDbRead(p_inq->remote_bd_addr);
3678   if (p_inq_info != NULL) {
3679     /* initialize remt_name_not_required to false so that we get the name by
3680      * default */
3681     result.inq_res.remt_name_not_required = false;
3682   }
3683 
3684   if (bta_dm_search_cb.p_csis_scan_cback)
3685     bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_RES_EVT, &result);
3686 
3687   if (p_inq_info) {
3688     /* application indicates if it knows the remote name, inside the callback
3689      copy that to the inquiry data base*/
3690     if (result.inq_res.remt_name_not_required)
3691       p_inq_info->appl_knows_rem_name = true;
3692   }
3693 }
3694 
3695 /*******************************************************************************
3696  *
3697  * Function         bta_dm_observe_cmpl_cb
3698  *
3699  * Description      Callback for BLE Observe complete
3700  *
3701  *
3702  * Returns          void
3703  *
3704  ******************************************************************************/
bta_dm_observe_cmpl_cb(void * p_result)3705 static void bta_dm_observe_cmpl_cb(void* p_result) {
3706   tBTA_DM_SEARCH data;
3707 
3708   APPL_TRACE_DEBUG("bta_dm_observe_cmpl_cb");
3709 
3710   data.inq_cmpl.num_resps = ((tBTM_INQUIRY_CMPL*)p_result)->num_resp;
3711   if (bta_dm_search_cb.p_scan_cback) {
3712     bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
3713   }
3714   if (bta_dm_search_cb.p_csis_scan_cback) {
3715     bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
3716   }
3717 }
3718 
ble_io_req(const RawAddress & bd_addr,tBTM_IO_CAP * p_io_cap,tBTM_OOB_DATA * p_oob_data,tBTM_LE_AUTH_REQ * p_auth_req,uint8_t * p_max_key_size,tBTM_LE_KEY_TYPE * p_init_key,tBTM_LE_KEY_TYPE * p_resp_key)3719 static void ble_io_req(const RawAddress& bd_addr, tBTM_IO_CAP* p_io_cap,
3720                        tBTM_OOB_DATA* p_oob_data, tBTM_LE_AUTH_REQ* p_auth_req,
3721                        uint8_t* p_max_key_size, tBTM_LE_KEY_TYPE* p_init_key,
3722                        tBTM_LE_KEY_TYPE* p_resp_key) {
3723   /* Retrieve the properties from file system if possible */
3724   tBTE_APPL_CFG nv_config;
3725   if (btif_dm_get_smp_config(&nv_config)) bte_appl_cfg = nv_config;
3726 
3727   /* *p_auth_req by default is false for devices with NoInputNoOutput; true for
3728    * other devices. */
3729 
3730   if (bte_appl_cfg.ble_auth_req)
3731     *p_auth_req = bte_appl_cfg.ble_auth_req |
3732                   (bte_appl_cfg.ble_auth_req & 0x04) | ((*p_auth_req) & 0x04);
3733 
3734   /* if OOB is not supported, this call-out function does not need to do
3735    * anything
3736    * otherwise, look for the OOB data associated with the address and set
3737    * *p_oob_data accordingly.
3738    * If the answer can not be obtained right away,
3739    * set *p_oob_data to BTA_OOB_UNKNOWN and call bta_dm_ci_io_req() when the
3740    * answer is available.
3741    */
3742 
3743   btif_dm_set_oob_for_le_io_req(bd_addr, p_oob_data, p_auth_req);
3744 
3745   if (bte_appl_cfg.ble_io_cap <= 4) *p_io_cap = bte_appl_cfg.ble_io_cap;
3746 
3747   if (bte_appl_cfg.ble_init_key <= BTM_BLE_INITIATOR_KEY_SIZE)
3748     *p_init_key = bte_appl_cfg.ble_init_key;
3749 
3750   if (bte_appl_cfg.ble_resp_key <= BTM_BLE_RESPONDER_KEY_SIZE)
3751     *p_resp_key = bte_appl_cfg.ble_resp_key;
3752 
3753   if (bte_appl_cfg.ble_max_key_size > 7 && bte_appl_cfg.ble_max_key_size <= 16)
3754     *p_max_key_size = bte_appl_cfg.ble_max_key_size;
3755 }
3756 
3757 /*******************************************************************************
3758  *
3759  * Function         bta_dm_ble_smp_cback
3760  *
3761  * Description      Callback for BLE SMP
3762  *
3763  *
3764  * Returns          void
3765  *
3766  ******************************************************************************/
bta_dm_ble_smp_cback(tBTM_LE_EVT event,const RawAddress & bda,tBTM_LE_EVT_DATA * p_data)3767 static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, const RawAddress& bda,
3768                                     tBTM_LE_EVT_DATA* p_data) {
3769   tBTM_STATUS status = BTM_SUCCESS;
3770   tBTA_DM_SEC sec_event;
3771   char* p_name = NULL;
3772 
3773   if (!bta_dm_cb.p_sec_cback) return BTM_NOT_AUTHORIZED;
3774 
3775   memset(&sec_event, 0, sizeof(tBTA_DM_SEC));
3776   switch (event) {
3777     case BTM_LE_IO_REQ_EVT:
3778       ble_io_req(bda, &p_data->io_req.io_cap, &p_data->io_req.oob_data,
3779                  &p_data->io_req.auth_req, &p_data->io_req.max_key_size,
3780                  &p_data->io_req.init_keys, &p_data->io_req.resp_keys);
3781       APPL_TRACE_EVENT("io mitm: %d oob_data:%d", p_data->io_req.auth_req,
3782                        p_data->io_req.oob_data);
3783       break;
3784 
3785     case BTM_LE_CONSENT_REQ_EVT:
3786       sec_event.ble_req.bd_addr = bda;
3787       p_name = BTM_SecReadDevName(bda);
3788       if (p_name != NULL)
3789         strlcpy((char*)sec_event.ble_req.bd_name, p_name, BD_NAME_LEN);
3790       else
3791         sec_event.ble_req.bd_name[0] = 0;
3792       bta_dm_cb.p_sec_cback(BTA_DM_BLE_CONSENT_REQ_EVT, &sec_event);
3793       break;
3794 
3795     case BTM_LE_SEC_REQUEST_EVT:
3796       sec_event.ble_req.bd_addr = bda;
3797       p_name = BTM_SecReadDevName(bda);
3798       if (p_name != NULL)
3799         strlcpy((char*)sec_event.ble_req.bd_name, p_name, BD_NAME_LEN + 1);
3800       else
3801         sec_event.ble_req.bd_name[0] = 0;
3802       bta_dm_cb.p_sec_cback(BTA_DM_BLE_SEC_REQ_EVT, &sec_event);
3803       break;
3804 
3805     case BTM_LE_KEY_NOTIF_EVT:
3806       sec_event.key_notif.bd_addr = bda;
3807       p_name = BTM_SecReadDevName(bda);
3808       if (p_name != NULL)
3809         strlcpy((char*)sec_event.key_notif.bd_name, p_name, BD_NAME_LEN + 1);
3810       else
3811         sec_event.key_notif.bd_name[0] = 0;
3812       sec_event.key_notif.passkey = p_data->key_notif;
3813       bta_dm_cb.p_sec_cback(BTA_DM_BLE_PASSKEY_NOTIF_EVT, &sec_event);
3814       break;
3815 
3816     case BTM_LE_KEY_REQ_EVT:
3817       sec_event.ble_req.bd_addr = bda;
3818       bta_dm_cb.p_sec_cback(BTA_DM_BLE_PASSKEY_REQ_EVT, &sec_event);
3819       break;
3820 
3821     case BTM_LE_OOB_REQ_EVT:
3822       sec_event.ble_req.bd_addr = bda;
3823       bta_dm_cb.p_sec_cback(BTA_DM_BLE_OOB_REQ_EVT, &sec_event);
3824       break;
3825 
3826     case BTM_LE_NC_REQ_EVT:
3827       sec_event.key_notif.bd_addr = bda;
3828       strlcpy((char*)sec_event.key_notif.bd_name, bta_dm_get_remname(),
3829               (BD_NAME_LEN + 1));
3830       sec_event.key_notif.passkey = p_data->key_notif;
3831       bta_dm_cb.p_sec_cback(BTA_DM_BLE_NC_REQ_EVT, &sec_event);
3832       break;
3833 
3834     case BTM_LE_SC_OOB_REQ_EVT:
3835       sec_event.ble_req.bd_addr = bda;
3836       bta_dm_cb.p_sec_cback(BTA_DM_BLE_SC_OOB_REQ_EVT, &sec_event);
3837       break;
3838 
3839     case BTM_LE_SC_LOC_OOB_EVT:
3840       tBTA_DM_LOC_OOB_DATA local_oob_data;
3841       local_oob_data.local_oob_c = p_data->local_oob_data.commitment;
3842       local_oob_data.local_oob_r = p_data->local_oob_data.randomizer;
3843       sec_event.local_oob_data = local_oob_data;
3844       bta_dm_cb.p_sec_cback(BTA_DM_BLE_SC_CR_LOC_OOB_EVT, &sec_event);
3845       break;
3846 
3847     case BTM_LE_KEY_EVT:
3848       sec_event.ble_key.bd_addr = bda;
3849       sec_event.ble_key.key_type = p_data->key.key_type;
3850       sec_event.ble_key.p_key_value = p_data->key.p_key_value;
3851       bta_dm_cb.p_sec_cback(BTA_DM_BLE_KEY_EVT, &sec_event);
3852       break;
3853 
3854     case BTM_LE_COMPLT_EVT:
3855       sec_event.auth_cmpl.bd_addr = bda;
3856       BTM_ReadDevInfo(bda, &sec_event.auth_cmpl.dev_type,
3857                       &sec_event.auth_cmpl.addr_type);
3858       p_name = BTM_SecReadDevName(bda);
3859       if (p_name != NULL)
3860         strlcpy((char*)sec_event.auth_cmpl.bd_name, p_name, (BD_NAME_LEN + 1));
3861       else
3862         sec_event.auth_cmpl.bd_name[0] = 0;
3863 
3864       if (p_data->complt.reason != HCI_SUCCESS) {
3865         // TODO This is not a proper use of this type
3866         sec_event.auth_cmpl.fail_reason =
3867             static_cast<tHCI_STATUS>(BTA_DM_AUTH_CONVERT_SMP_CODE(
3868                 (static_cast<uint8_t>(p_data->complt.reason))));
3869 
3870         if (btm_sec_is_a_bonded_dev(bda) &&
3871             p_data->complt.reason == SMP_CONN_TOUT &&
3872             !p_data->complt.smp_over_br) {
3873           // Bonded device failed to encrypt - to test this remove battery from
3874           // HID device right after connection, but before encryption is
3875           // established
3876           LOG(INFO) << __func__
3877                     << ": bonded device disconnected when encrypting - no "
3878                        "reason to unbond";
3879         } else {
3880           /* delete this device entry from Sec Dev DB */
3881           bta_dm_remove_sec_dev_entry(bda);
3882         }
3883 
3884       } else {
3885         sec_event.auth_cmpl.success = true;
3886         if (!p_data->complt.smp_over_br)
3887           GATT_ConfigServiceChangeCCC(bda, true, BT_TRANSPORT_LE);
3888       }
3889 
3890       if (bta_dm_cb.p_sec_cback) {
3891         // bta_dm_cb.p_sec_cback(BTA_DM_AUTH_CMPL_EVT, &sec_event);
3892         bta_dm_cb.p_sec_cback(BTA_DM_BLE_AUTH_CMPL_EVT, &sec_event);
3893       }
3894       break;
3895 
3896     case BTM_LE_ADDR_ASSOC_EVT:
3897       sec_event.proc_id_addr.pairing_bda = bda;
3898       sec_event.proc_id_addr.id_addr = p_data->id_addr;
3899       bta_dm_cb.p_sec_cback(BTA_DM_LE_ADDR_ASSOC_EVT, &sec_event);
3900       break;
3901 
3902     default:
3903       status = BTM_NOT_AUTHORIZED;
3904       break;
3905   }
3906   return status;
3907 }
3908 
3909 /*******************************************************************************
3910  *
3911  * Function         bta_dm_ble_id_key_cback
3912  *
3913  * Description      Callback for BLE local ID keys
3914  *
3915  *
3916  * Returns          void
3917  *
3918  ******************************************************************************/
bta_dm_ble_id_key_cback(uint8_t key_type,tBTM_BLE_LOCAL_KEYS * p_key)3919 static void bta_dm_ble_id_key_cback(uint8_t key_type,
3920                                     tBTM_BLE_LOCAL_KEYS* p_key) {
3921   switch (key_type) {
3922     case BTM_BLE_KEY_TYPE_ID:
3923     case BTM_BLE_KEY_TYPE_ER:
3924       if (bta_dm_cb.p_sec_cback) {
3925         tBTA_DM_SEC dm_key = {
3926             .ble_id_keys = {},
3927         };
3928         memcpy(&dm_key.ble_id_keys, p_key, sizeof(tBTM_BLE_LOCAL_KEYS));
3929 
3930         tBTA_DM_SEC_EVT evt = (key_type == BTM_BLE_KEY_TYPE_ID)
3931                                   ? BTA_DM_BLE_LOCAL_IR_EVT
3932                                   : BTA_DM_BLE_LOCAL_ER_EVT;
3933         bta_dm_cb.p_sec_cback(evt, &dm_key);
3934       }
3935       break;
3936 
3937     default:
3938       APPL_TRACE_DEBUG("Unknown key type %d", key_type);
3939       break;
3940   }
3941   return;
3942 }
3943 
3944 /*******************************************************************************
3945  *
3946  * Function         bta_dm_add_blekey
3947  *
3948  * Description      This function adds an BLE Key to an security database entry.
3949  *                  This function shall only be called AFTER BTA_DmAddBleDevice
3950  *                  has been called.
3951  *                  It is normally called during host startup to restore all
3952  *                  required information stored in the NVRAM.
3953  *
3954  * Parameters:
3955  *
3956  ******************************************************************************/
bta_dm_add_blekey(const RawAddress & bd_addr,tBTA_LE_KEY_VALUE blekey,tBTM_LE_KEY_TYPE key_type)3957 void bta_dm_add_blekey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE blekey,
3958                        tBTM_LE_KEY_TYPE key_type) {
3959   BTM_SecAddBleKey(bd_addr, (tBTM_LE_KEY_VALUE*)&blekey, key_type);
3960 }
3961 
3962 /*******************************************************************************
3963  *
3964  * Function         bta_dm_add_ble_device
3965  *
3966  * Description      This function adds an BLE device to an security database
3967  *                  entry.
3968  *                  It is normally called during host startup to restore all
3969  *                  required information stored in the NVRAM.
3970  *
3971  * Parameters:
3972  *
3973  ******************************************************************************/
bta_dm_add_ble_device(const RawAddress & bd_addr,tBLE_ADDR_TYPE addr_type,tBT_DEVICE_TYPE dev_type)3974 void bta_dm_add_ble_device(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type,
3975                            tBT_DEVICE_TYPE dev_type) {
3976   BTM_SecAddBleDevice(bd_addr, dev_type, addr_type);
3977 }
3978 
3979 /*******************************************************************************
3980  *
3981  * Function         bta_dm_add_ble_device
3982  *
3983  * Description      This function adds an BLE device to an security database
3984  *                  entry.
3985  *                  It is normally called during host startup to restore all
3986  *                  required information stored in the NVRAM.
3987  *
3988  * Parameters:
3989  *
3990  ******************************************************************************/
bta_dm_ble_passkey_reply(const RawAddress & bd_addr,bool accept,uint32_t passkey)3991 void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept,
3992                               uint32_t passkey) {
3993   BTM_BlePasskeyReply(bd_addr, accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED,
3994                       passkey);
3995 }
3996 
3997 /** This is response to SM numeric comparison request submitted to application.
3998  */
bta_dm_ble_confirm_reply(const RawAddress & bd_addr,bool accept)3999 void bta_dm_ble_confirm_reply(const RawAddress& bd_addr, bool accept) {
4000   BTM_BleConfirmReply(bd_addr, accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED);
4001 }
4002 
4003 /** This function set the preferred connection parameters */
bta_dm_ble_set_conn_params(const RawAddress & bd_addr,uint16_t conn_int_min,uint16_t conn_int_max,uint16_t peripheral_latency,uint16_t supervision_tout)4004 void bta_dm_ble_set_conn_params(const RawAddress& bd_addr,
4005                                 uint16_t conn_int_min, uint16_t conn_int_max,
4006                                 uint16_t peripheral_latency,
4007                                 uint16_t supervision_tout) {
4008   L2CA_AdjustConnectionIntervals(&conn_int_min, &conn_int_max,
4009                                  BTM_BLE_CONN_INT_MIN);
4010 
4011   BTM_BleSetPrefConnParams(bd_addr, conn_int_min, conn_int_max,
4012                            peripheral_latency, supervision_tout);
4013 }
4014 
4015 /** This function update LE connection parameters */
bta_dm_ble_update_conn_params(const RawAddress & bd_addr,uint16_t min_int,uint16_t max_int,uint16_t latency,uint16_t timeout,uint16_t min_ce_len,uint16_t max_ce_len)4016 void bta_dm_ble_update_conn_params(const RawAddress& bd_addr, uint16_t min_int,
4017                                    uint16_t max_int, uint16_t latency,
4018                                    uint16_t timeout, uint16_t min_ce_len,
4019                                    uint16_t max_ce_len) {
4020   L2CA_AdjustConnectionIntervals(&min_int, &max_int, BTM_BLE_CONN_INT_MIN);
4021 
4022   if (!L2CA_UpdateBleConnParams(bd_addr, min_int, max_int, latency, timeout,
4023                                 min_ce_len, max_ce_len)) {
4024     APPL_TRACE_ERROR("Update connection parameters failed!");
4025   }
4026 }
4027 
4028 /** This function set the local device LE privacy settings. */
bta_dm_ble_config_local_privacy(bool privacy_enable)4029 void bta_dm_ble_config_local_privacy(bool privacy_enable) {
4030   BTM_BleConfigPrivacy(privacy_enable);
4031 }
4032 
bta_dm_start_scan(uint8_t duration_sec,bool low_latency_scan=false)4033 static void bta_dm_start_scan(uint8_t duration_sec,
4034                               bool low_latency_scan = false) {
4035   tBTM_STATUS status =
4036       BTM_BleObserve(true, duration_sec, bta_dm_observe_results_cb,
4037                      bta_dm_observe_cmpl_cb, low_latency_scan);
4038 
4039   if (status != BTM_CMD_STARTED) {
4040     tBTA_DM_SEARCH data = {
4041         .inq_cmpl =
4042             {
4043                 .num_resps = 0,
4044             },
4045     };
4046     APPL_TRACE_WARNING(" %s BTM_BleObserve  failed. status %d", __func__,
4047                        status);
4048     if (bta_dm_search_cb.p_scan_cback) {
4049       bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
4050     }
4051     if (bta_dm_search_cb.p_csis_scan_cback) {
4052       bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
4053     }
4054   }
4055 }
4056 
bta_dm_ble_observe(bool start,uint8_t duration,tBTA_DM_SEARCH_CBACK * p_cback)4057 void bta_dm_ble_observe(bool start, uint8_t duration,
4058                         tBTA_DM_SEARCH_CBACK* p_cback) {
4059   if (!start) {
4060     bta_dm_search_cb.p_scan_cback = NULL;
4061     BTM_BleObserve(false, 0, NULL, NULL);
4062     return;
4063   }
4064 
4065   /*Save the  callback to be called when a scan results are available */
4066   bta_dm_search_cb.p_scan_cback = p_cback;
4067   bta_dm_start_scan(duration);
4068 }
4069 
bta_dm_ble_scan(bool start,uint8_t duration_sec,bool low_latency_scan=false)4070 void bta_dm_ble_scan(bool start, uint8_t duration_sec,
4071                      bool low_latency_scan = false) {
4072   /* Start or stop only if there is no active main scanner */
4073   if (bta_dm_search_cb.p_scan_cback != NULL) return;
4074 
4075   if (!start) {
4076     BTM_BleObserve(false, 0, NULL, NULL);
4077     return;
4078   }
4079 
4080   bta_dm_start_scan(duration_sec, low_latency_scan);
4081 }
4082 
bta_dm_ble_csis_observe(bool observe,tBTA_DM_SEARCH_CBACK * p_cback)4083 void bta_dm_ble_csis_observe(bool observe, tBTA_DM_SEARCH_CBACK* p_cback) {
4084   if (!observe) {
4085     bta_dm_search_cb.p_csis_scan_cback = NULL;
4086     BTM_BleOpportunisticObserve(false, NULL);
4087     return;
4088   }
4089 
4090   /* Save the callback to be called when a scan results are available */
4091   bta_dm_search_cb.p_csis_scan_cback = p_cback;
4092   BTM_BleOpportunisticObserve(true, bta_dm_opportunistic_observe_results_cb);
4093 }
4094 
4095 /** This function set the maximum transmission packet size */
bta_dm_ble_set_data_length(const RawAddress & bd_addr)4096 void bta_dm_ble_set_data_length(const RawAddress& bd_addr) {
4097   const controller_t* controller = controller_get_interface();
4098   uint16_t max_len = controller->get_ble_maximum_tx_data_length();
4099 
4100   if (BTM_SetBleDataLength(bd_addr, max_len) != BTM_SUCCESS) {
4101     LOG_INFO("Unable to set ble data length:%hu", max_len);
4102   }
4103 }
4104 
4105 /*******************************************************************************
4106  *
4107  * Function         bta_ble_enable_scan_cmpl
4108  *
4109  * Description      ADV payload filtering enable / disable complete callback
4110  *
4111  *
4112  * Returns          None
4113  *
4114  ******************************************************************************/
bta_ble_energy_info_cmpl(tBTM_BLE_TX_TIME_MS tx_time,tBTM_BLE_RX_TIME_MS rx_time,tBTM_BLE_IDLE_TIME_MS idle_time,tBTM_BLE_ENERGY_USED energy_used,tHCI_STATUS status)4115 static void bta_ble_energy_info_cmpl(tBTM_BLE_TX_TIME_MS tx_time,
4116                                      tBTM_BLE_RX_TIME_MS rx_time,
4117                                      tBTM_BLE_IDLE_TIME_MS idle_time,
4118                                      tBTM_BLE_ENERGY_USED energy_used,
4119                                      tHCI_STATUS status) {
4120   tBTA_STATUS st = (status == HCI_SUCCESS) ? BTA_SUCCESS : BTA_FAILURE;
4121   tBTM_CONTRL_STATE ctrl_state = BTM_CONTRL_UNKNOWN;
4122 
4123   if (BTA_SUCCESS == st) ctrl_state = bta_dm_pm_obtain_controller_state();
4124 
4125   if (bta_dm_cb.p_energy_info_cback)
4126     bta_dm_cb.p_energy_info_cback(tx_time, rx_time, idle_time, energy_used,
4127                                   ctrl_state, st);
4128 }
4129 
4130 /** This function obtains the energy info */
bta_dm_ble_get_energy_info(tBTA_BLE_ENERGY_INFO_CBACK * p_energy_info_cback)4131 void bta_dm_ble_get_energy_info(
4132     tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) {
4133   bta_dm_cb.p_energy_info_cback = p_energy_info_cback;
4134   tBTM_STATUS btm_status = BTM_BleGetEnergyInfo(bta_ble_energy_info_cmpl);
4135   if (btm_status != BTM_CMD_STARTED)
4136     bta_ble_energy_info_cmpl(0, 0, 0, 0, HCI_ERR_UNSPECIFIED);
4137 }
4138 
4139 #ifndef BTA_DM_GATT_CLOSE_DELAY_TOUT
4140 #define BTA_DM_GATT_CLOSE_DELAY_TOUT 1000
4141 #endif
4142 
4143 /*******************************************************************************
4144  *
4145  * Function         bta_dm_gattc_register
4146  *
4147  * Description      Register with GATTC in DM if BLE is needed.
4148  *
4149  *
4150  * Returns          void
4151  *
4152  ******************************************************************************/
bta_dm_gattc_register(void)4153 static void bta_dm_gattc_register(void) {
4154   if (bta_dm_search_cb.client_if == BTA_GATTS_INVALID_IF) {
4155     BTA_GATTC_AppRegister(bta_dm_gattc_callback,
4156                           base::Bind([](uint8_t client_id, uint8_t status) {
4157                             if (status == GATT_SUCCESS)
4158                               bta_dm_search_cb.client_if = client_id;
4159                             else
4160                               bta_dm_search_cb.client_if = BTA_GATTS_INVALID_IF;
4161 
4162                           }), false);
4163   }
4164 }
4165 
4166 /*******************************************************************************
4167  *
4168  * Function         bta_dm_gatt_disc_complete
4169  *
4170  * Description      This function process the GATT service search complete.
4171  *
4172  * Parameters:
4173  *
4174  ******************************************************************************/
bta_dm_gatt_disc_complete(uint16_t conn_id,tGATT_STATUS status)4175 static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) {
4176   APPL_TRACE_DEBUG("%s conn_id = %d", __func__, conn_id);
4177 
4178   tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG));
4179 
4180   /* no more services to be discovered */
4181   p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT;
4182   p_msg->disc_result.result.disc_res.result =
4183       (status == GATT_SUCCESS) ? BTA_SUCCESS : BTA_FAILURE;
4184   APPL_TRACE_DEBUG("%s service found: 0x%08x", __func__,
4185                    bta_dm_search_cb.services_found);
4186   p_msg->disc_result.result.disc_res.services = bta_dm_search_cb.services_found;
4187   p_msg->disc_result.result.disc_res.num_uuids = 0;
4188   p_msg->disc_result.result.disc_res.p_uuid_list = NULL;
4189   p_msg->disc_result.result.disc_res.bd_addr = bta_dm_search_cb.peer_bdaddr;
4190   strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name,
4191           bta_dm_get_remname(), BD_NAME_LEN + 1);
4192 
4193   p_msg->disc_result.result.disc_res.device_type |= BT_DEVICE_TYPE_BLE;
4194 
4195   bta_sys_sendmsg(p_msg);
4196 
4197   if (conn_id != GATT_INVALID_CONN_ID) {
4198     bta_dm_search_cb.pending_close_bda = bta_dm_search_cb.peer_bdaddr;
4199     // Gatt will be close immediately if bluetooth.gatt.delay_close.enabled is
4200     // set to false. If property is true / unset there will be a delay
4201     if (bta_dm_search_cb.gatt_close_timer != nullptr) {
4202       /* start a GATT channel close delay timer */
4203       bta_sys_start_timer(bta_dm_search_cb.gatt_close_timer,
4204                           BTA_DM_GATT_CLOSE_DELAY_TOUT,
4205                           BTA_DM_DISC_CLOSE_TOUT_EVT, 0);
4206     } else {
4207       p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG));
4208       p_msg->hdr.event = BTA_DM_DISC_CLOSE_TOUT_EVT;
4209       p_msg->hdr.layer_specific = 0;
4210       bta_sys_sendmsg(p_msg);
4211     }
4212   } else {
4213     if (bluetooth::common::init_flags::
4214             bta_dm_clear_conn_id_on_client_close_is_enabled()) {
4215       bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
4216     }
4217   }
4218 }
4219 
4220 /*******************************************************************************
4221  *
4222  * Function         bta_dm_close_gatt_conn
4223  *
4224  * Description      This function close the GATT connection after delay
4225  *timeout.
4226  *
4227  * Parameters:
4228  *
4229  ******************************************************************************/
bta_dm_close_gatt_conn(UNUSED_ATTR tBTA_DM_MSG * p_data)4230 void bta_dm_close_gatt_conn(UNUSED_ATTR tBTA_DM_MSG* p_data) {
4231   if (bta_dm_search_cb.conn_id != GATT_INVALID_CONN_ID)
4232     BTA_GATTC_Close(bta_dm_search_cb.conn_id);
4233 
4234   bta_dm_search_cb.pending_close_bda = RawAddress::kEmpty;
4235   bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
4236 }
4237 /*******************************************************************************
4238  *
4239  * Function         btm_dm_start_gatt_discovery
4240  *
4241  * Description      This is GATT initiate the service search by open a GATT
4242  *                  connection first.
4243  *
4244  * Parameters:
4245  *
4246  ******************************************************************************/
btm_dm_start_gatt_discovery(const RawAddress & bd_addr)4247 void btm_dm_start_gatt_discovery(const RawAddress& bd_addr) {
4248   bta_dm_search_cb.gatt_disc_active = true;
4249 
4250   /* connection is already open */
4251   if (bta_dm_search_cb.pending_close_bda == bd_addr &&
4252       bta_dm_search_cb.conn_id != GATT_INVALID_CONN_ID) {
4253     bta_dm_search_cb.pending_close_bda = RawAddress::kEmpty;
4254     alarm_cancel(bta_dm_search_cb.gatt_close_timer);
4255     BTA_GATTC_ServiceSearchRequest(bta_dm_search_cb.conn_id, nullptr);
4256   } else {
4257     if (BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
4258       BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr,
4259                      BTM_BLE_DIRECT_CONNECTION, true);
4260     } else {
4261       BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr,
4262                      BTM_BLE_DIRECT_CONNECTION, false);
4263     }
4264   }
4265 }
4266 
4267 /*******************************************************************************
4268  *
4269  * Function         bta_dm_proc_open_evt
4270  *
4271  * Description      process BTA_GATTC_OPEN_EVT in DM.
4272  *
4273  * Parameters:
4274  *
4275  ******************************************************************************/
bta_dm_proc_open_evt(tBTA_GATTC_OPEN * p_data)4276 void bta_dm_proc_open_evt(tBTA_GATTC_OPEN* p_data) {
4277   VLOG(1) << "DM Search state= " << bta_dm_search_get_state()
4278           << " search_cb.peer_dbaddr:" << bta_dm_search_cb.peer_bdaddr
4279           << " connected_bda=" << p_data->remote_bda.address;
4280 
4281   APPL_TRACE_DEBUG("BTA_GATTC_OPEN_EVT conn_id = %d client_if=%d status = %d",
4282                    p_data->conn_id, p_data->client_if, p_data->status);
4283 
4284   bta_dm_search_cb.conn_id = p_data->conn_id;
4285 
4286   if (p_data->status == GATT_SUCCESS) {
4287     BTA_GATTC_ServiceSearchRequest(p_data->conn_id, nullptr);
4288   } else {
4289     bta_dm_gatt_disc_complete(GATT_INVALID_CONN_ID, p_data->status);
4290   }
4291 }
4292 
4293 /*******************************************************************************
4294  *
4295  * Function         bta_dm_clear_event_filter
4296  *
4297  * Description      clears out the event filter.
4298  *
4299  * Parameters:
4300  *
4301  ******************************************************************************/
bta_dm_clear_event_filter(void)4302 void bta_dm_clear_event_filter(void) {
4303   VLOG(1) << "bta_dm_clear_event_filter in bta_dm_act";
4304   bluetooth::shim::BTM_ClearEventFilter();
4305 }
4306 
4307 /*******************************************************************************
4308  *
4309  * Function         bta_dm_clear_event_mask
4310  *
4311  * Description      Clears out the event mask in the controller.
4312  *
4313  ******************************************************************************/
bta_dm_clear_event_mask(void)4314 void bta_dm_clear_event_mask(void) {
4315   VLOG(1) << "bta_dm_clear_event_mask in bta_dm_act";
4316   bluetooth::shim::BTM_ClearEventMask();
4317 }
4318 
4319 /*******************************************************************************
4320  *
4321  * Function         bta_dm_clear_filter_accept_list
4322  *
4323  * Description      Clears out the connect list in the controller.
4324  *
4325  ******************************************************************************/
bta_dm_clear_filter_accept_list(void)4326 void bta_dm_clear_filter_accept_list(void) {
4327   VLOG(1) << "bta_dm_clear_filter_accept_list in bta_dm_act";
4328   bluetooth::shim::BTM_ClearFilterAcceptList();
4329 }
4330 
4331 /*******************************************************************************
4332  *
4333  * Function         bta_dm_disconnect_all_acls
4334  *
4335  * Description      Disconnects all ACL connections.
4336  *
4337  ******************************************************************************/
bta_dm_disconnect_all_acls(void)4338 void bta_dm_disconnect_all_acls(void) {
4339   VLOG(1) << "bta_dm_disconnect_all_acls in bta_dm_act";
4340   bluetooth::shim::BTM_DisconnectAllAcls();
4341 }
4342 
4343 /*******************************************************************************
4344  *
4345  * Function         bta_dm_le_rand
4346  *
4347  * Description      Generates a random number from the controller.
4348  *
4349  * Parameters:      |cb| Callback to receive the random number.
4350  *
4351  ******************************************************************************/
bta_dm_le_rand(LeRandCallback cb)4352 void bta_dm_le_rand(LeRandCallback cb) {
4353   VLOG(1) << "bta_dm_le_rand in bta_dm_act";
4354   bluetooth::shim::BTM_LeRand(cb);
4355 }
4356 
4357 /*******************************************************************************
4358  *
4359  * Function        BTA_DmSetEventFilterConnectionSetupAllDevices
4360  *
4361  * Description    Tell the controller to allow all devices
4362  *
4363  * Parameters
4364  *
4365  *******************************************************************************/
bta_dm_set_event_filter_connection_setup_all_devices()4366 void bta_dm_set_event_filter_connection_setup_all_devices() {
4367   // Autoplumbed
4368   bluetooth::shim::BTM_SetEventFilterConnectionSetupAllDevices();
4369 }
4370 
4371 /*******************************************************************************
4372  *
4373  * Function        BTA_DmAllowWakeByHid
4374  *
4375  * Description     Allow the device to be woken by HID devices
4376  *
4377  * Parameters      std::vector of Classic Address and LE (Address, Address Type)
4378  *
4379  *******************************************************************************/
bta_dm_allow_wake_by_hid(std::vector<RawAddress> classic_hid_devices,std::vector<std::pair<RawAddress,uint8_t>> le_hid_devices)4380 void bta_dm_allow_wake_by_hid(
4381     std::vector<RawAddress> classic_hid_devices,
4382     std::vector<std::pair<RawAddress, uint8_t>> le_hid_devices) {
4383   // If there are any entries in the classic hid list, we should also make
4384   // the adapter connectable for classic.
4385   if (classic_hid_devices.size() > 0) {
4386     BTM_SetConnectability(BTA_DM_CONN);
4387   }
4388 
4389   bluetooth::shim::BTM_AllowWakeByHid(std::move(classic_hid_devices),
4390                                       std::move(le_hid_devices));
4391 }
4392 
4393 /*******************************************************************************
4394  *
4395  * Function        BTA_DmRestoreFilterAcceptList
4396  *
4397  * Description    Floss: Restore the state of the for the filter accept list
4398  *
4399  * Parameters
4400  *
4401  *******************************************************************************/
bta_dm_restore_filter_accept_list(std::vector<std::pair<RawAddress,uint8_t>> le_devices)4402 void bta_dm_restore_filter_accept_list(
4403     std::vector<std::pair<RawAddress, uint8_t>> le_devices) {
4404   // Autoplumbed
4405   bluetooth::shim::BTM_RestoreFilterAcceptList(le_devices);
4406 }
4407 
4408 /*******************************************************************************
4409  *
4410  * Function       BTA_DmSetDefaultEventMaskExcept
4411  *
4412  * Description    Floss: Set the default event mask for Classic and LE except
4413  *                the given values (they will be disabled in the final set
4414  *                mask).
4415  *
4416  * Parameters     Bits set for event mask and le event mask that should be
4417  *                disabled in the final value.
4418  *
4419  *******************************************************************************/
bta_dm_set_default_event_mask_except(uint64_t mask,uint64_t le_mask)4420 void bta_dm_set_default_event_mask_except(uint64_t mask, uint64_t le_mask) {
4421   // Autoplumbed
4422   bluetooth::shim::BTM_SetDefaultEventMaskExcept(mask, le_mask);
4423 }
4424 
4425 /*******************************************************************************
4426  *
4427  * Function        BTA_DmSetEventFilterInquiryResultAllDevices
4428  *
4429  * Description    Floss: Set the event filter to inquiry result device all
4430  *
4431  * Parameters
4432  *
4433  *******************************************************************************/
bta_dm_set_event_filter_inquiry_result_all_devices()4434 void bta_dm_set_event_filter_inquiry_result_all_devices() {
4435   // Autoplumbed
4436   bluetooth::shim::BTM_SetEventFilterInquiryResultAllDevices();
4437 }
4438 
4439 /*******************************************************************************
4440  *
4441  * Function         bta_dm_ble_reset_id
4442  *
4443  * Description      Reset the local adapter BLE keys.
4444  *
4445  * Parameters:
4446  *
4447  ******************************************************************************/
bta_dm_ble_reset_id(void)4448 void bta_dm_ble_reset_id(void) {
4449   VLOG(1) << "bta_dm_ble_reset_id in bta_dm_act";
4450   bluetooth::shim::BTM_BleResetId();
4451 }
4452 
4453 /*******************************************************************************
4454  *
4455  * Function         bta_dm_gattc_callback
4456  *
4457  * Description      This is GATT client callback function used in DM.
4458  *
4459  * Parameters:
4460  *
4461  ******************************************************************************/
bta_dm_gattc_callback(tBTA_GATTC_EVT event,tBTA_GATTC * p_data)4462 static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) {
4463   APPL_TRACE_DEBUG("bta_dm_gattc_callback event = %d", event);
4464 
4465   switch (event) {
4466     case BTA_GATTC_OPEN_EVT:
4467       bta_dm_proc_open_evt(&p_data->open);
4468       break;
4469 
4470     case BTA_GATTC_SEARCH_RES_EVT:
4471       break;
4472 
4473     case BTA_GATTC_SEARCH_CMPL_EVT:
4474       switch (bta_dm_search_get_state()) {
4475         case BTA_DM_SEARCH_IDLE:
4476           break;
4477         case BTA_DM_SEARCH_ACTIVE:
4478         case BTA_DM_SEARCH_CANCELLING:
4479         case BTA_DM_DISCOVER_ACTIVE:
4480           bta_dm_gatt_disc_complete(p_data->search_cmpl.conn_id,
4481                                     p_data->search_cmpl.status);
4482           break;
4483       }
4484       break;
4485 
4486     case BTA_GATTC_CLOSE_EVT:
4487       LOG_INFO("BTA_GATTC_CLOSE_EVT reason = %d", p_data->close.reason);
4488 
4489       if (p_data->close.remote_bda == bta_dm_search_cb.peer_bdaddr) {
4490         if (bluetooth::common::init_flags::
4491                 bta_dm_clear_conn_id_on_client_close_is_enabled()) {
4492           bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
4493         }
4494       }
4495 
4496       switch (bta_dm_search_get_state()) {
4497         case BTA_DM_SEARCH_IDLE:
4498         case BTA_DM_SEARCH_ACTIVE:
4499           break;
4500 
4501         case BTA_DM_SEARCH_CANCELLING:
4502         case BTA_DM_DISCOVER_ACTIVE:
4503           /* in case of disconnect before search is completed */
4504           if (p_data->close.remote_bda == bta_dm_search_cb.peer_bdaddr) {
4505             bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID,
4506                                       (tGATT_STATUS)GATT_ERROR);
4507           }
4508       }
4509       break;
4510 
4511     default:
4512       break;
4513   }
4514 }
4515 
4516 #if (BLE_VND_INCLUDED == TRUE)
4517 /*******************************************************************************
4518  *
4519  * Function         bta_dm_ctrl_features_rd_cmpl_cback
4520  *
4521  * Description      callback to handle controller feature read complete
4522  *
4523  * Parameters:
4524  *
4525  ******************************************************************************/
bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result)4526 static void bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result) {
4527   APPL_TRACE_DEBUG("%s  status = %d ", __func__, result);
4528   if (result == HCI_SUCCESS) {
4529     if (bta_dm_cb.p_sec_cback)
4530       bta_dm_cb.p_sec_cback(BTA_DM_LE_FEATURES_READ, NULL);
4531   } else {
4532     APPL_TRACE_ERROR("%s Ctrl BLE feature read failed: status :%d", __func__,
4533                      result);
4534   }
4535 }
4536 #endif /* BLE_VND_INCLUDED */
4537 
4538 /*******************************************************************************
4539  *
4540  * Function         bta_dm_ble_subrate_request
4541  *
4542  * Description      This function requests BLE subrate procedure.
4543  *
4544  * Parameters:
4545  *
4546  ******************************************************************************/
bta_dm_ble_subrate_request(const RawAddress & bd_addr,uint16_t subrate_min,uint16_t subrate_max,uint16_t max_latency,uint16_t cont_num,uint16_t timeout)4547 void bta_dm_ble_subrate_request(const RawAddress& bd_addr, uint16_t subrate_min,
4548                                 uint16_t subrate_max, uint16_t max_latency,
4549                                 uint16_t cont_num, uint16_t timeout) {
4550     // Logging done in l2c_ble.cc
4551     L2CA_SubrateRequest(bd_addr, subrate_min, subrate_max, max_latency,
4552                         cont_num, timeout);
4553 }
4554 
4555 namespace bluetooth {
4556 namespace legacy {
4557 namespace testing {
allocate_device_for(const RawAddress & bd_addr,tBT_TRANSPORT transport)4558 tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr,
4559                                          tBT_TRANSPORT transport) {
4560   return ::allocate_device_for(bd_addr, transport);
4561 }
4562 
bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME * p)4563 void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p) {
4564   ::bta_dm_remname_cback(p);
4565 }
4566 
bta_dm_determine_discovery_transport(const RawAddress & bd_addr)4567 tBT_TRANSPORT bta_dm_determine_discovery_transport(const RawAddress& bd_addr) {
4568   return ::bta_dm_determine_discovery_transport(bd_addr);
4569 }
4570 
4571 }  // namespace testing
4572 }  // namespace legacy
4573 }  // namespace bluetooth
4574