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