1 /*
2  * Copyright 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "bt_bta_dm"
18 
19 #include "bta/dm/bta_dm_disc_legacy.h"
20 
21 #include <base/functional/bind.h>
22 #include <base/strings/stringprintf.h>
23 #include <bluetooth/log.h>
24 #include <com_android_bluetooth_flags.h>
25 #include <stddef.h>
26 
27 #include <cstdint>
28 #include <string>
29 #include <variant>
30 #include <vector>
31 
32 #include "bta/dm/bta_dm_disc_int_legacy.h"
33 #include "bta/include/bta_gatt_api.h"
34 #include "bta/include/bta_sdp_api.h"
35 #include "btif/include/btif_config.h"
36 #include "com_android_bluetooth_flags.h"
37 #include "common/circular_buffer.h"
38 #include "common/init_flags.h"
39 #include "common/strings.h"
40 #include "device/include/interop.h"
41 #include "internal_include/bt_target.h"
42 #include "main/shim/dumpsys.h"
43 #include "os/logging/log_adapter.h"
44 #include "osi/include/allocator.h"
45 #include "stack/btm/btm_int_types.h"  // TimestampedStringCircularBuffer
46 #include "stack/btm/neighbor_inquiry.h"
47 #include "stack/include/bt_dev_class.h"
48 #include "stack/include/bt_name.h"
49 #include "stack/include/bt_uuid16.h"
50 #include "stack/include/btm_client_interface.h"
51 #include "stack/include/btm_inq.h"
52 #include "stack/include/btm_log_history.h"
53 #include "stack/include/btm_sec_api.h"  // BTM_IsRemoteNameKnown
54 #include "stack/include/gap_api.h"      // GAP_BleReadPeerPrefConnParams
55 #include "stack/include/hidh_api.h"
56 #include "stack/include/main_thread.h"
57 #include "stack/include/sdp_status.h"
58 #include "stack/sdp/sdpint.h"  // is_sdp_pbap_pce_disabled
59 #include "storage/config_keys.h"
60 #include "types/raw_address.h"
61 
62 #ifdef TARGET_FLOSS
63 #include "stack/include/srvc_api.h"
64 #endif
65 
66 // TODO: Remove this file after flag separate_service_and_device_discovery rolls
67 // out
68 namespace bta_dm_disc_legacy {
69 
70 using ::bluetooth::Uuid;
71 using namespace ::bluetooth::legacy::stack::sdp;
72 using namespace ::bluetooth;
73 
74 tBTM_CONTRL_STATE bta_dm_pm_obtain_controller_state(void);
75 
76 namespace {
77 constexpr char kBtmLogTag[] = "SDP";
78 
79 tBTA_DM_SEARCH_CB bta_dm_search_cb;
80 }  // namespace
81 
82 static void bta_dm_search_sm_execute(tBTA_DM_EVT event,
83                                      std::unique_ptr<tBTA_DM_MSG> msg);
post_disc_evt(tBTA_DM_EVT event,std::unique_ptr<tBTA_DM_MSG> msg)84 static void post_disc_evt(tBTA_DM_EVT event, std::unique_ptr<tBTA_DM_MSG> msg) {
85   if (do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_search_sm_execute,
86                                                   event, std::move(msg))) !=
87       BT_STATUS_SUCCESS) {
88     log::error("post_disc_evt failed");
89   }
90 }
91 
92 static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status);
93 static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir,
94                                   uint16_t eir_len);
95 static void bta_dm_inq_cmpl();
96 static void bta_dm_inq_cmpl_cb(void* p_result);
97 static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr,
98                                                 DEV_CLASS dc, BD_NAME bd_name);
99 static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p);
100 static void bta_dm_find_services(const RawAddress& bd_addr);
101 static void bta_dm_discover_next_device(void);
102 static void bta_dm_sdp_callback(const RawAddress& bd_addr,
103                                 tSDP_STATUS sdp_status);
104 
105 static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr,
106                                            tBT_TRANSPORT transport);
107 static void bta_dm_discover_name(const RawAddress& remote_bd_addr);
108 static void bta_dm_discover_services(const RawAddress& remote_bd_addr);
109 
110 static void bta_dm_disable_search_and_disc(void);
111 
112 static void bta_dm_gattc_register(void);
113 static void btm_dm_start_gatt_discovery(const RawAddress& bd_addr);
114 static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data);
115 static void bta_dm_search_cmpl();
116 static void bta_dm_free_sdp_db();
117 static void bta_dm_execute_queued_request();
118 static void bta_dm_search_cancel_notify();
119 static void bta_dm_close_gatt_conn();
120 
121 TimestampedStringCircularBuffer disc_gatt_history_{50};
122 
123 namespace {
124 
125 struct gatt_interface_t {
126   void (*BTA_GATTC_CancelOpen)(tGATT_IF client_if, const RawAddress& remote_bda,
127                                bool is_direct);
128   void (*BTA_GATTC_Refresh)(const RawAddress& remote_bda);
129   void (*BTA_GATTC_GetGattDb)(uint16_t conn_id, uint16_t start_handle,
130                               uint16_t end_handle, btgatt_db_element_t** db,
131                               int* count);
132   void (*BTA_GATTC_AppRegister)(tBTA_GATTC_CBACK* p_client_cb,
133                                 BtaAppRegisterCallback cb, bool eatt_support);
134   void (*BTA_GATTC_Close)(uint16_t conn_id);
135   void (*BTA_GATTC_ServiceSearchRequest)(uint16_t conn_id,
136                                          const bluetooth::Uuid* p_srvc_uuid);
137   void (*BTA_GATTC_Open)(tGATT_IF client_if, const RawAddress& remote_bda,
138                          tBTM_BLE_CONN_TYPE connection_type,
139                          bool opportunistic);
140 } default_gatt_interface = {
141     .BTA_GATTC_CancelOpen =
__anonf50479c50302(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) 142         [](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) {
143           disc_gatt_history_.Push(base::StringPrintf(
144               "%-32s bd_addr:%s client_if:%hu is_direct:%c", "GATTC_CancelOpen",
145               ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if,
146               (is_direct) ? 'T' : 'F'));
147           BTA_GATTC_CancelOpen(client_if, remote_bda, is_direct);
148         },
149     .BTA_GATTC_Refresh =
__anonf50479c50402(const RawAddress& remote_bda) 150         [](const RawAddress& remote_bda) {
151           disc_gatt_history_.Push(
152               base::StringPrintf("%-32s bd_addr:%s", "GATTC_Refresh",
153                                  ADDRESS_TO_LOGGABLE_CSTR(remote_bda)));
154           BTA_GATTC_Refresh(remote_bda);
155         },
156     .BTA_GATTC_GetGattDb =
157         [](uint16_t conn_id, uint16_t start_handle, uint16_t end_handle,
__anonf50479c50502(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, btgatt_db_element_t** db, int* count) 158            btgatt_db_element_t** db, int* count) {
159           disc_gatt_history_.Push(base::StringPrintf(
160               "%-32s conn_id:%hu start_handle:%hu end:handle:%hu",
161               "GATTC_GetGattDb", conn_id, start_handle, end_handle));
162           BTA_GATTC_GetGattDb(conn_id, start_handle, end_handle, db, count);
163         },
164     .BTA_GATTC_AppRegister =
165         [](tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb,
__anonf50479c50602(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, bool eatt_support) 166            bool eatt_support) {
167           disc_gatt_history_.Push(
168               base::StringPrintf("%-32s eatt_support:%c", "GATTC_AppRegister",
169                                  (eatt_support) ? 'T' : 'F'));
170           BTA_GATTC_AppRegister(p_client_cb, cb, eatt_support);
171         },
172     .BTA_GATTC_Close =
__anonf50479c50702(uint16_t conn_id) 173         [](uint16_t conn_id) {
174           disc_gatt_history_.Push(
175               base::StringPrintf("%-32s conn_id:%hu", "GATTC_Close", conn_id));
176           BTA_GATTC_Close(conn_id);
177         },
178     .BTA_GATTC_ServiceSearchRequest =
__anonf50479c50802(uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) 179         [](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) {
180           disc_gatt_history_.Push(base::StringPrintf(
181               "%-32s conn_id:%hu", "GATTC_ServiceSearchRequest", conn_id));
182           if (p_srvc_uuid) {
183             BTA_GATTC_ServiceSearchRequest(conn_id, *p_srvc_uuid);
184           } else {
185             BTA_GATTC_ServiceSearchAllRequest(conn_id);
186           }
187         },
188     .BTA_GATTC_Open =
189         [](tGATT_IF client_if, const RawAddress& remote_bda,
__anonf50479c50902(tGATT_IF client_if, const RawAddress& remote_bda, tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) 190            tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) {
191           disc_gatt_history_.Push(base::StringPrintf(
192               "%-32s bd_addr:%s client_if:%hu type:0x%x opportunistic:%c",
193               "GATTC_Open", ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if,
194               connection_type, (opportunistic) ? 'T' : 'F'));
195           BTA_GATTC_Open(client_if, remote_bda, connection_type, opportunistic);
196         },
197 };
198 
199 gatt_interface_t* gatt_interface = &default_gatt_interface;
200 
get_gatt_interface()201 gatt_interface_t& get_gatt_interface() { return *gatt_interface; }
202 
203 }  // namespace
204 
bta_dm_disc_disable_search_and_disc()205 void bta_dm_disc_disable_search_and_disc() { bta_dm_disable_search_and_disc(); }
206 
bta_dm_disc_gatt_cancel_open(const RawAddress & bd_addr)207 void bta_dm_disc_gatt_cancel_open(const RawAddress& bd_addr) {
208   get_gatt_interface().BTA_GATTC_CancelOpen(0, bd_addr, false);
209 }
210 
bta_dm_disc_gatt_refresh(const RawAddress & bd_addr)211 void bta_dm_disc_gatt_refresh(const RawAddress& bd_addr) {
212   get_gatt_interface().BTA_GATTC_Refresh(bd_addr);
213 }
214 
bta_dm_disc_remove_device(const RawAddress & bd_addr)215 void bta_dm_disc_remove_device(const RawAddress& bd_addr) {
216   if (bta_dm_search_cb.state == BTA_DM_DISCOVER_ACTIVE &&
217       bta_dm_search_cb.peer_bdaddr == bd_addr) {
218     log::info(
219         "Device removed while service discovery was pending, conclude the "
220         "service disvovery");
221     bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID,
222                               (tGATT_STATUS)GATT_ERROR);
223   }
224 }
225 
bta_dm_disc_discover_next_device()226 void bta_dm_disc_discover_next_device() { bta_dm_discover_next_device(); }
227 
bta_dm_disc_gattc_register()228 void bta_dm_disc_gattc_register() { bta_dm_gattc_register(); }
229 
230 static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq,
231                                       const uint8_t* p_eir, uint16_t eir_len);
232 static void bta_dm_observe_cmpl_cb(void* p_result);
233 
234 const uint16_t bta_service_id_to_uuid_lkup_tbl[BTA_MAX_SERVICE_ID] = {
235     UUID_SERVCLASS_PNP_INFORMATION,       /* Reserved */
236     UUID_SERVCLASS_SERIAL_PORT,           /* BTA_SPP_SERVICE_ID */
237     UUID_SERVCLASS_DIALUP_NETWORKING,     /* BTA_DUN_SERVICE_ID */
238     UUID_SERVCLASS_AUDIO_SOURCE,          /* BTA_A2DP_SOURCE_SERVICE_ID */
239     UUID_SERVCLASS_LAN_ACCESS_USING_PPP,  /* BTA_LAP_SERVICE_ID */
240     UUID_SERVCLASS_HEADSET,               /* BTA_HSP_HS_SERVICE_ID */
241     UUID_SERVCLASS_HF_HANDSFREE,          /* BTA_HFP_HS_SERVICE_ID */
242     UUID_SERVCLASS_OBEX_OBJECT_PUSH,      /* BTA_OPP_SERVICE_ID */
243     UUID_SERVCLASS_OBEX_FILE_TRANSFER,    /* BTA_FTP_SERVICE_ID */
244     UUID_SERVCLASS_CORDLESS_TELEPHONY,    /* BTA_CTP_SERVICE_ID */
245     UUID_SERVCLASS_INTERCOM,              /* BTA_ICP_SERVICE_ID */
246     UUID_SERVCLASS_IRMC_SYNC,             /* BTA_SYNC_SERVICE_ID */
247     UUID_SERVCLASS_DIRECT_PRINTING,       /* BTA_BPP_SERVICE_ID */
248     UUID_SERVCLASS_IMAGING_RESPONDER,     /* BTA_BIP_SERVICE_ID */
249     UUID_SERVCLASS_PANU,                  /* BTA_PANU_SERVICE_ID */
250     UUID_SERVCLASS_NAP,                   /* BTA_NAP_SERVICE_ID */
251     UUID_SERVCLASS_GN,                    /* BTA_GN_SERVICE_ID */
252     UUID_SERVCLASS_SAP,                   /* BTA_SAP_SERVICE_ID */
253     UUID_SERVCLASS_AUDIO_SINK,            /* BTA_A2DP_SERVICE_ID */
254     UUID_SERVCLASS_AV_REMOTE_CONTROL,     /* BTA_AVRCP_SERVICE_ID */
255     UUID_SERVCLASS_HUMAN_INTERFACE,       /* BTA_HID_SERVICE_ID */
256     UUID_SERVCLASS_VIDEO_SINK,            /* BTA_VDP_SERVICE_ID */
257     UUID_SERVCLASS_PBAP_PSE,              /* BTA_PBAP_SERVICE_ID */
258     UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTA_HSP_SERVICE_ID */
259     UUID_SERVCLASS_AG_HANDSFREE,          /* BTA_HFP_SERVICE_ID */
260     UUID_SERVCLASS_MESSAGE_ACCESS,        /* BTA_MAP_SERVICE_ID */
261     UUID_SERVCLASS_MESSAGE_NOTIFICATION,  /* BTA_MN_SERVICE_ID */
262     UUID_SERVCLASS_HDP_PROFILE,           /* BTA_HDP_SERVICE_ID */
263     UUID_SERVCLASS_PBAP_PCE,              /* BTA_PCE_SERVICE_ID */
264     UUID_PROTOCOL_ATT                     /* BTA_GATT_SERVICE_ID */
265 };
266 
267 #define MAX_DISC_RAW_DATA_BUF (4096)
268 static uint8_t g_disc_raw_data_buf[MAX_DISC_RAW_DATA_BUF];
269 
bta_dm_search_set_state(tBTA_DM_STATE state)270 static void bta_dm_search_set_state(tBTA_DM_STATE state) {
271   bta_dm_search_cb.state = state;
272 }
bta_dm_search_get_state()273 static tBTA_DM_STATE bta_dm_search_get_state() {
274   return bta_dm_search_cb.state;
275 }
276 
277 /*******************************************************************************
278  *
279  * Function         bta_dm_search_start
280  *
281  * Description      Starts an inquiry
282  *
283  *
284  * Returns          void
285  *
286  ******************************************************************************/
bta_dm_search_start(tBTA_DM_API_SEARCH & search)287 static void bta_dm_search_start(tBTA_DM_API_SEARCH& search) {
288   bta_dm_gattc_register();
289 
290   if (get_btm_client_interface().db.BTM_ClearInqDb(nullptr) != BTM_SUCCESS) {
291     log::warn("Unable to clear inquiry db for device discovery");
292   }
293 
294   /* save search params */
295   bta_dm_search_cb.p_device_search_cback = search.p_cback;
296 
297   const tBTM_STATUS btm_status =
298       BTM_StartInquiry(bta_dm_inq_results_cb, bta_dm_inq_cmpl_cb);
299   switch (btm_status) {
300     case BTM_CMD_STARTED:
301       // Completion callback will be executed when controller inquiry
302       // timer pops or is cancelled by the user
303       break;
304     default:
305       log::warn("Unable to start device discovery search btm_status:{}",
306                 btm_status_text(btm_status));
307       // Not started so completion callback is executed now
308       bta_dm_inq_cmpl();
309       break;
310   }
311 }
312 
313 /*******************************************************************************
314  *
315  * Function         bta_dm_search_cancel
316  *
317  * Description      Cancels an ongoing search for devices
318  *
319  *
320  * Returns          void
321  *
322  ******************************************************************************/
bta_dm_search_cancel()323 static void bta_dm_search_cancel() {
324   if (BTM_IsInquiryActive()) {
325     BTM_CancelInquiry();
326     bta_dm_search_cancel_notify();
327     bta_dm_search_cmpl();
328   }
329   /* If no Service Search going on then issue cancel remote name in case it is
330      active */
331   else if (!bta_dm_search_cb.name_discover_done) {
332     if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() !=
333         BTM_CMD_STARTED) {
334       log::warn("Unable to cancel RNR");
335     }
336     /* bta_dm_search_cmpl is called when receiving the remote name cancel evt */
337     if (!com::android::bluetooth::flags::
338             bta_dm_defer_device_discovery_state_change_until_rnr_complete()) {
339       bta_dm_search_cmpl();
340     }
341   } else {
342     bta_dm_inq_cmpl();
343   }
344 }
345 
346 /*******************************************************************************
347  *
348  * Function         bta_dm_discover
349  *
350  * Description      Discovers services on a remote device
351  *
352  *
353  * Returns          void
354  *
355  ******************************************************************************/
bta_dm_discover(tBTA_DM_API_DISCOVER & discover)356 static void bta_dm_discover(tBTA_DM_API_DISCOVER& discover) {
357   bta_dm_gattc_register();
358 
359   bta_dm_search_cb.service_search_cbacks = discover.cbacks;
360   bta_dm_search_cb.services_to_search = BTA_ALL_SERVICE_MASK;
361   bta_dm_search_cb.service_index = 0;
362   bta_dm_search_cb.services_found = 0;
363   bta_dm_search_cb.peer_name[0] = 0;
364   bta_dm_search_cb.p_btm_inq_info =
365       get_btm_client_interface().db.BTM_InqDbRead(discover.bd_addr);
366   bta_dm_search_cb.transport = discover.transport;
367 
368   bta_dm_search_cb.name_discover_done = false;
369 
370   log::info(
371       "bta_dm_discovery: starting service discovery to {} , transport: {}",
372       discover.bd_addr, bt_transport_text(discover.transport));
373   bta_dm_discover_services(discover.bd_addr);
374 }
375 
376 /*******************************************************************************
377  *
378  * Function         bta_dm_disable_search_and_disc
379  *
380  * Description      Cancels an ongoing search or discovery for devices in case
381  *                  of a Bluetooth disable
382  *
383  * Returns          void
384  *
385  ******************************************************************************/
bta_dm_disable_search_and_disc(void)386 static void bta_dm_disable_search_and_disc(void) {
387   switch (bta_dm_search_get_state()) {
388     case BTA_DM_SEARCH_IDLE:
389       break;
390     case BTA_DM_SEARCH_ACTIVE:
391     case BTA_DM_SEARCH_CANCELLING:
392     case BTA_DM_DISCOVER_ACTIVE:
393     default:
394       log::debug(
395           "Search state machine is not idle so issuing search cancel current "
396           "state:{}",
397           bta_dm_state_text(bta_dm_search_get_state()));
398       bta_dm_search_cancel();
399   }
400 }
401 
402 /*******************************************************************************
403  *
404  * Function         bta_dm_read_remote_device_name
405  *
406  * Description      Initiate to get remote device name
407  *
408  * Returns          true if started to get remote name
409  *
410  ******************************************************************************/
bta_dm_read_remote_device_name(const RawAddress & bd_addr,tBT_TRANSPORT transport)411 static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr,
412                                            tBT_TRANSPORT transport) {
413   tBTM_STATUS btm_status;
414 
415   log::verbose("");
416 
417   bta_dm_search_cb.peer_bdaddr = bd_addr;
418   bta_dm_search_cb.peer_name[0] = 0;
419 
420   btm_status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName(
421       bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback, transport);
422 
423   if (btm_status == BTM_CMD_STARTED) {
424     log::verbose("BTM_ReadRemoteDeviceName is started");
425 
426     return (true);
427   } else if (btm_status == BTM_BUSY) {
428     log::verbose("BTM_ReadRemoteDeviceName is busy");
429 
430     /* Remote name discovery is on going now so BTM cannot notify through
431      * "bta_dm_remname_cback" */
432     /* adding callback to get notified that current reading remote name done */
433 
434     get_btm_client_interface().security.BTM_SecAddRmtNameNotifyCallback(
435         &bta_dm_service_search_remname_cback);
436 
437     return (true);
438   } else {
439     log::warn("BTM_ReadRemoteDeviceName returns 0x{:02X}", btm_status);
440 
441     return (false);
442   }
443 }
444 
445 /*******************************************************************************
446  *
447  * Function         bta_dm_inq_cmpl
448  *
449  * Description      Process the inquiry complete event from BTM
450  *
451  * Returns          void
452  *
453  ******************************************************************************/
bta_dm_inq_cmpl()454 static void bta_dm_inq_cmpl() {
455   if (bta_dm_search_get_state() == BTA_DM_SEARCH_CANCELLING) {
456     bta_dm_search_set_state(BTA_DM_SEARCH_IDLE);
457     bta_dm_execute_queued_request();
458     return;
459   }
460 
461   if (bta_dm_search_get_state() != BTA_DM_SEARCH_ACTIVE) {
462     return;
463   }
464 
465   log::verbose("bta_dm_inq_cmpl");
466 
467   bta_dm_search_cb.p_btm_inq_info =
468       get_btm_client_interface().db.BTM_InqDbFirst();
469   if (bta_dm_search_cb.p_btm_inq_info != NULL) {
470     /* start name discovery from the first device on inquiry result
471      */
472     bta_dm_search_cb.name_discover_done = false;
473     bta_dm_search_cb.peer_name[0] = 0;
474     bta_dm_discover_name(
475         bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr);
476   } else {
477     bta_dm_search_cmpl();
478   }
479 }
480 
bta_dm_remote_name_cmpl(const tBTA_DM_REMOTE_NAME & remote_name_msg)481 static void bta_dm_remote_name_cmpl(
482     const tBTA_DM_REMOTE_NAME& remote_name_msg) {
483   BTM_LogHistory(kBtmLogTag, remote_name_msg.bd_addr, "Remote name completed",
484                  base::StringPrintf(
485                      "status:%s state:%s name:\"%s\"",
486                      hci_status_code_text(remote_name_msg.hci_status).c_str(),
487                      bta_dm_state_text(bta_dm_search_get_state()).c_str(),
488                      PRIVATE_NAME(remote_name_msg.bd_name)));
489 
490   tBTM_INQ_INFO* p_btm_inq_info =
491       get_btm_client_interface().db.BTM_InqDbRead(remote_name_msg.bd_addr);
492   if (!bd_name_is_empty(remote_name_msg.bd_name) && p_btm_inq_info) {
493     p_btm_inq_info->appl_knows_rem_name = true;
494   }
495 
496   // Callback with this property
497   if (bta_dm_search_cb.p_device_search_cback != nullptr ||
498       bta_dm_search_cb.service_search_cbacks.on_name_read != nullptr) {
499     // Both device and service search callbacks end up sending event to java.
500     // It's enough to send callback to just one of them.
501     if (bta_dm_search_cb.p_device_search_cback != nullptr) {
502       tBTA_DM_SEARCH search_data = {
503           .name_res = {.bd_addr = remote_name_msg.bd_addr, .bd_name = {}},
504       };
505       if (remote_name_msg.hci_status == HCI_SUCCESS) {
506         bd_name_copy(search_data.name_res.bd_name, remote_name_msg.bd_name);
507       }
508       bta_dm_search_cb.p_device_search_cback(BTA_DM_NAME_READ_EVT,
509                                              &search_data);
510     } else if (bta_dm_search_cb.service_search_cbacks.on_name_read != nullptr) {
511       bta_dm_search_cb.service_search_cbacks.on_name_read(
512           remote_name_msg.bd_addr, remote_name_msg.hci_status,
513           remote_name_msg.bd_name);
514     }
515   } else {
516     log::warn("Received remote name complete without callback");
517   }
518 
519   switch (bta_dm_search_get_state()) {
520     case BTA_DM_SEARCH_ACTIVE:
521       bta_dm_discover_name(bta_dm_search_cb.peer_bdaddr);
522       break;
523     case BTA_DM_DISCOVER_ACTIVE:
524       /* TODO: Get rid of this case when Name and Service discovery state
525        * machines are separated */
526       bta_dm_discover_name(remote_name_msg.bd_addr);
527       break;
528     case BTA_DM_SEARCH_IDLE:
529     case BTA_DM_SEARCH_CANCELLING:
530       log::warn("Received remote name request in state:{}",
531                 bta_dm_state_text(bta_dm_search_get_state()));
532       break;
533   }
534 }
535 
store_avrcp_profile_feature(tSDP_DISC_REC * sdp_rec)536 static void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) {
537   tSDP_DISC_ATTR* p_attr =
538       get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
539           sdp_rec, ATTR_ID_SUPPORTED_FEATURES);
540   if (p_attr == NULL) {
541     return;
542   }
543 
544   uint16_t avrcp_features = p_attr->attr_value.v.u16;
545   if (avrcp_features == 0) {
546     return;
547   }
548 
549   if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(),
550                           BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES,
551                           (const uint8_t*)&avrcp_features,
552                           sizeof(avrcp_features))) {
553     log::info("Saving avrcp_features: 0x{:x}", avrcp_features);
554   } else {
555     log::info("Failed to store avrcp_features 0x{:x} for {}", avrcp_features,
556               sdp_rec->remote_bd_addr);
557   }
558 }
559 
bta_dm_store_audio_profiles_version()560 static void bta_dm_store_audio_profiles_version() {
561   struct AudioProfile {
562     const uint16_t servclass_uuid;
563     const uint16_t btprofile_uuid;
564     const char* profile_key;
565     void (*store_audio_profile_feature)(tSDP_DISC_REC*);
566   };
567 
568   std::array<AudioProfile, 1> audio_profiles = {{
569       {
570           .servclass_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL,
571           .btprofile_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL,
572           .profile_key = BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION,
573           .store_audio_profile_feature = store_avrcp_profile_feature,
574       },
575   }};
576 
577   for (const auto& audio_profile : audio_profiles) {
578     tSDP_DISC_REC* sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
579         bta_dm_search_cb.p_sdp_db, audio_profile.servclass_uuid, NULL);
580     if (sdp_rec == NULL) continue;
581 
582     if (get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
583             sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST) == NULL)
584       continue;
585 
586     uint16_t profile_version = 0;
587     /* get profile version (if failure, version parameter is not updated) */
588     if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(
589             sdp_rec, audio_profile.btprofile_uuid, &profile_version)) {
590       log::warn("Unable to find SDP profile version in record peer:{}",
591                 sdp_rec->remote_bd_addr);
592     }
593     if (profile_version != 0) {
594       if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(),
595                               audio_profile.profile_key,
596                               (const uint8_t*)&profile_version,
597                               sizeof(profile_version))) {
598       } else {
599         log::info("Failed to store peer profile version for {}",
600                   sdp_rec->remote_bd_addr);
601       }
602     }
603     audio_profile.store_audio_profile_feature(sdp_rec);
604   }
605 }
606 
607 /*******************************************************************************
608  *
609  * Function         bta_dm_sdp_result
610  *
611  * Description      Process the discovery result from sdp
612  *
613  * Returns          void
614  *
615  ******************************************************************************/
bta_dm_sdp_result(tBTA_DM_SDP_RESULT & sdp_event)616 static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) {
617   tSDP_DISC_REC* p_sdp_rec = NULL;
618   bool scn_found = false;
619   uint16_t service = 0xFFFF;
620   tSDP_PROTOCOL_ELEM pe;
621 
622   std::vector<Uuid> uuid_list;
623 
624   const tSDP_RESULT sdp_result = sdp_event.sdp_result;
625 
626   if ((sdp_event.sdp_result == SDP_SUCCESS) ||
627       (sdp_event.sdp_result == SDP_NO_RECS_MATCH) ||
628       (sdp_event.sdp_result == SDP_DB_FULL)) {
629     log::verbose("sdp_result::0x{:x}", sdp_event.sdp_result);
630     do {
631       p_sdp_rec = NULL;
632       if (bta_dm_search_cb.service_index == (BTA_USER_SERVICE_ID + 1)) {
633         if (p_sdp_rec &&
634             get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(
635                 p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) {
636           bta_dm_search_cb.peer_scn = (uint8_t)pe.params[0];
637           scn_found = true;
638         }
639       } else {
640         service =
641             bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - 1];
642         p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
643             bta_dm_search_cb.p_sdp_db, service, p_sdp_rec);
644       }
645       /* finished with BR/EDR services, now we check the result for GATT based
646        * service UUID */
647       if (bta_dm_search_cb.service_index == BTA_MAX_SERVICE_ID) {
648         /* all GATT based services */
649 
650         std::vector<Uuid> gatt_uuids;
651 
652         do {
653           /* find a service record, report it */
654           p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
655               bta_dm_search_cb.p_sdp_db, 0, p_sdp_rec);
656           if (p_sdp_rec) {
657             Uuid service_uuid;
658             if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec(
659                     p_sdp_rec, &service_uuid)) {
660               gatt_uuids.push_back(service_uuid);
661             }
662           }
663         } while (p_sdp_rec);
664 
665         if (!gatt_uuids.empty()) {
666           log::info("GATT services discovered using SDP");
667 
668           // send all result back to app
669           BD_NAME bd_name;
670           bd_name_from_char_pointer(bd_name, bta_dm_get_remname());
671 
672           bta_dm_search_cb.service_search_cbacks.on_gatt_results(
673               bta_dm_search_cb.peer_bdaddr, bd_name, gatt_uuids,
674               /* transport_le */ false);
675         }
676       } else {
677         if ((p_sdp_rec != NULL)) {
678           if (service != UUID_SERVCLASS_PNP_INFORMATION) {
679             bta_dm_search_cb.services_found |=
680                 (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(
681                     bta_dm_search_cb.service_index - 1));
682             uint16_t tmp_svc =
683                 bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index -
684                                                 1];
685             /* Add to the list of UUIDs */
686             uuid_list.push_back(Uuid::From16Bit(tmp_svc));
687           }
688         }
689       }
690 
691       if (bta_dm_search_cb.services_to_search == 0) {
692         bta_dm_search_cb.service_index++;
693       } else /* regular one service per search or PNP search */
694         break;
695 
696     } while (bta_dm_search_cb.service_index <= BTA_MAX_SERVICE_ID);
697 
698     log::verbose("services_found = {:04x}", bta_dm_search_cb.services_found);
699 
700     /* Collect the 128-bit services here and put them into the list */
701     p_sdp_rec = NULL;
702     do {
703       /* find a service record, report it */
704       p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit(
705           bta_dm_search_cb.p_sdp_db, p_sdp_rec);
706       if (p_sdp_rec) {
707         // SDP_FindServiceUUIDInRec_128bit is used only once, refactor?
708         Uuid temp_uuid;
709         if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit(
710                 p_sdp_rec, &temp_uuid)) {
711           uuid_list.push_back(temp_uuid);
712         }
713       }
714     } while (p_sdp_rec);
715 
716     if (bluetooth::common::init_flags::
717             dynamic_avrcp_version_enhancement_is_enabled() &&
718         bta_dm_search_cb.services_to_search == 0) {
719       bta_dm_store_audio_profiles_version();
720     }
721 
722 #if TARGET_FLOSS
723     tSDP_DI_GET_RECORD di_record;
724     if (get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord(
725             1, &di_record, bta_dm_search_cb.p_sdp_db) == SDP_SUCCESS) {
726       bta_dm_search_cb.service_search_cbacks.on_did_received(
727           bta_dm_search_cb.peer_bdaddr, di_record.rec.vendor_id_source,
728           di_record.rec.vendor, di_record.rec.product, di_record.rec.version);
729     }
730 #endif
731 
732     /* if there are more services to search for */
733     if (bta_dm_search_cb.services_to_search) {
734       /* Free up the p_sdp_db before checking the next one */
735       bta_dm_free_sdp_db();
736       bta_dm_find_services(bta_dm_search_cb.peer_bdaddr);
737     } else {
738       /* callbacks */
739       /* start next bd_addr if necessary */
740 
741       get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback(
742           &bta_dm_service_search_remname_cback);
743 
744       BTM_LogHistory(
745           kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery completed",
746           base::StringPrintf("Result:%s services_found:0x%x service_index:0x%d",
747                              sdp_result_text(sdp_result).c_str(),
748                              bta_dm_search_cb.services_found,
749                              bta_dm_search_cb.service_index));
750 
751       auto msg = std::make_unique<tBTA_DM_MSG>(tBTA_DM_SVC_RES{});
752       auto& disc_result = std::get<tBTA_DM_SVC_RES>(*msg);
753 
754       disc_result.result = BTA_SUCCESS;
755       disc_result.uuids = std::move(uuid_list);
756       // Copy the raw_data to the discovery result structure
757       if (bta_dm_search_cb.p_sdp_db != NULL &&
758           bta_dm_search_cb.p_sdp_db->raw_used != 0 &&
759           bta_dm_search_cb.p_sdp_db->raw_data != NULL) {
760         log::verbose("raw_data used = 0x{:x} raw_data_ptr = 0x{}",
761                      bta_dm_search_cb.p_sdp_db->raw_used,
762                      fmt::ptr(bta_dm_search_cb.p_sdp_db->raw_data));
763 
764         bta_dm_search_cb.p_sdp_db->raw_data =
765             NULL;  // no need to free this - it is a global assigned.
766         bta_dm_search_cb.p_sdp_db->raw_used = 0;
767         bta_dm_search_cb.p_sdp_db->raw_size = 0;
768       } else {
769         log::verbose("raw data size is 0 or raw_data is null!!");
770       }
771       /* Done with p_sdp_db. Free it */
772       bta_dm_free_sdp_db();
773       disc_result.services = bta_dm_search_cb.services_found;
774 
775       // Piggy back the SCN over result field
776       if (scn_found) {
777         disc_result.result =
778             static_cast<tBTA_STATUS>((3 + bta_dm_search_cb.peer_scn));
779         disc_result.services |= BTA_USER_SERVICE_MASK;
780 
781         log::verbose("Piggy back the SCN over result field  SCN={}",
782                      bta_dm_search_cb.peer_scn);
783       }
784       disc_result.bd_addr = bta_dm_search_cb.peer_bdaddr;
785 
786       bta_dm_search_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, std::move(msg));
787     }
788   } else {
789     BTM_LogHistory(
790         kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery failed",
791         base::StringPrintf("Result:%s", sdp_result_text(sdp_result).c_str()));
792     log::error("SDP connection failed {}", sdp_status_text(sdp_result));
793     if (sdp_event.sdp_result == SDP_CONN_FAILED)
794       bta_dm_search_cb.wait_disc = false;
795 
796     /* not able to connect go to next device */
797     if (bta_dm_search_cb.p_sdp_db)
798       osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db);
799 
800     get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback(
801         &bta_dm_service_search_remname_cback);
802 
803     auto msg = std::make_unique<tBTA_DM_MSG>(tBTA_DM_SVC_RES{});
804     auto& disc_result = std::get<tBTA_DM_SVC_RES>(*msg);
805 
806     disc_result.result = BTA_FAILURE;
807     disc_result.services = bta_dm_search_cb.services_found;
808     disc_result.bd_addr = bta_dm_search_cb.peer_bdaddr;
809 
810     bta_dm_search_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, std::move(msg));
811   }
812 }
813 
814 /** Callback of peer's DIS reply. This is only called for floss */
815 #if TARGET_FLOSS
bta_dm_read_dis_cmpl(const RawAddress & addr,tDIS_VALUE * p_dis_value)816 static void bta_dm_read_dis_cmpl(const RawAddress& addr,
817                                  tDIS_VALUE* p_dis_value) {
818   if (!p_dis_value) {
819     log::warn("read DIS failed");
820   } else {
821     bta_dm_search_cb.service_search_cbacks.on_did_received(
822         addr, p_dis_value->pnp_id.vendor_id_src, p_dis_value->pnp_id.vendor_id,
823         p_dis_value->pnp_id.product_id, p_dis_value->pnp_id.product_version);
824   }
825 
826   bta_dm_execute_queued_request();
827 }
828 #endif
829 
830 /*******************************************************************************
831  *
832  * Function         bta_dm_search_cmpl
833  *
834  * Description      Sends event to application
835  *
836  * Returns          void
837  *
838  ******************************************************************************/
bta_dm_search_cmpl()839 static void bta_dm_search_cmpl() {
840   bta_dm_search_set_state(BTA_DM_SEARCH_IDLE);
841 
842   uint16_t conn_id = bta_dm_search_cb.conn_id;
843 
844   std::vector<Uuid> gatt_services;
845 
846   bool send_gatt_results =
847       bluetooth::common::init_flags::
848               always_send_services_if_gatt_disc_done_is_enabled()
849           ? bta_dm_search_cb.gatt_disc_active
850           : false;
851 
852   /* no BLE connection, i.e. Classic service discovery end */
853   if (conn_id == GATT_INVALID_CONN_ID) {
854     if (bta_dm_search_cb.gatt_disc_active) {
855       log::warn(
856           "GATT active but no BLE connection, likely disconnected midway "
857           "through");
858     } else {
859       log::info("No BLE connection, processing classic results");
860     }
861   } else {
862     btgatt_db_element_t* db = NULL;
863     int count = 0;
864     get_gatt_interface().BTA_GATTC_GetGattDb(conn_id, 0x0000, 0xFFFF, &db,
865                                              &count);
866     if (count != 0) {
867       for (int i = 0; i < count; i++) {
868         // we process service entries only
869         if (db[i].type == BTGATT_DB_PRIMARY_SERVICE) {
870           gatt_services.push_back(db[i].uuid);
871         }
872       }
873       osi_free(db);
874       log::info(
875           "GATT services discovered using LE Transport, will always send to "
876           "upper layer");
877       send_gatt_results = true;
878     } else {
879       log::warn("Empty GATT database - no BLE services discovered");
880     }
881   }
882 
883   // send all result back to app
884   if (send_gatt_results) {
885     if (bta_dm_search_cb.service_search_cbacks.on_gatt_results != nullptr) {
886       log::info("Sending GATT results to upper layer");
887 
888       BD_NAME bd_name;
889       bd_name_from_char_pointer(bd_name, bta_dm_get_remname());
890       bta_dm_search_cb.service_search_cbacks.on_gatt_results(
891           bta_dm_search_cb.peer_bdaddr, bd_name, gatt_services,
892           /* transport_le */ true);
893     } else {
894       log::warn("on_gatt_results is nullptr!");
895     }
896   }
897 
898   if (bta_dm_search_cb.p_device_search_cback) {
899     bta_dm_search_cb.p_device_search_cback(BTA_DM_DISC_CMPL_EVT, nullptr);
900   }
901   bta_dm_search_cb.gatt_disc_active = false;
902 
903 #if TARGET_FLOSS
904   if (conn_id != GATT_INVALID_CONN_ID &&
905       DIS_ReadDISInfo(bta_dm_search_cb.peer_bdaddr, bta_dm_read_dis_cmpl,
906                       DIS_ATTR_PNP_ID_BIT)) {
907     return;
908   }
909 #endif
910 
911   bta_dm_execute_queued_request();
912 }
913 
914 /*******************************************************************************
915  *
916  * Function         bta_dm_disc_result
917  *
918  * Description      Service discovery result when discovering services on a
919  *                  device
920  *
921  * Returns          void
922  *
923  ******************************************************************************/
bta_dm_disc_result(tBTA_DM_SVC_RES & disc_result)924 static void bta_dm_disc_result(tBTA_DM_SVC_RES& disc_result) {
925   log::verbose("");
926 
927   /* disc_res.device_type is set only when GATT discovery is finished in
928    * bta_dm_gatt_disc_complete */
929   bool is_gatt_over_ble = ((disc_result.device_type & BT_DEVICE_TYPE_BLE) != 0);
930 
931   /* if any BR/EDR service discovery has been done, report the event */
932   if (!is_gatt_over_ble) {
933     auto& r = disc_result;
934     bta_dm_search_cb.service_search_cbacks.on_service_discovery_results(
935         r.bd_addr, r.uuids, r.result);
936   }
937 
938   /* Services were discovered while device search is in progress.
939    * Don't execute bta_dm_search_cmpl, as it would also finish the device
940    * search. It will be executed later when device search is finished. */
941   if (bta_dm_search_get_state() != BTA_DM_SEARCH_ACTIVE) {
942     get_gatt_interface().BTA_GATTC_CancelOpen(0, bta_dm_search_cb.peer_bdaddr,
943                                               true);
944 
945     bta_dm_search_cmpl();
946   }
947 }
948 
949 /*******************************************************************************
950  *
951  * Function         bta_dm_free_sdp_db
952  *
953  * Description      Frees SDP data base
954  *
955  * Returns          void
956  *
957  ******************************************************************************/
bta_dm_free_sdp_db()958 static void bta_dm_free_sdp_db() {
959   osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db);
960 }
961 
962 /*******************************************************************************
963  *
964  * Function         bta_dm_queue_search
965  *
966  * Description      Queues search command
967  *
968  * Returns          void
969  *
970  ******************************************************************************/
bta_dm_queue_search(tBTA_DM_API_SEARCH & search)971 static void bta_dm_queue_search(tBTA_DM_API_SEARCH& search) {
972   if (bta_dm_search_cb.p_pending_search) {
973     log::warn("Overwrote previous device discovery inquiry scan request");
974   }
975   bta_dm_search_cb.p_pending_search.reset(new tBTA_DM_MSG(search));
976   log::info("Queued device discovery inquiry scan request");
977 }
978 
979 /*******************************************************************************
980  *
981  * Function         bta_dm_queue_disc
982  *
983  * Description      Queues discovery command
984  *
985  * Returns          void
986  *
987  ******************************************************************************/
bta_dm_queue_disc(tBTA_DM_API_DISCOVER & discovery)988 static void bta_dm_queue_disc(tBTA_DM_API_DISCOVER& discovery) {
989   log::info("bta_dm_discovery: queuing service discovery to {}",
990             discovery.bd_addr);
991   bta_dm_search_cb.pending_discovery_queue.push(discovery);
992 }
993 
994 /*******************************************************************************
995  *
996  * Function         bta_dm_execute_queued_request
997  *
998  * Description      Executes queued request if one exists
999  *
1000  * Returns          void
1001  *
1002  ******************************************************************************/
bta_dm_execute_queued_request()1003 static void bta_dm_execute_queued_request() {
1004   if (!bta_dm_search_cb.pending_discovery_queue.empty()) {
1005     tBTA_DM_API_DISCOVER pending_discovery =
1006         bta_dm_search_cb.pending_discovery_queue.front();
1007     bta_dm_search_cb.pending_discovery_queue.pop();
1008     log::info("Start pending discovery");
1009     post_disc_evt(
1010         BTA_DM_API_DISCOVER_EVT,
1011         std::make_unique<tBTA_DM_MSG>(tBTA_DM_API_DISCOVER{pending_discovery}));
1012   } else if (bta_dm_search_cb.p_pending_search) {
1013     log::info("Start pending search");
1014     post_disc_evt(BTA_DM_API_SEARCH_EVT,
1015                   std::move(bta_dm_search_cb.p_pending_search));
1016     bta_dm_search_cb.p_pending_search.reset();
1017   }
1018 }
1019 
1020 /*******************************************************************************
1021  *
1022  * Function         bta_dm_is_search_request_queued
1023  *
1024  * Description      Checks if there is a queued search request
1025  *
1026  * Returns          bool
1027  *
1028  ******************************************************************************/
bta_dm_is_search_request_queued()1029 bool bta_dm_is_search_request_queued() {
1030   return bta_dm_search_cb.p_pending_search != NULL;
1031 }
1032 
1033 /*******************************************************************************
1034  *
1035  * Function         bta_dm_search_clear_queue
1036  *
1037  * Description      Clears the queue if API search cancel is called
1038  *
1039  * Returns          void
1040  *
1041  ******************************************************************************/
bta_dm_search_clear_queue()1042 static void bta_dm_search_clear_queue() {
1043   bta_dm_search_cb.p_pending_search.reset();
1044   if (bluetooth::common::InitFlags::
1045           IsBtmDmFlushDiscoveryQueueOnSearchCancel()) {
1046     bta_dm_search_cb.pending_discovery_queue = {};
1047   }
1048 }
1049 
1050 /*******************************************************************************
1051  *
1052  * Function         bta_dm_search_cancel_notify
1053  *
1054  * Description      Notify application that search has been cancelled
1055  *
1056  * Returns          void
1057  *
1058  ******************************************************************************/
bta_dm_search_cancel_notify()1059 static void bta_dm_search_cancel_notify() {
1060   if (bta_dm_search_cb.p_device_search_cback) {
1061     bta_dm_search_cb.p_device_search_cback(BTA_DM_SEARCH_CANCEL_CMPL_EVT, NULL);
1062   }
1063   switch (bta_dm_search_get_state()) {
1064     case BTA_DM_SEARCH_ACTIVE:
1065     case BTA_DM_SEARCH_CANCELLING:
1066       if (!bta_dm_search_cb.name_discover_done) {
1067         if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() !=
1068             BTM_CMD_STARTED) {
1069           log::warn("Unable to cancel RNR");
1070         }
1071       }
1072       break;
1073     case BTA_DM_SEARCH_IDLE:
1074     case BTA_DM_DISCOVER_ACTIVE:
1075       // Nothing to do
1076       break;
1077   }
1078 }
1079 
1080 /*******************************************************************************
1081  *
1082  * Function         bta_dm_find_services
1083  *
1084  * Description      Starts discovery on a device
1085  *
1086  * Returns          void
1087  *
1088  ******************************************************************************/
bta_dm_find_services(const RawAddress & bd_addr)1089 static void bta_dm_find_services(const RawAddress& bd_addr) {
1090   while (bta_dm_search_cb.service_index < BTA_MAX_SERVICE_ID) {
1091     Uuid uuid = Uuid::kEmpty;
1092     if (bta_dm_search_cb.services_to_search &
1093         (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(
1094             bta_dm_search_cb.service_index))) {
1095       bta_dm_search_cb.p_sdp_db =
1096           (tSDP_DISCOVERY_DB*)osi_malloc(BTA_DM_SDP_DB_SIZE);
1097 
1098       /* try to search all services by search based on L2CAP UUID */
1099       log::info("services_to_search={:08x}",
1100                 bta_dm_search_cb.services_to_search);
1101       if (bta_dm_search_cb.services_to_search & BTA_RES_SERVICE_MASK) {
1102         uuid = Uuid::From16Bit(bta_service_id_to_uuid_lkup_tbl[0]);
1103         bta_dm_search_cb.services_to_search &= ~BTA_RES_SERVICE_MASK;
1104       } else {
1105         uuid = Uuid::From16Bit(UUID_PROTOCOL_L2CAP);
1106         bta_dm_search_cb.services_to_search = 0;
1107       }
1108 
1109       log::info("search UUID = {}", uuid.ToString());
1110       if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(
1111               bta_dm_search_cb.p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, &uuid, 0,
1112               NULL)) {
1113         log::warn("Unable to initialize SDP service discovery db peer:{}",
1114                   bd_addr);
1115       }
1116 
1117       memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf));
1118       bta_dm_search_cb.p_sdp_db->raw_data = g_disc_raw_data_buf;
1119 
1120       bta_dm_search_cb.p_sdp_db->raw_size = MAX_DISC_RAW_DATA_BUF;
1121 
1122       if (!get_legacy_stack_sdp_api()
1123                ->service.SDP_ServiceSearchAttributeRequest(
1124                    bd_addr, bta_dm_search_cb.p_sdp_db, &bta_dm_sdp_callback)) {
1125         log::warn(
1126             "Unable to start SDP service search attribute request peer:{}",
1127             bd_addr);
1128         /*
1129          * If discovery is not successful with this device, then
1130          * proceed with the next one.
1131          */
1132         osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db);
1133         bta_dm_search_cb.service_index = BTA_MAX_SERVICE_ID;
1134 
1135       } else {
1136         if (uuid == Uuid::From16Bit(UUID_PROTOCOL_L2CAP)) {
1137           if (!is_sdp_pbap_pce_disabled(bd_addr)) {
1138             log::debug("SDP search for PBAP Client");
1139             BTA_SdpSearch(bd_addr, Uuid::From16Bit(UUID_SERVCLASS_PBAP_PCE));
1140           }
1141         }
1142         bta_dm_search_cb.service_index++;
1143         return;
1144       }
1145     }
1146 
1147     bta_dm_search_cb.service_index++;
1148   }
1149 
1150   /* no more services to be discovered */
1151   if (bta_dm_search_cb.service_index >= BTA_MAX_SERVICE_ID) {
1152     auto msg = std::make_unique<tBTA_DM_MSG>(tBTA_DM_SVC_RES{});
1153     auto& disc_result = std::get<tBTA_DM_SVC_RES>(*msg);
1154     disc_result.services = bta_dm_search_cb.services_found;
1155     disc_result.bd_addr = bta_dm_search_cb.peer_bdaddr;
1156 
1157     post_disc_evt(BTA_DM_DISCOVERY_RESULT_EVT, std::move(msg));
1158   }
1159 }
1160 
1161 /*******************************************************************************
1162  *
1163  * Function         bta_dm_discover_next_device
1164  *
1165  * Description      Starts discovery on the next device in Inquiry data base
1166  *
1167  * Returns          void
1168  *
1169  ******************************************************************************/
bta_dm_discover_next_device(void)1170 static void bta_dm_discover_next_device(void) {
1171   log::verbose("bta_dm_discover_next_device");
1172 
1173   /* searching next device on inquiry result */
1174   bta_dm_search_cb.p_btm_inq_info = get_btm_client_interface().db.BTM_InqDbNext(
1175       bta_dm_search_cb.p_btm_inq_info);
1176   if (bta_dm_search_cb.p_btm_inq_info != NULL) {
1177     bta_dm_search_cb.name_discover_done = false;
1178     bta_dm_search_cb.peer_name[0] = 0;
1179     bta_dm_discover_name(
1180         bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr);
1181   } else {
1182     post_disc_evt(BTA_DM_SEARCH_CMPL_EVT, nullptr);
1183   }
1184 }
1185 
1186 /*******************************************************************************
1187  *
1188  * Function         bta_dm_determine_discovery_transport
1189  *
1190  * Description      Starts name and service discovery on the device
1191  *
1192  * Returns          void
1193  *
1194  ******************************************************************************/
bta_dm_determine_discovery_transport(const RawAddress & remote_bd_addr)1195 static tBT_TRANSPORT bta_dm_determine_discovery_transport(
1196     const RawAddress& remote_bd_addr) {
1197   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1198   if (bta_dm_search_cb.transport == BT_TRANSPORT_AUTO) {
1199     tBT_DEVICE_TYPE dev_type;
1200     tBLE_ADDR_TYPE addr_type;
1201 
1202     get_btm_client_interface().peer.BTM_ReadDevInfo(remote_bd_addr, &dev_type,
1203                                                     &addr_type);
1204     if (dev_type == BT_DEVICE_TYPE_BLE || addr_type == BLE_ADDR_RANDOM) {
1205       transport = BT_TRANSPORT_LE;
1206     } else if (dev_type == BT_DEVICE_TYPE_DUMO) {
1207       if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(
1208               remote_bd_addr, BT_TRANSPORT_BR_EDR)) {
1209         transport = BT_TRANSPORT_BR_EDR;
1210       } else if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(
1211                      remote_bd_addr, BT_TRANSPORT_LE)) {
1212         transport = BT_TRANSPORT_LE;
1213       }
1214     }
1215   } else {
1216     transport = bta_dm_search_cb.transport;
1217   }
1218   return transport;
1219 }
1220 
bta_dm_discover_name(const RawAddress & remote_bd_addr)1221 static void bta_dm_discover_name(const RawAddress& remote_bd_addr) {
1222   const tBT_TRANSPORT transport =
1223       bta_dm_determine_discovery_transport(remote_bd_addr);
1224 
1225   log::verbose("BDA: {}", remote_bd_addr);
1226 
1227   bta_dm_search_cb.peer_bdaddr = remote_bd_addr;
1228 
1229   log::verbose(
1230       "name_discover_done = {} p_btm_inq_info 0x{} state = {}, transport={}",
1231       bta_dm_search_cb.name_discover_done,
1232       fmt::ptr(bta_dm_search_cb.p_btm_inq_info), bta_dm_search_get_state(),
1233       transport);
1234 
1235   if (bta_dm_search_cb.p_btm_inq_info) {
1236     log::verbose("appl_knows_rem_name {}",
1237                  bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name);
1238   }
1239   if (((bta_dm_search_cb.p_btm_inq_info) &&
1240        (bta_dm_search_cb.p_btm_inq_info->results.device_type ==
1241         BT_DEVICE_TYPE_BLE) &&
1242        (bta_dm_search_get_state() == BTA_DM_SEARCH_ACTIVE)) ||
1243       (transport == BT_TRANSPORT_LE &&
1244        interop_match_addr(INTEROP_DISABLE_NAME_REQUEST,
1245                           &bta_dm_search_cb.peer_bdaddr))) {
1246     /* Do not perform RNR for LE devices at inquiry complete*/
1247     bta_dm_search_cb.name_discover_done = true;
1248   }
1249   // If we already have the name we can skip getting the name
1250   if (BTM_IsRemoteNameKnown(remote_bd_addr, transport) &&
1251       bluetooth::common::init_flags::sdp_skip_rnr_if_known_is_enabled()) {
1252     log::debug(
1253         "Security record already known skipping read remote name peer:{}",
1254         remote_bd_addr);
1255     bta_dm_search_cb.name_discover_done = true;
1256   }
1257 
1258   /* if name discovery is not done and application needs remote name */
1259   if ((!bta_dm_search_cb.name_discover_done) &&
1260       ((bta_dm_search_cb.p_btm_inq_info == NULL) ||
1261        (bta_dm_search_cb.p_btm_inq_info &&
1262         (!bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name)))) {
1263     if (bta_dm_read_remote_device_name(bta_dm_search_cb.peer_bdaddr,
1264                                        transport)) {
1265       if (bta_dm_search_get_state() != BTA_DM_DISCOVER_ACTIVE) {
1266         log::debug("Reset transport state for next discovery");
1267         bta_dm_search_cb.transport = BT_TRANSPORT_AUTO;
1268       }
1269       BTM_LogHistory(kBtmLogTag, bta_dm_search_cb.peer_bdaddr,
1270                      "Read remote name",
1271                      base::StringPrintf("Transport:%s",
1272                                         bt_transport_text(transport).c_str()));
1273       return;
1274     } else {
1275       log::error("Unable to start read remote device name");
1276     }
1277 
1278     /* starting name discovery failed */
1279     bta_dm_search_cb.name_discover_done = true;
1280   }
1281 
1282   /* Reset transport state for next discovery */
1283   bta_dm_search_cb.transport = BT_TRANSPORT_AUTO;
1284 
1285   /* name discovery is done for this device */
1286   if (bta_dm_search_get_state() == BTA_DM_SEARCH_ACTIVE) {
1287     // if p_btm_inq_info is nullptr, there is no more inquiry results to
1288     // discover name for
1289     if (bta_dm_search_cb.p_btm_inq_info) {
1290       bta_dm_discover_next_device();
1291     } else {
1292       log::info("end of parsing inquiry result");
1293     }
1294   } else {
1295     log::info("name discovery finished in bad state: {}",
1296               bta_dm_state_text(bta_dm_search_get_state()));
1297   }
1298 }
1299 
bta_dm_discover_services(const RawAddress & remote_bd_addr)1300 static void bta_dm_discover_services(const RawAddress& remote_bd_addr) {
1301   const tBT_TRANSPORT transport =
1302       bta_dm_determine_discovery_transport(remote_bd_addr);
1303 
1304   log::verbose("BDA: {}, transport={}, state = {}", remote_bd_addr, transport,
1305                bta_dm_search_get_state());
1306 
1307   bta_dm_search_cb.peer_bdaddr = remote_bd_addr;
1308 
1309   /* Reset transport state for next discovery */
1310   bta_dm_search_cb.transport = BT_TRANSPORT_AUTO;
1311 
1312   bool sdp_disable = HID_HostSDPDisable(remote_bd_addr);
1313   if (sdp_disable)
1314     log::debug("peer:{} with HIDSDPDisable attribute.", remote_bd_addr);
1315 
1316   /* if application wants to discover service and HIDSDPDisable attribute is
1317      false.
1318      Classic mouses with this attribute should not start SDP here, because the
1319      SDP has been done during bonding. SDP request here will interleave with
1320      connections to the Control or Interrupt channels */
1321   if (!sdp_disable) {
1322     BTM_LogHistory(kBtmLogTag, remote_bd_addr, "Discovery started ",
1323                    base::StringPrintf("Transport:%s",
1324                                       bt_transport_text(transport).c_str()));
1325 
1326     /* initialize variables */
1327     bta_dm_search_cb.service_index = 0;
1328     bta_dm_search_cb.services_found = 0;
1329     bta_dm_search_cb.services_to_search = BTA_ALL_SERVICE_MASK;
1330 
1331     /* if seaching with EIR is not completed */
1332     if (bta_dm_search_cb.services_to_search) {
1333       /* check whether connection already exists to the device
1334          if connection exists, we don't have to wait for ACL
1335          link to go down to start search on next device */
1336       if (transport == BT_TRANSPORT_BR_EDR) {
1337         if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(
1338                 bta_dm_search_cb.peer_bdaddr, BT_TRANSPORT_BR_EDR))
1339           bta_dm_search_cb.wait_disc = false;
1340         else
1341           bta_dm_search_cb.wait_disc = true;
1342       }
1343 
1344       if (transport == BT_TRANSPORT_LE) {
1345         if (bta_dm_search_cb.services_to_search & BTA_BLE_SERVICE_MASK) {
1346           log::info("bta_dm_discovery: starting GATT discovery on {}",
1347                     bta_dm_search_cb.peer_bdaddr);
1348           // set the raw data buffer here
1349           memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf));
1350           /* start GATT for service discovery */
1351           btm_dm_start_gatt_discovery(bta_dm_search_cb.peer_bdaddr);
1352           return;
1353         }
1354       } else {
1355         log::info("bta_dm_discovery: starting SDP discovery on {}",
1356                   bta_dm_search_cb.peer_bdaddr);
1357         bta_dm_search_cb.sdp_results = false;
1358         bta_dm_find_services(bta_dm_search_cb.peer_bdaddr);
1359         return;
1360       }
1361     }
1362   }
1363 
1364   /* service discovery is done for this device */
1365   auto msg = std::make_unique<tBTA_DM_MSG>(tBTA_DM_SVC_RES{});
1366   auto& svc_result = std::get<tBTA_DM_SVC_RES>(*msg);
1367 
1368   /* initialize the data structure */
1369   svc_result.result = BTA_SUCCESS;
1370   svc_result.services = bta_dm_search_cb.services_found;
1371   svc_result.bd_addr = bta_dm_search_cb.peer_bdaddr;
1372 
1373   bta_dm_search_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, std::move(msg));
1374 }
1375 
1376 /*******************************************************************************
1377  *
1378  * Function         bta_dm_sdp_callback
1379  *
1380  * Description      Callback from sdp with discovery status
1381  *
1382  * Returns          void
1383  *
1384  ******************************************************************************/
bta_dm_sdp_callback(const RawAddress &,tSDP_STATUS sdp_status)1385 static void bta_dm_sdp_callback(const RawAddress& /* bd_addr */,
1386                                 tSDP_STATUS sdp_status) {
1387   post_disc_evt(BTA_DM_SDP_RESULT_EVT,
1388                 std::make_unique<tBTA_DM_MSG>(
1389                     tBTA_DM_SDP_RESULT{.sdp_result = sdp_status}));
1390 }
1391 
1392 /*******************************************************************************
1393  *
1394  * Function         bta_dm_inq_results_cb
1395  *
1396  * Description      Inquiry results callback from BTM
1397  *
1398  * Returns          void
1399  *
1400  ******************************************************************************/
bta_dm_inq_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)1401 static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir,
1402                                   uint16_t eir_len) {
1403   tBTA_DM_SEARCH result;
1404   tBTM_INQ_INFO* p_inq_info;
1405   uint16_t service_class;
1406 
1407   result.inq_res.bd_addr = p_inq->remote_bd_addr;
1408 
1409   // Pass the original address to GattService#onScanResult
1410   result.inq_res.original_bda = p_inq->original_bda;
1411 
1412   result.inq_res.dev_class = p_inq->dev_class;
1413   BTM_COD_SERVICE_CLASS(service_class, p_inq->dev_class);
1414   result.inq_res.is_limited =
1415       (service_class & BTM_COD_SERVICE_LMTD_DISCOVER) ? true : false;
1416   result.inq_res.rssi = p_inq->rssi;
1417 
1418   result.inq_res.ble_addr_type = p_inq->ble_addr_type;
1419   result.inq_res.inq_result_type = p_inq->inq_result_type;
1420   result.inq_res.device_type = p_inq->device_type;
1421   result.inq_res.flag = p_inq->flag;
1422   result.inq_res.include_rsi = p_inq->include_rsi;
1423   result.inq_res.clock_offset = p_inq->clock_offset;
1424 
1425   /* application will parse EIR to find out remote device name */
1426   result.inq_res.p_eir = const_cast<uint8_t*>(p_eir);
1427   result.inq_res.eir_len = eir_len;
1428 
1429   result.inq_res.ble_evt_type = p_inq->ble_evt_type;
1430 
1431   p_inq_info =
1432       get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr);
1433   if (p_inq_info != NULL) {
1434     /* initialize remt_name_not_required to false so that we get the name by
1435      * default */
1436     result.inq_res.remt_name_not_required = false;
1437   }
1438 
1439   if (bta_dm_search_cb.p_device_search_cback)
1440     bta_dm_search_cb.p_device_search_cback(BTA_DM_INQ_RES_EVT, &result);
1441 
1442   if (p_inq_info) {
1443     /* application indicates if it knows the remote name, inside the callback
1444      copy that to the inquiry data base*/
1445     if (result.inq_res.remt_name_not_required)
1446       p_inq_info->appl_knows_rem_name = true;
1447   }
1448 }
1449 
1450 /*******************************************************************************
1451  *
1452  * Function         bta_dm_inq_cmpl_cb
1453  *
1454  * Description      Inquiry complete callback from BTM
1455  *
1456  * Returns          void
1457  *
1458  ******************************************************************************/
bta_dm_inq_cmpl_cb(void *)1459 static void bta_dm_inq_cmpl_cb(void* /* p_result */) {
1460   log::verbose("");
1461 
1462   bta_dm_inq_cmpl();
1463 }
1464 
1465 /*******************************************************************************
1466  *
1467  * Function         bta_dm_service_search_remname_cback
1468  *
1469  * Description      Remote name call back from BTM during service discovery
1470  *
1471  * Returns          void
1472  *
1473  ******************************************************************************/
bta_dm_service_search_remname_cback(const RawAddress & bd_addr,DEV_CLASS,BD_NAME bd_name)1474 static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr,
1475                                                 DEV_CLASS /* dc */,
1476                                                 BD_NAME bd_name) {
1477   tBTM_REMOTE_DEV_NAME rem_name = {};
1478   tBTM_STATUS btm_status;
1479 
1480   log::verbose("name=<{}>", reinterpret_cast<char const*>(bd_name));
1481 
1482   /* if this is what we are looking for */
1483   if (bta_dm_search_cb.peer_bdaddr == bd_addr) {
1484     rem_name.bd_addr = bd_addr;
1485     bd_name_copy(rem_name.remote_bd_name, bd_name);
1486     rem_name.status = BTM_SUCCESS;
1487     rem_name.hci_status = HCI_SUCCESS;
1488     bta_dm_remname_cback(&rem_name);
1489   } else {
1490     /* get name of device */
1491     btm_status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName(
1492         bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback,
1493         BT_TRANSPORT_BR_EDR);
1494     if (btm_status == BTM_BUSY) {
1495       /* wait for next chance(notification of remote name discovery done) */
1496       log::verbose("BTM_ReadRemoteDeviceName is busy");
1497     } else if (btm_status != BTM_CMD_STARTED) {
1498       /* if failed to start getting remote name then continue */
1499       log::warn("BTM_ReadRemoteDeviceName returns 0x{:02X}", btm_status);
1500 
1501       // needed so our response is not ignored, since this corresponds to the
1502       // actual peer_bdaddr
1503       rem_name.bd_addr = bta_dm_search_cb.peer_bdaddr;
1504       rem_name.remote_bd_name[0] = 0;
1505       rem_name.status = btm_status;
1506       rem_name.hci_status = HCI_SUCCESS;
1507       bta_dm_remname_cback(&rem_name);
1508     }
1509   }
1510 }
1511 
1512 /*******************************************************************************
1513  *
1514  * Function         bta_dm_remname_cback
1515  *
1516  * Description      Remote name complete call back from BTM
1517  *
1518  * Returns          void
1519  *
1520  ******************************************************************************/
bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME * p_remote_name)1521 static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p_remote_name) {
1522   log::assert_that(p_remote_name != nullptr,
1523                    "assert failed: p_remote_name != nullptr");
1524 
1525   log::info(
1526       "Remote name request complete peer:{} btm_status:{} hci_status:{} "
1527       "name[0]:{:c} length:{}",
1528       p_remote_name->bd_addr, btm_status_text(p_remote_name->status),
1529       hci_error_code_text(p_remote_name->hci_status),
1530       p_remote_name->remote_bd_name[0],
1531       strnlen((const char*)p_remote_name->remote_bd_name, BD_NAME_LEN));
1532 
1533   if (bta_dm_search_cb.peer_bdaddr == p_remote_name->bd_addr) {
1534     get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback(
1535         &bta_dm_service_search_remname_cback);
1536   } else {
1537     // if we got a different response, maybe ignore it
1538     // we will have made a request directly from BTM_ReadRemoteDeviceName so we
1539     // expect a dedicated response for us
1540     if (p_remote_name->hci_status == HCI_ERR_CONNECTION_EXISTS) {
1541       get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback(
1542           &bta_dm_service_search_remname_cback);
1543       log::info(
1544           "Assume command failed due to disconnection hci_status:{} peer:{}",
1545           hci_error_code_text(p_remote_name->hci_status),
1546           p_remote_name->bd_addr);
1547     } else {
1548       log::info(
1549           "Ignored remote name response for the wrong address exp:{} act:{}",
1550           bta_dm_search_cb.peer_bdaddr, p_remote_name->bd_addr);
1551       return;
1552     }
1553   }
1554 
1555   /* remote name discovery is done but it could be failed */
1556   bta_dm_search_cb.name_discover_done = true;
1557   bd_name_copy(bta_dm_search_cb.peer_name, p_remote_name->remote_bd_name);
1558 
1559   if (bta_dm_search_cb.transport == BT_TRANSPORT_LE) {
1560     GAP_BleReadPeerPrefConnParams(bta_dm_search_cb.peer_bdaddr);
1561   }
1562 
1563   auto msg = std::make_unique<tBTA_DM_MSG>(tBTA_DM_REMOTE_NAME{});
1564   auto& rmt_name_msg = std::get<tBTA_DM_REMOTE_NAME>(*msg);
1565   rmt_name_msg.bd_addr = bta_dm_search_cb.peer_bdaddr;
1566   rmt_name_msg.hci_status = p_remote_name->hci_status;
1567   bd_name_copy(rmt_name_msg.bd_name, p_remote_name->remote_bd_name);
1568 
1569   post_disc_evt(BTA_DM_REMT_NAME_EVT, std::move(msg));
1570 }
1571 
1572 /*******************************************************************************
1573  *
1574  * Function         bta_dm_get_remname
1575  *
1576  * Description      Returns a pointer to the remote name stored in the DM
1577  *                  control block if it exists, or from the BTM memory.
1578  *
1579  * Returns          char * - Pointer to the remote device name
1580  ******************************************************************************/
bta_dm_get_remname(void)1581 const char* bta_dm_get_remname(void) {
1582   const char* p_name = (const char*)bta_dm_search_cb.peer_name;
1583 
1584   /* If the name isn't already stored, try retrieving from BTM */
1585   if (*p_name == '\0') {
1586     const char* p_temp = get_btm_client_interface().security.BTM_SecReadDevName(
1587         bta_dm_search_cb.peer_bdaddr);
1588     if (p_temp != NULL) p_name = (const char*)p_temp;
1589   }
1590 
1591   return p_name;
1592 }
1593 
1594 /*******************************************************************************
1595  *
1596  * Function         bta_dm_observe_results_cb
1597  *
1598  * Description      Callback for BLE Observe result
1599  *
1600  *
1601  * Returns          void
1602  *
1603  ******************************************************************************/
bta_dm_observe_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)1604 static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq,
1605                                       const uint8_t* p_eir, uint16_t eir_len) {
1606   tBTA_DM_SEARCH result;
1607   tBTM_INQ_INFO* p_inq_info;
1608   log::verbose("bta_dm_observe_results_cb");
1609 
1610   result.inq_res.bd_addr = p_inq->remote_bd_addr;
1611   result.inq_res.original_bda = p_inq->original_bda;
1612   result.inq_res.rssi = p_inq->rssi;
1613   result.inq_res.ble_addr_type = p_inq->ble_addr_type;
1614   result.inq_res.inq_result_type = p_inq->inq_result_type;
1615   result.inq_res.device_type = p_inq->device_type;
1616   result.inq_res.flag = p_inq->flag;
1617   result.inq_res.ble_evt_type = p_inq->ble_evt_type;
1618   result.inq_res.ble_primary_phy = p_inq->ble_primary_phy;
1619   result.inq_res.ble_secondary_phy = p_inq->ble_secondary_phy;
1620   result.inq_res.ble_advertising_sid = p_inq->ble_advertising_sid;
1621   result.inq_res.ble_tx_power = p_inq->ble_tx_power;
1622   result.inq_res.ble_periodic_adv_int = p_inq->ble_periodic_adv_int;
1623 
1624   /* application will parse EIR to find out remote device name */
1625   result.inq_res.p_eir = const_cast<uint8_t*>(p_eir);
1626   result.inq_res.eir_len = eir_len;
1627 
1628   p_inq_info =
1629       get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr);
1630   if (p_inq_info != NULL) {
1631     /* initialize remt_name_not_required to false so that we get the name by
1632      * default */
1633     result.inq_res.remt_name_not_required = false;
1634   }
1635 
1636   if (p_inq_info) {
1637     /* application indicates if it knows the remote name, inside the callback
1638      copy that to the inquiry data base*/
1639     if (result.inq_res.remt_name_not_required)
1640       p_inq_info->appl_knows_rem_name = true;
1641   }
1642 }
1643 
1644 /*******************************************************************************
1645  *
1646  * Function         bta_dm_opportunistic_observe_results_cb
1647  *
1648  * Description      Callback for BLE Observe result
1649  *
1650  *
1651  * Returns          void
1652  *
1653  ******************************************************************************/
bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)1654 static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq,
1655                                                     const uint8_t* p_eir,
1656                                                     uint16_t eir_len) {
1657   tBTA_DM_SEARCH result;
1658   tBTM_INQ_INFO* p_inq_info;
1659 
1660   result.inq_res.bd_addr = p_inq->remote_bd_addr;
1661   result.inq_res.rssi = p_inq->rssi;
1662   result.inq_res.ble_addr_type = p_inq->ble_addr_type;
1663   result.inq_res.inq_result_type = p_inq->inq_result_type;
1664   result.inq_res.device_type = p_inq->device_type;
1665   result.inq_res.flag = p_inq->flag;
1666   result.inq_res.ble_evt_type = p_inq->ble_evt_type;
1667   result.inq_res.ble_primary_phy = p_inq->ble_primary_phy;
1668   result.inq_res.ble_secondary_phy = p_inq->ble_secondary_phy;
1669   result.inq_res.ble_advertising_sid = p_inq->ble_advertising_sid;
1670   result.inq_res.ble_tx_power = p_inq->ble_tx_power;
1671   result.inq_res.ble_periodic_adv_int = p_inq->ble_periodic_adv_int;
1672 
1673   /* application will parse EIR to find out remote device name */
1674   result.inq_res.p_eir = const_cast<uint8_t*>(p_eir);
1675   result.inq_res.eir_len = eir_len;
1676 
1677   p_inq_info =
1678       get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr);
1679   if (p_inq_info != NULL) {
1680     /* initialize remt_name_not_required to false so that we get the name by
1681      * default */
1682     result.inq_res.remt_name_not_required = false;
1683   }
1684 
1685   if (bta_dm_search_cb.p_csis_scan_cback)
1686     bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_RES_EVT, &result);
1687 
1688   if (p_inq_info) {
1689     /* application indicates if it knows the remote name, inside the callback
1690      copy that to the inquiry data base*/
1691     if (result.inq_res.remt_name_not_required)
1692       p_inq_info->appl_knows_rem_name = true;
1693   }
1694 }
1695 
1696 /*******************************************************************************
1697  *
1698  * Function         bta_dm_observe_cmpl_cb
1699  *
1700  * Description      Callback for BLE Observe complete
1701  *
1702  *
1703  * Returns          void
1704  *
1705  ******************************************************************************/
bta_dm_observe_cmpl_cb(void * p_result)1706 static void bta_dm_observe_cmpl_cb(void* p_result) {
1707   log::verbose("bta_dm_observe_cmpl_cb");
1708 
1709   if (bta_dm_search_cb.p_csis_scan_cback) {
1710     auto num_resps = ((tBTM_INQUIRY_CMPL*)p_result)->num_resp;
1711     tBTA_DM_SEARCH data{.observe_cmpl{.num_resps = num_resps}};
1712     bta_dm_search_cb.p_csis_scan_cback(BTA_DM_OBSERVE_CMPL_EVT, &data);
1713   }
1714 }
1715 
bta_dm_start_scan(uint8_t duration_sec,bool low_latency_scan=false)1716 static void bta_dm_start_scan(uint8_t duration_sec,
1717                               bool low_latency_scan = false) {
1718   tBTM_STATUS status = get_btm_client_interface().ble.BTM_BleObserve(
1719       true, duration_sec, bta_dm_observe_results_cb, bta_dm_observe_cmpl_cb,
1720       low_latency_scan);
1721 
1722   if (status != BTM_CMD_STARTED) {
1723     log::warn("BTM_BleObserve  failed. status {}", status);
1724     if (bta_dm_search_cb.p_csis_scan_cback) {
1725       tBTA_DM_SEARCH data{.observe_cmpl = {.num_resps = 0}};
1726       bta_dm_search_cb.p_csis_scan_cback(BTA_DM_OBSERVE_CMPL_EVT, &data);
1727     }
1728   }
1729 }
1730 
bta_dm_ble_scan(bool start,uint8_t duration_sec,bool low_latency_scan=false)1731 void bta_dm_ble_scan(bool start, uint8_t duration_sec,
1732                      bool low_latency_scan = false) {
1733   if (!start) {
1734     if (get_btm_client_interface().ble.BTM_BleObserve(
1735             false, 0, NULL, NULL, false) != BTM_CMD_STARTED) {
1736       log::warn("Unable to stop ble observe");
1737     }
1738     return;
1739   }
1740 
1741   bta_dm_start_scan(duration_sec, low_latency_scan);
1742 }
1743 
bta_dm_ble_csis_observe(bool observe,tBTA_DM_SEARCH_CBACK * p_cback)1744 void bta_dm_ble_csis_observe(bool observe, tBTA_DM_SEARCH_CBACK* p_cback) {
1745   if (!observe) {
1746     bta_dm_search_cb.p_csis_scan_cback = NULL;
1747     BTM_BleOpportunisticObserve(false, NULL);
1748     return;
1749   }
1750 
1751   /* Save the callback to be called when a scan results are available */
1752   bta_dm_search_cb.p_csis_scan_cback = p_cback;
1753   BTM_BleOpportunisticObserve(true, bta_dm_opportunistic_observe_results_cb);
1754 }
1755 
1756 #ifndef BTA_DM_GATT_CLOSE_DELAY_TOUT
1757 #define BTA_DM_GATT_CLOSE_DELAY_TOUT 1000
1758 #endif
1759 
1760 /*******************************************************************************
1761  *
1762  * Function         bta_dm_gattc_register
1763  *
1764  * Description      Register with GATTC in DM if BLE is needed.
1765  *
1766  *
1767  * Returns          void
1768  *
1769  ******************************************************************************/
bta_dm_gattc_register(void)1770 static void bta_dm_gattc_register(void) {
1771   if (bta_dm_search_cb.client_if != BTA_GATTS_INVALID_IF) {
1772     // Already registered
1773     return;
1774   }
1775   get_gatt_interface().BTA_GATTC_AppRegister(
1776       bta_dm_gattc_callback, base::Bind([](uint8_t client_id, uint8_t status) {
1777         tGATT_STATUS gatt_status = static_cast<tGATT_STATUS>(status);
1778         disc_gatt_history_.Push(base::StringPrintf(
1779             "%-32s client_id:%hu status:%s", "GATTC_RegisteredCallback",
1780             client_id, gatt_status_text(gatt_status).c_str()));
1781         if (static_cast<tGATT_STATUS>(status) == GATT_SUCCESS) {
1782           log::info(
1783               "Registered device discovery search gatt client tGATT_IF:{}",
1784               client_id);
1785           bta_dm_search_cb.client_if = client_id;
1786         } else {
1787           log::warn(
1788               "Failed to register device discovery search gatt client "
1789               "gatt_status:{} previous tGATT_IF:{}",
1790               bta_dm_search_cb.client_if, status);
1791           bta_dm_search_cb.client_if = BTA_GATTS_INVALID_IF;
1792         }
1793       }),
1794       false);
1795 }
1796 
gatt_close_timer_cb(void *)1797 static void gatt_close_timer_cb(void*) {
1798   bta_dm_search_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT, nullptr);
1799 }
1800 
1801 /*******************************************************************************
1802  *
1803  * Function         bta_dm_gatt_disc_complete
1804  *
1805  * Description      This function process the GATT service search complete.
1806  *
1807  * Parameters:
1808  *
1809  ******************************************************************************/
bta_dm_gatt_disc_complete(uint16_t conn_id,tGATT_STATUS status)1810 static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) {
1811   log::verbose("conn_id = {}", conn_id);
1812 
1813   auto msg = std::make_unique<tBTA_DM_MSG>(tBTA_DM_SVC_RES{});
1814   auto& svc_result = std::get<tBTA_DM_SVC_RES>(*msg);
1815 
1816   /* no more services to be discovered */
1817   svc_result.result = (status == GATT_SUCCESS) ? BTA_SUCCESS : BTA_FAILURE;
1818   log::verbose("service found: 0x{:08x}", bta_dm_search_cb.services_found);
1819   svc_result.services = bta_dm_search_cb.services_found;
1820   svc_result.bd_addr = bta_dm_search_cb.peer_bdaddr;
1821   svc_result.device_type |= BT_DEVICE_TYPE_BLE;
1822 
1823   bta_dm_search_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, std::move(msg));
1824 
1825   if (conn_id != GATT_INVALID_CONN_ID) {
1826     bta_dm_search_cb.pending_close_bda = bta_dm_search_cb.peer_bdaddr;
1827     // Gatt will be close immediately if bluetooth.gatt.delay_close.enabled is
1828     // set to false. If property is true / unset there will be a delay
1829     if (bta_dm_search_cb.gatt_close_timer != nullptr) {
1830       /* start a GATT channel close delay timer */
1831       alarm_set_on_mloop(bta_dm_search_cb.gatt_close_timer,
1832                          BTA_DM_GATT_CLOSE_DELAY_TOUT, gatt_close_timer_cb, 0);
1833     } else {
1834       bta_dm_search_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT, nullptr);
1835     }
1836   } else {
1837     bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
1838 
1839     if (com::android::bluetooth::flags::bta_dm_disc_stuck_in_cancelling_fix()) {
1840       log::info(
1841           "Discovery complete for invalid conn ID. Will pick up next job");
1842       bta_dm_search_set_state(BTA_DM_SEARCH_IDLE);
1843       bta_dm_free_sdp_db();
1844       bta_dm_execute_queued_request();
1845     }
1846   }
1847 }
1848 
1849 /*******************************************************************************
1850  *
1851  * Function         bta_dm_close_gatt_conn
1852  *
1853  * Description      This function close the GATT connection after delay
1854  *timeout.
1855  *
1856  * Parameters:
1857  *
1858  ******************************************************************************/
bta_dm_close_gatt_conn()1859 static void bta_dm_close_gatt_conn() {
1860   if (bta_dm_search_cb.conn_id != GATT_INVALID_CONN_ID)
1861     BTA_GATTC_Close(bta_dm_search_cb.conn_id);
1862 
1863   bta_dm_search_cb.pending_close_bda = RawAddress::kEmpty;
1864   bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
1865 }
1866 /*******************************************************************************
1867  *
1868  * Function         btm_dm_start_gatt_discovery
1869  *
1870  * Description      This is GATT initiate the service search by open a GATT
1871  *                  connection first.
1872  *
1873  * Parameters:
1874  *
1875  ******************************************************************************/
btm_dm_start_gatt_discovery(const RawAddress & bd_addr)1876 static void btm_dm_start_gatt_discovery(const RawAddress& bd_addr) {
1877   constexpr bool kUseOpportunistic = true;
1878 
1879   bta_dm_search_cb.gatt_disc_active = true;
1880 
1881   /* connection is already open */
1882   if (bta_dm_search_cb.pending_close_bda == bd_addr &&
1883       bta_dm_search_cb.conn_id != GATT_INVALID_CONN_ID) {
1884     bta_dm_search_cb.pending_close_bda = RawAddress::kEmpty;
1885     alarm_cancel(bta_dm_search_cb.gatt_close_timer);
1886     get_gatt_interface().BTA_GATTC_ServiceSearchRequest(
1887         bta_dm_search_cb.conn_id, nullptr);
1888   } else {
1889     if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(
1890             bd_addr, BT_TRANSPORT_LE)) {
1891       log::debug(
1892           "Use existing gatt client connection for discovery peer:{} "
1893           "transport:{} opportunistic:{:c}",
1894           bd_addr, bt_transport_text(BT_TRANSPORT_LE),
1895           (kUseOpportunistic) ? 'T' : 'F');
1896       get_gatt_interface().BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr,
1897                                           BTM_BLE_DIRECT_CONNECTION,
1898                                           kUseOpportunistic);
1899     } else {
1900       log::debug(
1901           "Opening new gatt client connection for discovery peer:{} "
1902           "transport:{} opportunistic:{:c}",
1903           bd_addr, bt_transport_text(BT_TRANSPORT_LE),
1904           (!kUseOpportunistic) ? 'T' : 'F');
1905       get_gatt_interface().BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr,
1906                                           BTM_BLE_DIRECT_CONNECTION,
1907                                           !kUseOpportunistic);
1908     }
1909   }
1910 }
1911 
1912 /*******************************************************************************
1913  *
1914  * Function         bta_dm_proc_open_evt
1915  *
1916  * Description      process BTA_GATTC_OPEN_EVT in DM.
1917  *
1918  * Parameters:
1919  *
1920  ******************************************************************************/
bta_dm_proc_open_evt(tBTA_GATTC_OPEN * p_data)1921 static void bta_dm_proc_open_evt(tBTA_GATTC_OPEN* p_data) {
1922   log::verbose("DM Search state= {} search_cb.peer_dbaddr:{} connected_bda={}",
1923                bta_dm_search_get_state(), bta_dm_search_cb.peer_bdaddr,
1924                p_data->remote_bda);
1925 
1926   log::debug("BTA_GATTC_OPEN_EVT conn_id = {} client_if={} status = {}",
1927              p_data->conn_id, p_data->client_if, p_data->status);
1928 
1929   disc_gatt_history_.Push(base::StringPrintf(
1930       "%-32s bd_addr:%s conn_id:%hu client_if:%hu event:%s",
1931       "GATTC_EventCallback", ADDRESS_TO_LOGGABLE_CSTR(p_data->remote_bda),
1932       p_data->conn_id, p_data->client_if,
1933       gatt_client_event_text(BTA_GATTC_OPEN_EVT).c_str()));
1934 
1935   bta_dm_search_cb.conn_id = p_data->conn_id;
1936 
1937   if (p_data->status == GATT_SUCCESS) {
1938     get_gatt_interface().BTA_GATTC_ServiceSearchRequest(p_data->conn_id,
1939                                                         nullptr);
1940   } else {
1941     bta_dm_gatt_disc_complete(GATT_INVALID_CONN_ID, p_data->status);
1942   }
1943 }
1944 
1945 /*******************************************************************************
1946  *
1947  * Function         bta_dm_gattc_callback
1948  *
1949  * Description      This is GATT client callback function used in DM.
1950  *
1951  * Parameters:
1952  *
1953  ******************************************************************************/
bta_dm_gattc_callback(tBTA_GATTC_EVT event,tBTA_GATTC * p_data)1954 static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) {
1955   log::verbose("bta_dm_gattc_callback event = {}", event);
1956 
1957   switch (event) {
1958     case BTA_GATTC_OPEN_EVT:
1959       bta_dm_proc_open_evt(&p_data->open);
1960       break;
1961 
1962     case BTA_GATTC_SEARCH_CMPL_EVT:
1963       switch (bta_dm_search_get_state()) {
1964         case BTA_DM_SEARCH_IDLE:
1965           break;
1966         case BTA_DM_SEARCH_ACTIVE:
1967         case BTA_DM_SEARCH_CANCELLING:
1968         case BTA_DM_DISCOVER_ACTIVE:
1969           bta_dm_gatt_disc_complete(p_data->search_cmpl.conn_id,
1970                                     p_data->search_cmpl.status);
1971           break;
1972       }
1973       disc_gatt_history_.Push(base::StringPrintf(
1974           "%-32s conn_id:%hu status:%s", "GATTC_EventCallback",
1975           p_data->search_cmpl.conn_id,
1976           gatt_status_text(p_data->search_cmpl.status).c_str()));
1977       break;
1978 
1979     case BTA_GATTC_CLOSE_EVT:
1980       log::info("BTA_GATTC_CLOSE_EVT reason = {}", p_data->close.reason);
1981 
1982       if (p_data->close.remote_bda == bta_dm_search_cb.peer_bdaddr) {
1983         bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
1984       }
1985 
1986       switch (bta_dm_search_get_state()) {
1987         case BTA_DM_SEARCH_IDLE:
1988         case BTA_DM_SEARCH_ACTIVE:
1989           break;
1990 
1991         case BTA_DM_SEARCH_CANCELLING:
1992         case BTA_DM_DISCOVER_ACTIVE:
1993           /* in case of disconnect before search is completed */
1994           if (p_data->close.remote_bda == bta_dm_search_cb.peer_bdaddr) {
1995             bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID,
1996                                       (tGATT_STATUS)GATT_ERROR);
1997           }
1998       }
1999       break;
2000 
2001     case BTA_GATTC_CANCEL_OPEN_EVT:
2002     case BTA_GATTC_CFG_MTU_EVT:
2003     case BTA_GATTC_CONGEST_EVT:
2004     case BTA_GATTC_CONN_UPDATE_EVT:
2005     case BTA_GATTC_DEREG_EVT:
2006     case BTA_GATTC_ENC_CMPL_CB_EVT:
2007     case BTA_GATTC_EXEC_EVT:
2008     case BTA_GATTC_NOTIF_EVT:
2009     case BTA_GATTC_PHY_UPDATE_EVT:
2010     case BTA_GATTC_SEARCH_RES_EVT:
2011     case BTA_GATTC_SRVC_CHG_EVT:
2012     case BTA_GATTC_SRVC_DISC_DONE_EVT:
2013     case BTA_GATTC_SUBRATE_CHG_EVT:
2014       disc_gatt_history_.Push(
2015           base::StringPrintf("%-32s event:%s", "GATTC_EventCallback",
2016                              gatt_client_event_text(event).c_str()));
2017       break;
2018   }
2019 }
2020 
2021 namespace bluetooth {
2022 namespace legacy {
2023 namespace testing {
2024 
bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME * p)2025 void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p) {
2026   ::bta_dm_disc_legacy::bta_dm_remname_cback(p);
2027 }
2028 
bta_dm_determine_discovery_transport(const RawAddress & bd_addr)2029 tBT_TRANSPORT bta_dm_determine_discovery_transport(const RawAddress& bd_addr) {
2030   return ::bta_dm_disc_legacy::bta_dm_determine_discovery_transport(bd_addr);
2031 }
2032 
bta_dm_remote_name_cmpl(const tBTA_DM_REMOTE_NAME & remote_name_msg)2033 void bta_dm_remote_name_cmpl(const tBTA_DM_REMOTE_NAME& remote_name_msg) {
2034   ::bta_dm_disc_legacy::bta_dm_remote_name_cmpl(remote_name_msg);
2035 }
2036 
bta_dm_sdp_result(tBTA_DM_SDP_RESULT & sdp_event)2037 void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) {
2038   ::bta_dm_disc_legacy::bta_dm_sdp_result(sdp_event);
2039 }
2040 
2041 }  // namespace testing
2042 }  // namespace legacy
2043 }  // namespace bluetooth
2044 
2045 namespace {
2046 constexpr size_t kSearchStateHistorySize = 50;
2047 constexpr char kTimeFormatString[] = "%Y-%m-%d %H:%M:%S";
2048 
2049 constexpr unsigned MillisPerSecond = 1000;
EpochMillisToString(long long time_ms)2050 std::string EpochMillisToString(long long time_ms) {
2051   time_t time_sec = time_ms / MillisPerSecond;
2052   struct tm tm;
2053   localtime_r(&time_sec, &tm);
2054   std::string s = ::bluetooth::common::StringFormatTime(kTimeFormatString, tm);
2055   return base::StringPrintf(
2056       "%s.%03u", s.c_str(),
2057       static_cast<unsigned int>(time_ms % MillisPerSecond));
2058 }
2059 
2060 }  // namespace
2061 
2062 struct tSEARCH_STATE_HISTORY {
2063   const tBTA_DM_STATE state;
2064   const tBTA_DM_EVT event;
ToStringbta_dm_disc_legacy::tSEARCH_STATE_HISTORY2065   std::string ToString() const {
2066     return base::StringPrintf("state:%25s event:%s",
2067                               bta_dm_state_text(state).c_str(),
2068                               bta_dm_event_text(event).c_str());
2069   }
2070 };
2071 
2072 ::bluetooth::common::TimestampedCircularBuffer<tSEARCH_STATE_HISTORY>
2073     search_state_history_(kSearchStateHistorySize);
2074 
2075 /*******************************************************************************
2076  *
2077  * Function         bta_dm_search_sm_execute
2078  *
2079  * Description      State machine event handling function for DM
2080  *
2081  *
2082  * Returns          void
2083  *
2084  ******************************************************************************/
bta_dm_search_sm_execute(tBTA_DM_EVT event,std::unique_ptr<tBTA_DM_MSG> msg)2085 static void bta_dm_search_sm_execute(tBTA_DM_EVT event,
2086                                      std::unique_ptr<tBTA_DM_MSG> msg) {
2087   log::info("state:{}, event:{}[0x{:x}]",
2088             bta_dm_state_text(bta_dm_search_get_state()),
2089             bta_dm_event_text(event), event);
2090   search_state_history_.Push({
2091       .state = bta_dm_search_get_state(),
2092       .event = event,
2093   });
2094 
2095   switch (bta_dm_search_get_state()) {
2096     case BTA_DM_SEARCH_IDLE:
2097       switch (event) {
2098         case BTA_DM_API_SEARCH_EVT:
2099           bta_dm_search_set_state(BTA_DM_SEARCH_ACTIVE);
2100           log::assert_that(std::holds_alternative<tBTA_DM_API_SEARCH>(*msg),
2101                            "bad message type: {}", msg->index());
2102 
2103           bta_dm_search_start(std::get<tBTA_DM_API_SEARCH>(*msg));
2104           break;
2105         case BTA_DM_API_DISCOVER_EVT:
2106           bta_dm_search_set_state(BTA_DM_DISCOVER_ACTIVE);
2107           log::assert_that(std::holds_alternative<tBTA_DM_API_DISCOVER>(*msg),
2108                            "bad message type: {}", msg->index());
2109 
2110           bta_dm_discover(std::get<tBTA_DM_API_DISCOVER>(*msg));
2111           break;
2112         case BTA_DM_API_SEARCH_CANCEL_EVT:
2113           bta_dm_search_clear_queue();
2114           bta_dm_search_cancel_notify();
2115           break;
2116         case BTA_DM_SDP_RESULT_EVT:
2117           bta_dm_free_sdp_db();
2118           break;
2119         case BTA_DM_DISC_CLOSE_TOUT_EVT:
2120           bta_dm_close_gatt_conn();
2121           break;
2122         default:
2123           log::info("Received unexpected event {}[0x{:x}] in state {}",
2124                     bta_dm_event_text(event), event,
2125                     bta_dm_state_text(bta_dm_search_get_state()));
2126       }
2127       break;
2128     case BTA_DM_SEARCH_ACTIVE:
2129       switch (event) {
2130         case BTA_DM_REMT_NAME_EVT:
2131           log::assert_that(std::holds_alternative<tBTA_DM_REMOTE_NAME>(*msg),
2132                            "bad message type: {}", msg->index());
2133 
2134           bta_dm_remote_name_cmpl(std::get<tBTA_DM_REMOTE_NAME>(*msg));
2135           break;
2136         case BTA_DM_SEARCH_CMPL_EVT:
2137           bta_dm_search_cmpl();
2138           break;
2139         case BTA_DM_DISCOVERY_RESULT_EVT:
2140           log::assert_that(std::holds_alternative<tBTA_DM_SVC_RES>(*msg),
2141                            "bad message type: {}", msg->index());
2142 
2143           bta_dm_disc_result(std::get<tBTA_DM_SVC_RES>(*msg));
2144           break;
2145         case BTA_DM_DISC_CLOSE_TOUT_EVT:
2146           bta_dm_close_gatt_conn();
2147           break;
2148         case BTA_DM_API_DISCOVER_EVT:
2149           log::assert_that(std::holds_alternative<tBTA_DM_API_DISCOVER>(*msg),
2150                            "bad message type: {}", msg->index());
2151 
2152           bta_dm_queue_disc(std::get<tBTA_DM_API_DISCOVER>(*msg));
2153           break;
2154         case BTA_DM_API_SEARCH_CANCEL_EVT:
2155           bta_dm_search_clear_queue();
2156           bta_dm_search_set_state(BTA_DM_SEARCH_CANCELLING);
2157           bta_dm_search_cancel();
2158           break;
2159         default:
2160           log::info("Received unexpected event {}[0x{:x}] in state {}",
2161                     bta_dm_event_text(event), event,
2162                     bta_dm_state_text(bta_dm_search_get_state()));
2163       }
2164       break;
2165     case BTA_DM_SEARCH_CANCELLING:
2166       switch (event) {
2167         case BTA_DM_API_SEARCH_EVT:
2168           log::assert_that(std::holds_alternative<tBTA_DM_API_SEARCH>(*msg),
2169                            "bad message type: {}", msg->index());
2170 
2171           bta_dm_queue_search(std::get<tBTA_DM_API_SEARCH>(*msg));
2172           break;
2173         case BTA_DM_API_DISCOVER_EVT:
2174           log::assert_that(std::holds_alternative<tBTA_DM_API_DISCOVER>(*msg),
2175                            "bad message type: {}", msg->index());
2176 
2177           bta_dm_queue_disc(std::get<tBTA_DM_API_DISCOVER>(*msg));
2178           break;
2179         case BTA_DM_API_SEARCH_CANCEL_EVT:
2180           bta_dm_search_clear_queue();
2181           bta_dm_search_cancel_notify();
2182           break;
2183         case BTA_DM_SDP_RESULT_EVT:
2184         case BTA_DM_REMT_NAME_EVT:
2185         case BTA_DM_SEARCH_CMPL_EVT:
2186         case BTA_DM_DISCOVERY_RESULT_EVT:
2187           bta_dm_search_set_state(BTA_DM_SEARCH_IDLE);
2188           bta_dm_free_sdp_db();
2189           bta_dm_search_cancel_notify();
2190           bta_dm_execute_queued_request();
2191           break;
2192         case BTA_DM_DISC_CLOSE_TOUT_EVT:
2193           bta_dm_close_gatt_conn();
2194           break;
2195         default:
2196           log::info("Received unexpected event {}[0x{:x}] in state {}",
2197                     bta_dm_event_text(event), event,
2198                     bta_dm_state_text(bta_dm_search_get_state()));
2199       }
2200       break;
2201     case BTA_DM_DISCOVER_ACTIVE:
2202       switch (event) {
2203         case BTA_DM_REMT_NAME_EVT:
2204           log::assert_that(std::holds_alternative<tBTA_DM_REMOTE_NAME>(*msg),
2205                            "bad message type: {}", msg->index());
2206 
2207           bta_dm_remote_name_cmpl(std::get<tBTA_DM_REMOTE_NAME>(*msg));
2208           break;
2209         case BTA_DM_SDP_RESULT_EVT:
2210           log::assert_that(std::holds_alternative<tBTA_DM_SDP_RESULT>(*msg),
2211                            "bad message type: {}", msg->index());
2212 
2213           bta_dm_sdp_result(std::get<tBTA_DM_SDP_RESULT>(*msg));
2214           break;
2215         case BTA_DM_SEARCH_CMPL_EVT:
2216           bta_dm_search_cmpl();
2217           break;
2218         case BTA_DM_DISCOVERY_RESULT_EVT:
2219           log::assert_that(std::holds_alternative<tBTA_DM_SVC_RES>(*msg),
2220                            "bad message type: {}", msg->index());
2221 
2222           bta_dm_disc_result(std::get<tBTA_DM_SVC_RES>(*msg));
2223           break;
2224         case BTA_DM_API_SEARCH_EVT:
2225           log::assert_that(std::holds_alternative<tBTA_DM_API_SEARCH>(*msg),
2226                            "bad message type: {}", msg->index());
2227 
2228           bta_dm_queue_search(std::get<tBTA_DM_API_SEARCH>(*msg));
2229           break;
2230         case BTA_DM_API_DISCOVER_EVT:
2231           log::assert_that(std::holds_alternative<tBTA_DM_API_DISCOVER>(*msg),
2232                            "bad message type: {}", msg->index());
2233 
2234           bta_dm_queue_disc(std::get<tBTA_DM_API_DISCOVER>(*msg));
2235           break;
2236         case BTA_DM_API_SEARCH_CANCEL_EVT:
2237           bta_dm_search_clear_queue();
2238           bta_dm_search_set_state(BTA_DM_SEARCH_CANCELLING);
2239           bta_dm_search_cancel_notify();
2240           break;
2241         case BTA_DM_DISC_CLOSE_TOUT_EVT:
2242           bta_dm_close_gatt_conn();
2243           break;
2244         default:
2245           log::info("Received unexpected event {}[0x{:x}] in state {}",
2246                     bta_dm_event_text(event), event,
2247                     bta_dm_state_text(bta_dm_search_get_state()));
2248       }
2249       break;
2250   }
2251 }
2252 
bta_dm_disc_init_search_cb(tBTA_DM_SEARCH_CB & bta_dm_search_cb)2253 static void bta_dm_disc_init_search_cb(tBTA_DM_SEARCH_CB& bta_dm_search_cb) {
2254   bta_dm_search_cb = {};
2255   bta_dm_search_cb.state = BTA_DM_SEARCH_IDLE;
2256   bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID;
2257   bta_dm_search_cb.transport = BT_TRANSPORT_AUTO;
2258 }
2259 
bta_dm_disc_reset()2260 static void bta_dm_disc_reset() {
2261   alarm_free(bta_dm_search_cb.search_timer);
2262   alarm_free(bta_dm_search_cb.gatt_close_timer);
2263   bta_dm_search_cb.p_pending_search.reset();
2264   bta_dm_search_cb.pending_discovery_queue = {};
2265   bta_dm_disc_init_search_cb(bta_dm_search_cb);
2266 }
2267 
bta_dm_disc_start(bool delay_close_gatt)2268 void bta_dm_disc_start(bool delay_close_gatt) {
2269   bta_dm_disc_reset();
2270   bta_dm_search_cb.search_timer = alarm_new("bta_dm_search.search_timer");
2271   bta_dm_search_cb.gatt_close_timer =
2272       delay_close_gatt ? alarm_new("bta_dm_search.gatt_close_timer") : nullptr;
2273   bta_dm_search_cb.pending_discovery_queue = {};
2274 }
2275 
bta_dm_disc_acl_down(const RawAddress & bd_addr,tBT_TRANSPORT transport)2276 void bta_dm_disc_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
2277   switch (transport) {
2278     case BT_TRANSPORT_BR_EDR:
2279       if (bta_dm_search_cb.wait_disc &&
2280           bta_dm_search_cb.peer_bdaddr == bd_addr) {
2281         bta_dm_search_cb.wait_disc = false;
2282 
2283         if (bta_dm_search_cb.sdp_results) {
2284           log::verbose("timer stopped");
2285           alarm_cancel(bta_dm_search_cb.search_timer);
2286           bta_dm_disc_discover_next_device();
2287         }
2288       }
2289       break;
2290 
2291     case BT_TRANSPORT_LE:
2292     default:
2293       break;
2294   }
2295 }
2296 
bta_dm_disc_stop()2297 void bta_dm_disc_stop() { bta_dm_disc_reset(); }
2298 
bta_dm_disc_start_device_discovery(tBTA_DM_SEARCH_CBACK * p_cback)2299 void bta_dm_disc_start_device_discovery(tBTA_DM_SEARCH_CBACK* p_cback) {
2300   bta_dm_search_sm_execute(
2301       BTA_DM_API_SEARCH_EVT,
2302       std::make_unique<tBTA_DM_MSG>(tBTA_DM_API_SEARCH{.p_cback = p_cback}));
2303 }
2304 
bta_dm_disc_stop_device_discovery()2305 void bta_dm_disc_stop_device_discovery() {
2306   bta_dm_search_sm_execute(BTA_DM_API_SEARCH_CANCEL_EVT, nullptr);
2307 }
2308 
bta_dm_disc_start_service_discovery(service_discovery_callbacks cbacks,const RawAddress & bd_addr,tBT_TRANSPORT transport)2309 void bta_dm_disc_start_service_discovery(service_discovery_callbacks cbacks,
2310                                          const RawAddress& bd_addr,
2311                                          tBT_TRANSPORT transport) {
2312   bta_dm_search_sm_execute(
2313       BTA_DM_API_DISCOVER_EVT,
2314       std::make_unique<tBTA_DM_MSG>(tBTA_DM_API_DISCOVER{
2315           .bd_addr = bd_addr, .cbacks = cbacks, .transport = transport}));
2316 }
2317 
2318 #define DUMPSYS_TAG "shim::legacy::bta::dm"
DumpsysBtaDmDisc(int fd)2319 void DumpsysBtaDmDisc(int fd) {
2320   auto copy = search_state_history_.Pull();
2321   LOG_DUMPSYS(fd, " last %zu search state transitions", copy.size());
2322   for (const auto& it : copy) {
2323     LOG_DUMPSYS(fd, "   %s %s", EpochMillisToString(it.timestamp).c_str(),
2324                 it.entry.ToString().c_str());
2325   }
2326   LOG_DUMPSYS(fd, " current bta_dm_search_state:%s",
2327               bta_dm_state_text(bta_dm_search_get_state()).c_str());
2328 }
2329 #undef DUMPSYS_TAG
2330 
2331 namespace bluetooth {
2332 namespace legacy {
2333 namespace testing {
2334 
bta_dm_disc_init_search_cb(tBTA_DM_SEARCH_CB & bta_dm_search_cb)2335 void bta_dm_disc_init_search_cb(tBTA_DM_SEARCH_CB& bta_dm_search_cb) {
2336   ::bta_dm_disc_legacy::bta_dm_disc_init_search_cb(bta_dm_search_cb);
2337 }
bta_dm_disc_get_search_cb()2338 tBTA_DM_SEARCH_CB bta_dm_disc_get_search_cb() {
2339   tBTA_DM_SEARCH_CB search_cb = {};
2340   ::bta_dm_disc_legacy::bta_dm_disc_init_search_cb(search_cb);
2341   return search_cb;
2342 }
bta_dm_disc_search_cb()2343 tBTA_DM_SEARCH_CB& bta_dm_disc_search_cb() {
2344   return ::bta_dm_disc_legacy::bta_dm_search_cb;
2345 }
bta_dm_read_remote_device_name(const RawAddress & bd_addr,tBT_TRANSPORT transport)2346 bool bta_dm_read_remote_device_name(const RawAddress& bd_addr,
2347                                     tBT_TRANSPORT transport) {
2348   return ::bta_dm_disc_legacy::bta_dm_read_remote_device_name(bd_addr,
2349                                                               transport);
2350 }
bta_dm_discover_next_device()2351 void bta_dm_discover_next_device() {
2352   ::bta_dm_disc_legacy::bta_dm_discover_next_device();
2353 }
2354 
bta_dm_execute_queued_request()2355 void bta_dm_execute_queued_request() {
2356   ::bta_dm_disc_legacy::bta_dm_execute_queued_request();
2357 }
bta_dm_find_services(const RawAddress & bd_addr)2358 void bta_dm_find_services(const RawAddress& bd_addr) {
2359   ::bta_dm_disc_legacy::bta_dm_find_services(bd_addr);
2360 }
bta_dm_inq_cmpl()2361 void bta_dm_inq_cmpl() { ::bta_dm_disc_legacy::bta_dm_inq_cmpl(); }
bta_dm_inq_cmpl_cb(void * p_result)2362 void bta_dm_inq_cmpl_cb(void* p_result) {
2363   ::bta_dm_disc_legacy::bta_dm_inq_cmpl_cb(p_result);
2364 }
bta_dm_observe_cmpl_cb(void * p_result)2365 void bta_dm_observe_cmpl_cb(void* p_result) {
2366   ::bta_dm_disc_legacy::bta_dm_observe_cmpl_cb(p_result);
2367 }
bta_dm_observe_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)2368 void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir,
2369                                uint16_t eir_len) {
2370   ::bta_dm_disc_legacy::bta_dm_observe_results_cb(p_inq, p_eir, eir_len);
2371 }
bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS * p_inq,const uint8_t * p_eir,uint16_t eir_len)2372 void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq,
2373                                              const uint8_t* p_eir,
2374                                              uint16_t eir_len) {
2375   ::bta_dm_disc_legacy::bta_dm_opportunistic_observe_results_cb(p_inq, p_eir,
2376                                                                 eir_len);
2377 }
bta_dm_queue_search(tBTA_DM_API_SEARCH & search)2378 void bta_dm_queue_search(tBTA_DM_API_SEARCH& search) {
2379   ::bta_dm_disc_legacy::bta_dm_queue_search(search);
2380 }
2381 
bta_dm_service_search_remname_cback(const RawAddress & bd_addr,DEV_CLASS dc,BD_NAME bd_name)2382 void bta_dm_service_search_remname_cback(const RawAddress& bd_addr,
2383                                          DEV_CLASS dc, BD_NAME bd_name) {
2384   ::bta_dm_disc_legacy::bta_dm_service_search_remname_cback(bd_addr, dc,
2385                                                             bd_name);
2386 }
2387 
bta_dm_start_scan(uint8_t duration_sec,bool low_latency_scan=false)2388 void bta_dm_start_scan(uint8_t duration_sec, bool low_latency_scan = false) {
2389   ::bta_dm_disc_legacy::bta_dm_start_scan(duration_sec, low_latency_scan);
2390 }
2391 
store_avrcp_profile_feature(tSDP_DISC_REC * sdp_rec)2392 void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) {
2393   ::bta_dm_disc_legacy::store_avrcp_profile_feature(sdp_rec);
2394 }
2395 
2396 }  // namespace testing
2397 }  // namespace legacy
2398 }  // namespace bluetooth
2399 
2400 }  // namespace bta_dm_disc_legacy
2401