1 /******************************************************************************
2 *
3 * Copyright (C) 2016-2017 The Linux Foundation
4 * Copyright 2009-2012 Broadcom Corporation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at:
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 ******************************************************************************/
19
20 /*******************************************************************************
21 *
22 * Filename: btif_dm.c
23 *
24 * Description: Contains Device Management (DM) related functionality
25 *
26 *
27 ******************************************************************************/
28
29 #define LOG_TAG "bt_btif_dm"
30
31 #include "btif_dm.h"
32
33 #include <base/functional/bind.h>
34 #include <base/strings/stringprintf.h>
35 #include <bluetooth/log.h>
36 #include <bluetooth/uuid.h>
37 #include <com_android_bluetooth_flags.h>
38 #include <hardware/bluetooth.h>
39 #include <hardware/bt_csis.h>
40 #include <hardware/bt_hearing_aid.h>
41 #include <hardware/bt_le_audio.h>
42 #include <hardware/bt_vc.h>
43 #include <signal.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <sys/types.h>
47 #include <time.h>
48 #include <unistd.h>
49
50 #include <mutex>
51 #include <optional>
52
53 #include "advertise_data_parser.h"
54 #include "bt_dev_class.h"
55 #include "bt_name.h"
56 #include "bta/dm/bta_dm_disc.h"
57 #include "bta/include/bta_api.h"
58 #include "bta/include/bta_hh_api.h"
59 #include "btif/include/stack_manager_t.h"
60 #include "btif_api.h"
61 #include "btif_bqr.h"
62 #include "btif_config.h"
63 #include "btif_dm.h"
64 #include "btif_metrics_logging.h"
65 #include "btif_profile_storage.h"
66 #include "btif_storage.h"
67 #include "btif_util.h"
68 #include "common/init_flags.h"
69 #include "common/lru_cache.h"
70 #include "common/metrics.h"
71 #include "device/include/interop.h"
72 #include "hci/controller_interface.h"
73 #include "hci/le_rand_callback.h"
74 #include "internal_include/bt_target.h"
75 #include "internal_include/stack_config.h"
76 #include "main/shim/entry.h"
77 #include "main/shim/helpers.h"
78 #include "main/shim/le_advertising_manager.h"
79 #include "main_thread.h"
80 #include "os/log.h"
81 #include "os/logging/log_adapter.h"
82 #include "osi/include/allocator.h"
83 #include "osi/include/properties.h"
84 #include "osi/include/stack_power_telemetry.h"
85 #include "stack/btm/btm_dev.h"
86 #include "stack/btm/btm_sec.h"
87 #include "stack/include/acl_api.h"
88 #include "stack/include/acl_api_types.h"
89 #include "stack/include/bt_dev_class.h"
90 #include "stack/include/bt_octets.h"
91 #include "stack/include/bt_types.h"
92 #include "stack/include/bt_uuid16.h"
93 #include "stack/include/btm_ble_addr.h"
94 #include "stack/include/btm_ble_api.h"
95 #include "stack/include/btm_ble_sec_api.h"
96 #include "stack/include/btm_ble_sec_api_types.h"
97 #include "stack/include/btm_client_interface.h"
98 #include "stack/include/btm_log_history.h"
99 #include "stack/include/btm_sec_api.h"
100 #include "stack/include/btm_sec_api_types.h"
101 #include "stack/include/smp_api.h"
102 #include "stack/include/srvc_api.h" // tDIS_VALUE
103 #include "stack/sdp/sdpint.h"
104 #include "storage/config_keys.h"
105 #include "types/raw_address.h"
106
107 #ifdef __ANDROID__
108 #include <android/sysprop/BluetoothProperties.sysprop.h>
109 #endif
110
111 bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type);
112 bool btif_get_device_type(const RawAddress& bda, int* p_device_type);
113
114 using bluetooth::Uuid;
115 using namespace bluetooth;
116
117 namespace {
118 constexpr char kBtmLogTag[] = "API";
119 constexpr char kBtmLogTagCallback[] = "CBACK";
120 constexpr char kBtmLogTagSdp[] = "SDP";
121 }
122
123 /******************************************************************************
124 * Constants & Macros
125 *****************************************************************************/
126
127 const Uuid UUID_HEARING_AID = Uuid::FromString("FDF0");
128 const Uuid UUID_VC = Uuid::FromString("1844");
129 const Uuid UUID_CSIS = Uuid::FromString("1846");
130 const Uuid UUID_LE_AUDIO = Uuid::FromString("184E");
131 const Uuid UUID_LE_MIDI =
132 Uuid::FromString("03B80E5A-EDE8-4B33-A751-6CE34EC4C700");
133 const Uuid UUID_HAS = Uuid::FromString("1854");
134 const Uuid UUID_BASS = Uuid::FromString("184F");
135 const Uuid UUID_BATTERY = Uuid::FromString("180F");
136 const Uuid UUID_A2DP_SINK = Uuid::FromString("110B");
137
138 #define BTIF_DM_MAX_SDP_ATTEMPTS_AFTER_PAIRING 2
139
140 #ifndef PROPERTY_CLASS_OF_DEVICE
141 #define PROPERTY_CLASS_OF_DEVICE "bluetooth.device.class_of_device"
142 #endif
143
144 #define NUM_TIMEOUT_RETRIES 5
145 #ifndef PROPERTY_DEFAULT_DEVICE_NAME
146 #define PROPERTY_DEFAULT_DEVICE_NAME "bluetooth.device.default_name"
147 #endif
148 #ifndef PROPERTY_PRODUCT_MODEL
149 #define PROPERTY_PRODUCT_MODEL "ro.product.model"
150 #endif
151 #define DEFAULT_LOCAL_NAME_MAX 31
152 #if (DEFAULT_LOCAL_NAME_MAX > BD_NAME_LEN)
153 #error "default btif local name size exceeds stack supported length"
154 #endif
155
156 #ifndef PROPERTY_BLE_PRIVACY_ENABLED
157 #define PROPERTY_BLE_PRIVACY_ENABLED "bluetooth.core.gap.le.privacy.enabled"
158 #endif
159
160 #define ENCRYPTED_BREDR 2
161 #define ENCRYPTED_LE 4
162
163 struct btif_dm_pairing_cb_t {
164 bt_bond_state_t state;
165 RawAddress static_bdaddr;
166 RawAddress bd_addr;
167 tBTM_BOND_TYPE bond_type;
168 uint8_t pin_code_len;
169 uint8_t is_ssp;
170 uint8_t auth_req;
171 uint8_t io_cap;
172 uint8_t autopair_attempts;
173 uint8_t timeout_retries;
174 uint8_t is_local_initiated;
175 uint8_t sdp_attempts;
176 bool is_le_only;
177 bool is_le_nc; /* LE Numeric comparison */
178 btif_dm_ble_cb_t ble;
179 uint8_t fail_reason;
180
181 enum ServiceDiscoveryState { NOT_STARTED, SCHEDULED, FINISHED };
182
183 ServiceDiscoveryState gatt_over_le;
184 ServiceDiscoveryState sdp_over_classic;
185 };
186
187 namespace fmt {
188 template <>
189 struct formatter<btif_dm_pairing_cb_t::ServiceDiscoveryState>
190 : enum_formatter<btif_dm_pairing_cb_t::ServiceDiscoveryState> {};
191 } // namespace fmt
192
193 // TODO(jpawlowski): unify ?
194 // btif_dm_local_key_id_t == tBTM_BLE_LOCAL_ID_KEYS == tBTA_BLE_LOCAL_ID_KEYS
195 typedef struct {
196 Octet16 ir;
197 Octet16 irk;
198 Octet16 dhk;
199 } btif_dm_local_key_id_t;
200
201 typedef struct {
202 bool is_er_rcvd;
203 Octet16 er;
204 bool is_id_keys_rcvd;
205 btif_dm_local_key_id_t id_keys; /* ID kyes */
206
207 } btif_dm_local_key_cb_t;
208
209 /* this structure holds optional OOB data for remote device */
210 typedef struct {
211 RawAddress bdaddr; /* peer bdaddr */
212 tBT_TRANSPORT transport; /* BR/EDR or LE */
213 int data_present; /* What type(s) of OOB Data present */
214 bt_oob_data_t p192_data; /* P192 Data or empty */
215 bt_oob_data_t p256_data; /* P256 Data or empty */
216 } btif_dm_oob_cb_t;
217
218 typedef struct {
219 unsigned int manufact_id;
220 } skip_sdp_entry_t;
221
222 typedef struct {
223 bluetooth::common::LruCache<RawAddress, std::vector<uint8_t>> le_audio_cache;
224 } btif_dm_metadata_cb_t;
225
226 typedef enum {
227 BTIF_DM_FUNC_CREATE_BOND,
228 BTIF_DM_FUNC_CANCEL_BOND,
229 BTIF_DM_FUNC_REMOVE_BOND,
230 BTIF_DM_FUNC_BOND_STATE_CHANGED,
231 } bt_bond_function_t;
232
233 typedef struct {
234 RawAddress bd_addr;
235 bt_bond_function_t function;
236 bt_bond_state_t state;
237 struct timespec timestamp;
238 } btif_bond_event_t;
239
240 #define BTA_SERVICE_ID_TO_SERVICE_MASK(id) (1 << (id))
241
242 #define MAX_BTIF_BOND_EVENT_ENTRIES 15
243
244 #define MAX_NUM_DEVICES_IN_EIR_UUID_CACHE 128
245
246 static bluetooth::common::LruCache<RawAddress, std::set<Uuid>> eir_uuids_cache(
247 MAX_NUM_DEVICES_IN_EIR_UUID_CACHE);
248
249 static skip_sdp_entry_t sdp_rejectlist[] = {{76}}; // Apple Mouse and Keyboard
250
251 /* This flag will be true if HCI_Inquiry is in progress */
252 static bool btif_dm_inquiry_in_progress = false;
253
254 /*******************************************************************************
255 * Static variables
256 ******************************************************************************/
257 static char btif_default_local_name[DEFAULT_LOCAL_NAME_MAX + 1] = {'\0'};
258 static uid_set_t* uid_set = NULL;
259
260 /* A circular array to keep track of the most recent bond events */
261 static btif_bond_event_t btif_dm_bond_events[MAX_BTIF_BOND_EVENT_ENTRIES + 1];
262
263 static std::mutex bond_event_lock;
264
265 /* |btif_num_bond_events| keeps track of the total number of events and can be
266 greater than |MAX_BTIF_BOND_EVENT_ENTRIES| */
267 static size_t btif_num_bond_events = 0;
268 static size_t btif_events_start_index = 0;
269 static size_t btif_events_end_index = 0;
270
271 /******************************************************************************
272 * Static functions
273 *****************************************************************************/
274 static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req,
275 bool is_consent);
276 static void btif_dm_remove_ble_bonding_keys(void);
277 static void btif_dm_save_ble_bonding_keys(RawAddress& bd_addr);
278 static btif_dm_pairing_cb_t pairing_cb;
279 static btif_dm_oob_cb_t oob_cb;
280 static btif_dm_metadata_cb_t metadata_cb{.le_audio_cache{40}};
281 static void btif_dm_cb_create_bond(const RawAddress bd_addr,
282 tBT_TRANSPORT transport);
283 static void btif_dm_cb_create_bond_le(const RawAddress bd_addr,
284 tBLE_ADDR_TYPE addr_type);
285 static void btif_update_remote_properties(const RawAddress& bd_addr,
286 BD_NAME bd_name, DEV_CLASS dev_class,
287 tBT_DEVICE_TYPE dev_type);
288 static btif_dm_local_key_cb_t ble_local_key_cb;
289 static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif);
290 static void btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl);
291 static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ* p_pin_req);
292 static void btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF* p_notif_req);
293 static void btif_dm_ble_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type);
294 static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type);
295
296 static const char* btif_get_default_local_name();
297
298 static void btif_stats_add_bond_event(const RawAddress& bd_addr,
299 bt_bond_function_t function,
300 bt_bond_state_t state);
301
302 static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status,
303 const BD_NAME bd_name, bool during_device_search);
304
305 /******************************************************************************
306 * Externs
307 *****************************************************************************/
308 bt_status_t btif_sdp_execute_service(bool b_enable);
309 void btif_iot_update_remote_info(tBTA_DM_AUTH_CMPL* p_auth_cmpl, bool is_ble,
310 bool is_ssp);
311
312 /******************************************************************************
313 * Functions
314 *****************************************************************************/
315
is_empty_128bit(uint8_t * data)316 static bool is_empty_128bit(uint8_t* data) {
317 static const uint8_t zero[16] = {0};
318 return !memcmp(zero, data, sizeof(zero));
319 }
320
is_bonding_or_sdp()321 static bool is_bonding_or_sdp() {
322 return pairing_cb.state == BT_BOND_STATE_BONDING ||
323 (pairing_cb.state == BT_BOND_STATE_BONDED && pairing_cb.sdp_attempts);
324 }
325
btif_dm_init(uid_set_t * set)326 void btif_dm_init(uid_set_t* set) { uid_set = set; }
327
btif_dm_cleanup(void)328 void btif_dm_cleanup(void) {
329 if (uid_set) {
330 uid_set_destroy(uid_set);
331 uid_set = NULL;
332 }
333 }
334
btif_in_execute_service_request(tBTA_SERVICE_ID service_id,bool b_enable)335 bt_status_t btif_in_execute_service_request(tBTA_SERVICE_ID service_id,
336 bool b_enable) {
337 log::verbose("service_id:{}", service_id);
338
339 if (service_id == BTA_SDP_SERVICE_ID) {
340 btif_sdp_execute_service(b_enable);
341 return BT_STATUS_SUCCESS;
342 }
343
344 return GetInterfaceToProfiles()->toggleProfile(service_id, b_enable);
345 }
346
347 /**
348 * Helper method to get asha advertising service data
349 * @param inq_res {@code tBTA_DM_INQ_RES} inquiry result
350 * @param asha_capability value will be updated as non-negative if found,
351 * otherwise return -1
352 * @param asha_truncated_hi_sync_id value will be updated if found, otherwise no
353 * change
354 */
get_asha_service_data(const tBTA_DM_INQ_RES & inq_res,int16_t & asha_capability,uint32_t & asha_truncated_hi_sync_id)355 static void get_asha_service_data(const tBTA_DM_INQ_RES& inq_res,
356 int16_t& asha_capability,
357 uint32_t& asha_truncated_hi_sync_id) {
358 asha_capability = -1;
359 if (inq_res.p_eir) {
360 const RawAddress& bdaddr = inq_res.bd_addr;
361
362 // iterate through advertisement service data
363 const uint8_t* p_service_data = inq_res.p_eir;
364 uint8_t service_data_len = 0;
365 while ((p_service_data = AdvertiseDataParser::GetFieldByType(
366 p_service_data + service_data_len,
367 inq_res.eir_len - (p_service_data - inq_res.p_eir) -
368 service_data_len,
369 BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) {
370 if (service_data_len < 2) {
371 continue;
372 }
373 uint16_t uuid;
374 const uint8_t* p_uuid = p_service_data;
375 STREAM_TO_UINT16(uuid, p_uuid);
376
377 if (uuid == 0xfdf0 /* ASHA service*/) {
378 log::info("ASHA found in {}", bdaddr);
379
380 // ASHA advertisement service data length should be at least 8
381 if (service_data_len < 8) {
382 log::warn("ASHA device service_data_len too short");
383 } else {
384 // It is intended to save ASHA capability byte to int16_t
385 asha_capability = p_service_data[3];
386 log::info("asha_capability: {}", asha_capability);
387
388 const uint8_t* p_truncated_hisyncid = &(p_service_data[4]);
389 STREAM_TO_UINT32(asha_truncated_hi_sync_id, p_truncated_hisyncid);
390 }
391 break;
392 }
393 }
394 }
395 }
396
397 /*******************************************************************************
398 *
399 * Function check_eir_remote_name
400 *
401 * Description Check if remote name is in the EIR data
402 *
403 * Returns true if remote name found
404 * Populate p_remote_name, if provided and remote name found
405 *
406 ******************************************************************************/
check_eir_remote_name(tBTA_DM_SEARCH * p_search_data,uint8_t * p_remote_name,uint8_t * p_remote_name_len)407 static bool check_eir_remote_name(tBTA_DM_SEARCH* p_search_data,
408 uint8_t* p_remote_name,
409 uint8_t* p_remote_name_len) {
410 const uint8_t* p_eir_remote_name = NULL;
411 uint8_t remote_name_len = 0;
412
413 /* Check EIR for remote name and services */
414 if (p_search_data->inq_res.p_eir) {
415 p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
416 p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len,
417 HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
418 if (!p_eir_remote_name) {
419 p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
420 p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len,
421 HCI_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
422 }
423
424 if (p_eir_remote_name) {
425 if (remote_name_len > BD_NAME_LEN) remote_name_len = BD_NAME_LEN;
426
427 if (p_remote_name && p_remote_name_len) {
428 memcpy(p_remote_name, p_eir_remote_name, remote_name_len);
429 *(p_remote_name + remote_name_len) = 0;
430 *p_remote_name_len = remote_name_len;
431 }
432
433 return true;
434 }
435 }
436
437 return false;
438 }
439
440 /*******************************************************************************
441 *
442 * Function check_eir_appearance
443 *
444 * Description Check if appearance is in the EIR data
445 *
446 * Returns true if appearance found
447 * Populate p_appearance, if provided and appearance found
448 *
449 ******************************************************************************/
check_eir_appearance(tBTA_DM_SEARCH * p_search_data,uint16_t * p_appearance)450 static bool check_eir_appearance(tBTA_DM_SEARCH* p_search_data,
451 uint16_t* p_appearance) {
452 const uint8_t* p_eir_appearance = NULL;
453 uint8_t appearance_len = 0;
454
455 /* Check EIR for remote name and services */
456 if (p_search_data->inq_res.p_eir) {
457 p_eir_appearance = AdvertiseDataParser::GetFieldByType(
458 p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len,
459 HCI_EIR_APPEARANCE_TYPE, &appearance_len);
460
461 if (p_eir_appearance && appearance_len >= 2) {
462 if (p_appearance) {
463 *p_appearance = *((uint16_t*)p_eir_appearance);
464 }
465
466 return true;
467 }
468 }
469
470 return false;
471 }
472
473 /*******************************************************************************
474 *
475 * Function get_cached_remote_name
476 *
477 * Description Check if remote name is in the NVRAM cache
478 *
479 * Returns true if remote name found
480 * Populate p_remote_name, if provided and remote name found
481 *
482 ******************************************************************************/
get_cached_remote_name(const RawAddress & bd_addr,uint8_t * p_remote_name,uint8_t * p_remote_name_len)483 static bool get_cached_remote_name(const RawAddress& bd_addr,
484 uint8_t* p_remote_name,
485 uint8_t* p_remote_name_len) {
486 bt_bdname_t bdname;
487 bt_property_t prop_name;
488
489 /* check if we already have it in our btif_storage cache */
490
491 BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME,
492 sizeof(bt_bdname_t), &bdname);
493 if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) ==
494 BT_STATUS_SUCCESS) {
495 if (p_remote_name && p_remote_name_len) {
496 strcpy((char*)p_remote_name, (char*)bdname.name);
497 *p_remote_name_len = strlen((char*)p_remote_name);
498 }
499 return true;
500 }
501
502 return false;
503 }
504
get_cod(const RawAddress * remote_bdaddr)505 static uint32_t get_cod(const RawAddress* remote_bdaddr) {
506 uint32_t remote_cod;
507 bt_property_t prop_name;
508
509 /* check if we already have it in our btif_storage cache */
510 BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE,
511 sizeof(uint32_t), &remote_cod);
512 if (btif_storage_get_remote_device_property(
513 (RawAddress*)remote_bdaddr, &prop_name) == BT_STATUS_SUCCESS) {
514 return remote_cod;
515 }
516
517 return 0;
518 }
519
check_cod(const RawAddress * remote_bdaddr,uint32_t cod)520 bool check_cod(const RawAddress* remote_bdaddr, uint32_t cod) {
521 return (get_cod(remote_bdaddr) & COD_DEVICE_MASK) == cod;
522 }
523
check_cod_hid(const RawAddress * remote_bdaddr)524 bool check_cod_hid(const RawAddress* remote_bdaddr) {
525 return (get_cod(remote_bdaddr) & COD_HID_MASK) == COD_HID_MAJOR;
526 }
527
check_cod_hid(const RawAddress & bd_addr)528 bool check_cod_hid(const RawAddress& bd_addr) {
529 return (get_cod(&bd_addr) & COD_HID_MASK) == COD_HID_MAJOR;
530 }
531
check_cod_hid_major(const RawAddress & bd_addr,uint32_t cod)532 bool check_cod_hid_major(const RawAddress& bd_addr, uint32_t cod) {
533 uint32_t remote_cod = get_cod(&bd_addr);
534 return (remote_cod & COD_HID_MASK) == COD_HID_MAJOR &&
535 (remote_cod & COD_HID_SUB_MAJOR) == (cod & COD_HID_SUB_MAJOR);
536 }
537
check_cod_le_audio(const RawAddress & bd_addr)538 bool check_cod_le_audio(const RawAddress& bd_addr) {
539 return (get_cod(&bd_addr) & COD_CLASS_LE_AUDIO) == COD_CLASS_LE_AUDIO;
540 }
541 /*****************************************************************************
542 *
543 * Function check_sdp_bl
544 *
545 * Description Checks if a given device is rejectlisted to skip sdp
546 *
547 * Parameters skip_sdp_entry
548 *
549 * Returns true if the device is present in rejectlist, else false
550 *
551 ******************************************************************************/
check_sdp_bl(const RawAddress * remote_bdaddr)552 static bool check_sdp_bl(const RawAddress* remote_bdaddr) {
553 bt_property_t prop_name;
554 bt_remote_version_t info;
555
556 if (remote_bdaddr == NULL) return false;
557
558 /* if not available yet, try fetching from config database */
559 BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_REMOTE_VERSION_INFO,
560 sizeof(bt_remote_version_t), &info);
561
562 if (btif_storage_get_remote_device_property(remote_bdaddr, &prop_name) !=
563 BT_STATUS_SUCCESS) {
564 return false;
565 }
566 uint16_t manufacturer = info.manufacturer;
567
568 for (unsigned int i = 0; i < ARRAY_SIZE(sdp_rejectlist); i++) {
569 if (manufacturer == sdp_rejectlist[i].manufact_id) return true;
570 }
571 return false;
572 }
573
bond_state_changed(bt_status_t status,const RawAddress & bd_addr,bt_bond_state_t state)574 static void bond_state_changed(bt_status_t status, const RawAddress& bd_addr,
575 bt_bond_state_t state) {
576 btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_BOND_STATE_CHANGED, state);
577
578 if ((pairing_cb.state == state) && (state == BT_BOND_STATE_BONDING)) {
579 // Cross key pairing so send callback for static address
580 if (!pairing_cb.static_bdaddr.IsEmpty()) {
581 BTM_LogHistory(
582 kBtmLogTagCallback, bd_addr, "Bond state changed",
583 base::StringPrintf(
584 "Crosskey bt_status:%s bond_state:%u reason:%s",
585 bt_status_text(status).c_str(), state,
586 hci_reason_code_text(to_hci_reason_code(pairing_cb.fail_reason))
587 .c_str()));
588 GetInterfaceToProfiles()->events->invoke_bond_state_changed_cb(
589 status, bd_addr, state, pairing_cb.fail_reason);
590 }
591 return;
592 }
593
594 if (pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
595 state = BT_BOND_STATE_NONE;
596 }
597
598 log::info(
599 "Bond state changed to state={}[0:none, 1:bonding, "
600 "2:bonded],prev_state={}, sdp_attempts={}",
601 state, pairing_cb.state, pairing_cb.sdp_attempts);
602
603 if (state == BT_BOND_STATE_NONE) {
604 forget_device_from_metric_id_allocator(bd_addr);
605
606 if (com::android::bluetooth::flags::
607 bond_transport_after_bond_cancel_fix()) {
608 btif_config_remove_device(bd_addr.ToString());
609 }
610
611 if (bluetooth::common::init_flags::
612 pbap_pse_dynamic_version_upgrade_is_enabled()) {
613 if (btif_storage_is_pce_version_102(bd_addr)) {
614 update_pce_entry_to_interop_database(bd_addr);
615 }
616 }
617 } else if (state == BT_BOND_STATE_BONDED) {
618 allocate_metric_id_from_metric_id_allocator(bd_addr);
619 if (!save_metric_id_from_metric_id_allocator(bd_addr)) {
620 log::error("Fail to save metric id for device:{}", bd_addr);
621 }
622 }
623 BTM_LogHistory(
624 kBtmLogTagCallback, bd_addr, "Bond state changed",
625 base::StringPrintf(
626 "bt_status:%s bond_state:%u reason:%s",
627 bt_status_text(status).c_str(), state,
628 hci_reason_code_text(to_hci_reason_code(pairing_cb.fail_reason))
629 .c_str()));
630 GetInterfaceToProfiles()->events->invoke_bond_state_changed_cb(
631 status, bd_addr, state, pairing_cb.fail_reason);
632
633 if ((state == BT_BOND_STATE_NONE) && (pairing_cb.bd_addr != bd_addr)
634 && is_bonding_or_sdp()) {
635 log::warn(
636 "Ignoring bond state changed for unexpected device: {} pairing: {}",
637 bd_addr, pairing_cb.bd_addr);
638 return;
639 }
640
641 if (state == BT_BOND_STATE_BONDING ||
642 (state == BT_BOND_STATE_BONDED &&
643 (pairing_cb.sdp_attempts > 0 ||
644 pairing_cb.gatt_over_le ==
645 btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED))) {
646 // Save state for the device is bonding or SDP or GATT over LE discovery
647 pairing_cb.state = state;
648 pairing_cb.bd_addr = bd_addr;
649 } else {
650 log::debug("clearing btif pairing_cb");
651 pairing_cb = {};
652 }
653 }
654
655 /* store remote version in bt config to always have access
656 to it post pairing*/
btif_update_remote_version_property(RawAddress * p_bd)657 static void btif_update_remote_version_property(RawAddress* p_bd) {
658 bt_property_t property;
659 uint8_t lmp_ver = 0;
660 uint16_t lmp_subver = 0;
661 uint16_t mfct_set = 0;
662 bt_remote_version_t info;
663 bt_status_t status;
664
665 log::assert_that(p_bd != nullptr, "assert failed: p_bd != nullptr");
666
667 const bool version_info_valid =
668 BTM_ReadRemoteVersion(*p_bd, &lmp_ver, &mfct_set, &lmp_subver);
669
670 log::info("Remote version info valid:{} [{}]:0x{:x},0x{:x},0x{:x}",
671 version_info_valid, *p_bd, lmp_ver, mfct_set, lmp_subver);
672
673 if (version_info_valid) {
674 // Always update cache to ensure we have availability whenever BTM API is
675 // not populated
676 info.manufacturer = mfct_set;
677 info.sub_ver = lmp_subver;
678 info.version = lmp_ver;
679 BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_REMOTE_VERSION_INFO,
680 sizeof(bt_remote_version_t), &info);
681 status = btif_storage_set_remote_device_property(p_bd, &property);
682 ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote version",
683 status);
684 }
685 }
686
btif_update_remote_properties(const RawAddress & bdaddr,BD_NAME bd_name,DEV_CLASS dev_class,tBT_DEVICE_TYPE device_type)687 static void btif_update_remote_properties(const RawAddress& bdaddr,
688 BD_NAME bd_name, DEV_CLASS dev_class,
689 tBT_DEVICE_TYPE device_type) {
690 std::vector<bt_property_t> properties;
691 bt_status_t status = BT_STATUS_UNHANDLED;
692 uint32_t cod;
693 uint32_t dev_type;
694
695 /* remote name */
696 if (strlen((const char*)bd_name)) {
697 properties.push_back(bt_property_t{
698 BT_PROPERTY_BDNAME, static_cast<int>(strlen((char*)bd_name)), bd_name});
699 status =
700 btif_storage_set_remote_device_property(&bdaddr, &properties.back());
701 ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device name",
702 status);
703 }
704
705 uint32_t old_cod = get_cod(&bdaddr);
706
707 /* class of device */
708 cod = devclass2uint(dev_class);
709 if ((cod == 0 || cod == COD_UNCLASSIFIED) && old_cod != 0) {
710 cod = old_cod;
711 }
712
713 if (old_cod != cod) {
714 log::info("{} CoD: 0x{:06x} -> 0x{:06x}", bdaddr, old_cod, cod);
715 }
716
717 properties.push_back(
718 bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod});
719
720 status = btif_storage_set_remote_device_property(&bdaddr, &properties.back());
721 ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device class",
722 status);
723
724 /* device type */
725 bt_property_t prop_name;
726 uint32_t remote_dev_type;
727 BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_TYPE_OF_DEVICE,
728 sizeof(uint32_t), &remote_dev_type);
729 if (btif_storage_get_remote_device_property(&bdaddr, &prop_name) ==
730 BT_STATUS_SUCCESS) {
731 dev_type = remote_dev_type | device_type;
732 } else {
733 dev_type = device_type;
734 }
735
736 properties.push_back(
737 bt_property_t{BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type});
738 status = btif_storage_set_remote_device_property(&bdaddr, &properties.back());
739 ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device type",
740 status);
741
742 GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
743 status, bdaddr, properties.size(), properties.data());
744 }
745
746 /* If device is LE Audio capable, we prefer LE connection first, this speeds
747 * up LE profile connection, and limits all possible service discovery
748 * ordering issues (first Classic, GATT over SDP, etc) */
is_device_le_audio_capable(const RawAddress bd_addr)749 bool is_device_le_audio_capable(const RawAddress bd_addr) {
750 if (!GetInterfaceToProfiles()
751 ->profileSpecific_HACK->IsLeAudioClientRunning()) {
752 /* If LE Audio profile is not enabled, do nothing. */
753 return false;
754 }
755
756 if (!check_cod_le_audio(bd_addr) && !BTA_DmCheckLeAudioCapable(bd_addr)) {
757 /* LE Audio not present in CoD or in LE Advertisement, do nothing.*/
758 return false;
759 }
760
761 /* First try reading device type from BTIF - it persists over multiple
762 * inquiry sessions */
763 int dev_type = 0;
764 if (com::android::bluetooth::flags::le_audio_dev_type_detection_fix() &&
765 (btif_get_device_type(bd_addr, &dev_type) &&
766 (dev_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE)) {
767 /* LE Audio capable device is discoverable over both LE and Classic using
768 * same address. Prefer to use LE transport, as we don't know if it can do
769 * CTKD from Classic to LE */
770 return true;
771 }
772
773 tBT_DEVICE_TYPE tmp_dev_type;
774 tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
775 BTM_ReadDevInfo(bd_addr, &tmp_dev_type, &addr_type);
776 if (tmp_dev_type & BT_DEVICE_TYPE_BLE) {
777 /* LE Audio capable device is discoverable over both LE and Classic using
778 * same address. Prefer to use LE transport, as we don't know if it can do
779 * CTKD from Classic to LE */
780 return true;
781 }
782
783 return false;
784 }
785
786 /* use to check if device is LE Audio Capable during bonding */
is_le_audio_capable_during_service_discovery(const RawAddress & bd_addr)787 bool is_le_audio_capable_during_service_discovery(const RawAddress& bd_addr) {
788 if (!GetInterfaceToProfiles()
789 ->profileSpecific_HACK->IsLeAudioClientRunning()) {
790 /* If LE Audio profile is not enabled, do nothing. */
791 return false;
792 }
793
794 if (bd_addr != pairing_cb.bd_addr && bd_addr != pairing_cb.static_bdaddr) {
795 return false;
796 }
797
798 if (check_cod_le_audio(bd_addr) ||
799 metadata_cb.le_audio_cache.contains(bd_addr) ||
800 metadata_cb.le_audio_cache.contains(pairing_cb.bd_addr) ||
801 BTA_DmCheckLeAudioCapable(bd_addr)) {
802 return true;
803 }
804
805 return false;
806 }
807
808 /*******************************************************************************
809 *
810 * Function btif_dm_cb_create_bond
811 *
812 * Description Create bond initiated from the BTIF thread context
813 * Special handling for HID devices
814 *
815 * Returns void
816 *
817 ******************************************************************************/
btif_dm_cb_create_bond(const RawAddress bd_addr,tBT_TRANSPORT transport)818 static void btif_dm_cb_create_bond(const RawAddress bd_addr,
819 tBT_TRANSPORT transport) {
820 bool is_hid = check_cod_hid_major(bd_addr, COD_HID_POINTING);
821 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
822
823 if (transport == BT_TRANSPORT_AUTO && is_device_le_audio_capable(bd_addr)) {
824 log::debug("LE Audio capable, forcing LE transport for Bonding");
825 transport = BT_TRANSPORT_LE;
826 }
827
828 int device_type = 0;
829 tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
830 std::string addrstr = bd_addr.ToString();
831 const char* bdstr = addrstr.c_str();
832 if (transport == BT_TRANSPORT_LE) {
833 if (!btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type)) {
834 btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, BT_DEVICE_TYPE_BLE);
835 }
836 if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) !=
837 BT_STATUS_SUCCESS) {
838 // Try to read address type. OOB pairing might have set it earlier, but
839 // didn't store it, it defaults to BLE_ADDR_PUBLIC
840 uint8_t tmp_dev_type;
841 tBLE_ADDR_TYPE tmp_addr_type = BLE_ADDR_PUBLIC;
842 BTM_ReadDevInfo(bd_addr, &tmp_dev_type, &tmp_addr_type);
843 addr_type = tmp_addr_type;
844
845 btif_storage_set_remote_addr_type(&bd_addr, addr_type);
846 }
847 }
848 if ((btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type) &&
849 (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) ==
850 BT_STATUS_SUCCESS) &&
851 (device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE) ||
852 (transport == BT_TRANSPORT_LE)) {
853 BTA_DmAddBleDevice(bd_addr, addr_type,
854 static_cast<tBT_DEVICE_TYPE>(device_type));
855 }
856
857 if (!com::android::bluetooth::flags::connect_hid_after_service_discovery() &&
858 is_hid && (device_type & BT_DEVICE_TYPE_BLE) == 0) {
859 tAclLinkSpec link_spec;
860 link_spec.addrt.bda = bd_addr;
861 link_spec.addrt.type = addr_type;
862 link_spec.transport = transport;
863 const bt_status_t status =
864 GetInterfaceToProfiles()->profileSpecific_HACK->btif_hh_connect(
865 link_spec);
866 if (status != BT_STATUS_SUCCESS)
867 bond_state_changed(status, bd_addr, BT_BOND_STATE_NONE);
868 } else {
869 BTA_DmBond(bd_addr, addr_type, transport, device_type);
870 }
871 /* Track originator of bond creation */
872 pairing_cb.is_local_initiated = true;
873 }
874
875 /*******************************************************************************
876 *
877 * Function btif_dm_cb_create_bond_le
878 *
879 * Description Create bond initiated with le device from the BTIF thread
880 * context
881 *
882 * Returns void
883 *
884 ******************************************************************************/
btif_dm_cb_create_bond_le(const RawAddress bd_addr,tBLE_ADDR_TYPE addr_type)885 static void btif_dm_cb_create_bond_le(const RawAddress bd_addr,
886 tBLE_ADDR_TYPE addr_type) {
887 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
888 /* Handle only LE create bond with random address case */
889 BTA_DmAddBleDevice(bd_addr, addr_type, BT_DEVICE_TYPE_BLE);
890 BTA_DmBond(bd_addr, addr_type, BT_TRANSPORT_LE, BT_DEVICE_TYPE_BLE);
891 /* Track originator of bond creation */
892 pairing_cb.is_local_initiated = true;
893 }
894
895 /*******************************************************************************
896 *
897 * Function btif_dm_get_connection_state
898 *
899 * Description Returns whether the remote device is currently connected
900 * and whether encryption is active for the connection
901 *
902 * Returns 0 if not connected; 1 if connected and > 1 if connection is
903 * encrypted
904 *
905 ******************************************************************************/
btif_dm_get_connection_state(const RawAddress & bd_addr)906 uint16_t btif_dm_get_connection_state(const RawAddress& bd_addr) {
907 uint16_t rc = 0;
908 if (BTA_DmGetConnectionState(bd_addr)) {
909 rc = (uint16_t) true;
910 if (BTM_IsEncrypted(bd_addr, BT_TRANSPORT_BR_EDR)) {
911 rc |= ENCRYPTED_BREDR;
912 }
913 if (BTM_IsEncrypted(bd_addr, BT_TRANSPORT_LE)) {
914 rc |= ENCRYPTED_LE;
915 }
916 } else {
917 log::info("Acl is not connected to peer:{}", bd_addr);
918 }
919 return rc;
920 }
921
btif_dm_get_resolved_connection_state(tBLE_BD_ADDR ble_bd_addr)922 static uint16_t btif_dm_get_resolved_connection_state(
923 tBLE_BD_ADDR ble_bd_addr) {
924 uint16_t rc = 0;
925 if (maybe_resolve_address(&ble_bd_addr.bda, &ble_bd_addr.type)) {
926 if (BTA_DmGetConnectionState(ble_bd_addr.bda)) {
927 rc = 0x0001;
928 if (BTM_IsEncrypted(ble_bd_addr.bda, BT_TRANSPORT_BR_EDR)) {
929 rc |= ENCRYPTED_BREDR;
930 }
931 if (BTM_IsEncrypted(ble_bd_addr.bda, BT_TRANSPORT_LE)) {
932 rc |= ENCRYPTED_LE;
933 }
934 }
935 }
936 return rc;
937 }
938
btif_dm_get_connection_state_sync(const RawAddress & bd_addr)939 uint16_t btif_dm_get_connection_state_sync(const RawAddress& bd_addr) {
940 std::promise<uint16_t> promise;
941 std::future future = promise.get_future();
942
943 auto status = do_in_main_thread(
944 FROM_HERE,
945 base::BindOnce(
946 [](const RawAddress bd_addr, std::promise<uint16_t> promise) {
947 // Experiment to try with maybe resolved address
948 uint16_t state = btif_dm_get_resolved_connection_state({
949 .type = BLE_ADDR_RANDOM,
950 .bda = bd_addr,
951 });
952 state |= btif_dm_get_connection_state(bd_addr);
953 promise.set_value(state);
954 },
955 bd_addr, std::move(promise)));
956 log::assert_that(BT_STATUS_SUCCESS == status,
957 "assert failed: BT_STATUS_SUCCESS == status");
958 return future.get();
959 }
960
961 /******************************************************************************
962 *
963 * BTIF DM callback events
964 *
965 ****************************************************************************/
966
967 /*******************************************************************************
968 *
969 * Function btif_dm_pin_req_evt
970 *
971 * Description Executes pin request event in btif context
972 *
973 * Returns void
974 *
975 ******************************************************************************/
btif_dm_pin_req_evt(tBTA_DM_PIN_REQ * p_pin_req)976 static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) {
977 bt_bdname_t bd_name;
978 uint32_t cod;
979 bt_pin_code_t pin_code;
980 int dev_type;
981
982 /* Remote properties update */
983 if (BTM_GetPeerDeviceTypeFromFeatures(p_pin_req->bd_addr) ==
984 BT_DEVICE_TYPE_DUMO) {
985 dev_type = BT_DEVICE_TYPE_DUMO;
986 } else if (!btif_get_device_type(p_pin_req->bd_addr, &dev_type)) {
987 // Failed to get device type, defaulting to BR/EDR.
988 dev_type = BT_DEVICE_TYPE_BREDR;
989 }
990 btif_update_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name,
991 p_pin_req->dev_class,
992 (tBT_DEVICE_TYPE)dev_type);
993
994 const RawAddress& bd_addr = p_pin_req->bd_addr;
995 bd_name_copy(bd_name.name, p_pin_req->bd_name);
996
997 if (pairing_cb.state == BT_BOND_STATE_BONDING &&
998 bd_addr != pairing_cb.bd_addr) {
999 log::warn("already in bonding state, reject request");
1000 return;
1001 }
1002
1003 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
1004
1005 cod = devclass2uint(p_pin_req->dev_class);
1006
1007 if (cod == 0) {
1008 log::warn("cod is 0, set as unclassified");
1009 cod = COD_UNCLASSIFIED;
1010 }
1011
1012 /* check for auto pair possiblity only if bond was initiated by local device
1013 */
1014 if (pairing_cb.is_local_initiated && !p_pin_req->min_16_digit) {
1015 if (check_cod(&bd_addr, COD_AV_HEADSETS) ||
1016 check_cod(&bd_addr, COD_AV_HEADPHONES) ||
1017 check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) ||
1018 check_cod(&bd_addr, COD_AV_HIFI_AUDIO) ||
1019 check_cod_hid_major(bd_addr, COD_HID_POINTING)) {
1020 /* Check if this device can be auto paired */
1021 if (!interop_match_addr(INTEROP_DISABLE_AUTO_PAIRING, &bd_addr) &&
1022 !interop_match_name(INTEROP_DISABLE_AUTO_PAIRING,
1023 (const char*)bd_name.name) &&
1024 (pairing_cb.autopair_attempts == 0)) {
1025 log::debug("Attempting auto pair w/ IOP");
1026 pin_code.pin[0] = 0x30;
1027 pin_code.pin[1] = 0x30;
1028 pin_code.pin[2] = 0x30;
1029 pin_code.pin[3] = 0x30;
1030
1031 pairing_cb.autopair_attempts++;
1032 BTA_DmPinReply(bd_addr, true, 4, pin_code.pin);
1033 return;
1034 }
1035 } else if (check_cod_hid_major(bd_addr, COD_HID_KEYBOARD) ||
1036 check_cod_hid_major(bd_addr, COD_HID_COMBO)) {
1037 if ((interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &bd_addr) ==
1038 true) &&
1039 (pairing_cb.autopair_attempts == 0)) {
1040 log::debug("Attempting auto pair w/ IOP");
1041 pin_code.pin[0] = 0x30;
1042 pin_code.pin[1] = 0x30;
1043 pin_code.pin[2] = 0x30;
1044 pin_code.pin[3] = 0x30;
1045
1046 pairing_cb.autopair_attempts++;
1047 BTA_DmPinReply(bd_addr, true, 4, pin_code.pin);
1048 return;
1049 }
1050 }
1051 }
1052 BTM_LogHistory(
1053 kBtmLogTagCallback, bd_addr, "Pin request",
1054 base::StringPrintf("name:\"%s\" min16:%c", PRIVATE_NAME(bd_name.name),
1055 (p_pin_req->min_16_digit) ? 'T' : 'F'));
1056 GetInterfaceToProfiles()->events->invoke_pin_request_cb(
1057 bd_addr, bd_name, cod, p_pin_req->min_16_digit);
1058 }
1059
1060 /*******************************************************************************
1061 *
1062 * Function btif_dm_ssp_cfm_req_evt
1063 *
1064 * Description Executes SSP confirm request event in btif context
1065 *
1066 * Returns void
1067 *
1068 ******************************************************************************/
btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ * p_ssp_cfm_req)1069 static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) {
1070 bool is_incoming = !(pairing_cb.state == BT_BOND_STATE_BONDING);
1071 int dev_type;
1072
1073 log::verbose("addr:{}, just_works:{}, loc_auth_req={}, rmt_auth_req={}",
1074 p_ssp_cfm_req->bd_addr, p_ssp_cfm_req->just_works,
1075 p_ssp_cfm_req->loc_auth_req, p_ssp_cfm_req->rmt_auth_req);
1076 /* Remote properties update */
1077 if (BTM_GetPeerDeviceTypeFromFeatures(p_ssp_cfm_req->bd_addr) ==
1078 BT_DEVICE_TYPE_DUMO) {
1079 dev_type = BT_DEVICE_TYPE_DUMO;
1080 } else if (!btif_get_device_type(p_ssp_cfm_req->bd_addr, &dev_type)) {
1081 // Failed to get device type, defaulting to BR/EDR.
1082 dev_type = BT_DEVICE_TYPE_BREDR;
1083 }
1084 btif_update_remote_properties(p_ssp_cfm_req->bd_addr, p_ssp_cfm_req->bd_name,
1085 p_ssp_cfm_req->dev_class,
1086 (tBT_DEVICE_TYPE)dev_type);
1087
1088 RawAddress bd_addr = p_ssp_cfm_req->bd_addr;
1089
1090 if (pairing_cb.state == BT_BOND_STATE_BONDING &&
1091 bd_addr != pairing_cb.bd_addr) {
1092 log::warn("already in bonding state, reject request");
1093 btif_dm_ssp_reply(bd_addr, BT_SSP_VARIANT_PASSKEY_CONFIRMATION, 0);
1094 return;
1095 }
1096
1097 /* Set the pairing_cb based on the local & remote authentication requirements
1098 */
1099 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
1100
1101 /* if just_works and bonding bit is not set treat this as temporary */
1102 if (p_ssp_cfm_req->just_works &&
1103 !(p_ssp_cfm_req->loc_auth_req & BTM_AUTH_BONDS) &&
1104 !(p_ssp_cfm_req->rmt_auth_req & BTM_AUTH_BONDS) &&
1105 !(check_cod_hid_major(p_ssp_cfm_req->bd_addr, COD_HID_POINTING)))
1106 pairing_cb.bond_type = BOND_TYPE_TEMPORARY;
1107 else
1108 pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
1109
1110 btm_set_bond_type_dev(p_ssp_cfm_req->bd_addr, pairing_cb.bond_type);
1111
1112 pairing_cb.is_ssp = true;
1113
1114 /* If JustWorks auto-accept */
1115 if (p_ssp_cfm_req->just_works) {
1116 /* Pairing consent for JustWorks NOT needed if:
1117 * Incoming temporary pairing is detected
1118 */
1119 if (is_incoming && pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
1120 log::debug(
1121 "Auto-accept JustWorks incoming pairing for temporary bonding");
1122 btif_dm_ssp_reply(bd_addr, BT_SSP_VARIANT_CONSENT, true);
1123 return;
1124 }
1125 }
1126
1127 pairing_cb.sdp_attempts = 0;
1128 BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
1129 base::StringPrintf("just_works:%c pin:%u",
1130 (p_ssp_cfm_req->just_works) ? 'T' : 'F',
1131 p_ssp_cfm_req->num_val));
1132 GetInterfaceToProfiles()->events->invoke_ssp_request_cb(
1133 bd_addr,
1134 (p_ssp_cfm_req->just_works ? BT_SSP_VARIANT_CONSENT
1135 : BT_SSP_VARIANT_PASSKEY_CONFIRMATION),
1136 p_ssp_cfm_req->num_val);
1137 }
1138
btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF * p_ssp_key_notif)1139 static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) {
1140 int dev_type;
1141
1142 log::verbose("addr:{}", p_ssp_key_notif->bd_addr);
1143
1144 /* Remote properties update */
1145 if (BTM_GetPeerDeviceTypeFromFeatures(p_ssp_key_notif->bd_addr) ==
1146 BT_DEVICE_TYPE_DUMO) {
1147 dev_type = BT_DEVICE_TYPE_DUMO;
1148 } else if (!btif_get_device_type(p_ssp_key_notif->bd_addr, &dev_type)) {
1149 // Failed to get device type, defaulting to BR/EDR.
1150 dev_type = BT_DEVICE_TYPE_BREDR;
1151 }
1152 btif_update_remote_properties(
1153 p_ssp_key_notif->bd_addr, p_ssp_key_notif->bd_name,
1154 p_ssp_key_notif->dev_class, (tBT_DEVICE_TYPE)dev_type);
1155
1156 RawAddress bd_addr = p_ssp_key_notif->bd_addr;
1157
1158 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
1159 pairing_cb.is_ssp = true;
1160
1161 BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
1162 base::StringPrintf("passkey:%u", p_ssp_key_notif->passkey));
1163 GetInterfaceToProfiles()->events->invoke_ssp_request_cb(
1164 bd_addr, BT_SSP_VARIANT_PASSKEY_NOTIFICATION, p_ssp_key_notif->passkey);
1165 }
1166 /*******************************************************************************
1167 *
1168 * Function btif_dm_auth_cmpl_evt
1169 *
1170 * Description Executes authentication complete event in btif context
1171 *
1172 * Returns void
1173 *
1174 ******************************************************************************/
btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL * p_auth_cmpl)1175 static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) {
1176 /* Save link key, if not temporary */
1177 bt_status_t status = BT_STATUS_FAIL;
1178 bt_bond_state_t state = BT_BOND_STATE_NONE;
1179 bool skip_sdp = false;
1180
1181 log::info("bond state={}, success={}, key_present={}", pairing_cb.state,
1182 p_auth_cmpl->success, p_auth_cmpl->key_present);
1183
1184 pairing_cb.fail_reason = p_auth_cmpl->fail_reason;
1185
1186 RawAddress bd_addr = p_auth_cmpl->bd_addr;
1187 tBLE_ADDR_TYPE addr_type = p_auth_cmpl->addr_type;
1188 if ((p_auth_cmpl->success) && (p_auth_cmpl->key_present)) {
1189 if ((p_auth_cmpl->key_type < HCI_LKEY_TYPE_DEBUG_COMB) ||
1190 (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB) ||
1191 (p_auth_cmpl->key_type == HCI_LKEY_TYPE_CHANGED_COMB) ||
1192 (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB_P_256) ||
1193 pairing_cb.bond_type == BOND_TYPE_PERSISTENT) {
1194 bt_status_t ret;
1195
1196 if (!bd_addr.IsEmpty()) {
1197 log::debug("Storing link key. key_type=0x{:x}, bond_type={}",
1198 p_auth_cmpl->key_type, pairing_cb.bond_type);
1199 ret = btif_storage_add_bonded_device(&bd_addr, p_auth_cmpl->key,
1200 p_auth_cmpl->key_type,
1201 pairing_cb.pin_code_len);
1202 } else {
1203 log::warn("bd_addr is empty");
1204 ret = BT_STATUS_PARM_INVALID;
1205 }
1206 ASSERTC(ret == BT_STATUS_SUCCESS, "storing link key failed", ret);
1207 } else {
1208 log::debug("Temporary key. Not storing. key_type=0x{:x}, bond_type={}",
1209 p_auth_cmpl->key_type, pairing_cb.bond_type);
1210 if (pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
1211 log::debug("sending BT_BOND_STATE_NONE for Temp pairing");
1212 btif_storage_remove_bonded_device(&bd_addr);
1213 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_NONE);
1214 return;
1215 }
1216 }
1217 }
1218
1219 if (p_auth_cmpl->success) {
1220 // save remote info to iot conf file
1221 btif_iot_update_remote_info(p_auth_cmpl, false, pairing_cb.is_ssp);
1222
1223 // We could have received a new link key without going through the pairing
1224 // flow. If so, we don't want to perform SDP or any other operations on the
1225 // authenticated device. Also, make sure that the link key is not derived
1226 // from secure LTK, because we will need to perform SDP in case of link key
1227 // derivation to allow bond state change notification for the BR/EDR
1228 // transport so that the subsequent BR/EDR connections to the remote can use
1229 // the derived link key.
1230 if (p_auth_cmpl->bd_addr != pairing_cb.bd_addr &&
1231 (!pairing_cb.ble.is_penc_key_rcvd)) {
1232 log::warn("skipping SDP for unknown device {}", p_auth_cmpl->bd_addr);
1233 return;
1234 }
1235
1236 btif_storage_set_remote_addr_type(&bd_addr, p_auth_cmpl->addr_type);
1237
1238 int dev_type;
1239 if (BTM_GetPeerDeviceTypeFromFeatures(bd_addr) == BT_DEVICE_TYPE_DUMO) {
1240 dev_type = BT_DEVICE_TYPE_DUMO;
1241 } else {
1242 dev_type = p_auth_cmpl->dev_type;
1243 }
1244
1245 bool is_crosskey = false;
1246 if (pairing_cb.state == BT_BOND_STATE_BONDING && p_auth_cmpl->is_ctkd) {
1247 log::debug("bonding initiated due to cross key pairing");
1248 is_crosskey = true;
1249 }
1250
1251 if (!is_crosskey) {
1252 btif_update_remote_properties(p_auth_cmpl->bd_addr, p_auth_cmpl->bd_name,
1253 kDevClassEmpty, dev_type);
1254 }
1255
1256 pairing_cb.timeout_retries = 0;
1257 status = BT_STATUS_SUCCESS;
1258 state = BT_BOND_STATE_BONDED;
1259 bd_addr = p_auth_cmpl->bd_addr;
1260
1261 if (check_sdp_bl(&bd_addr) && check_cod_hid(&bd_addr)) {
1262 log::warn("skip SDP");
1263 skip_sdp = true;
1264 }
1265 if (!pairing_cb.is_local_initiated && skip_sdp) {
1266 bond_state_changed(status, bd_addr, state);
1267
1268 log::warn("Incoming HID Connection");
1269 bt_property_t prop;
1270 Uuid uuid = Uuid::From16Bit(UUID_SERVCLASS_HUMAN_INTERFACE);
1271
1272 prop.type = BT_PROPERTY_UUIDS;
1273 prop.val = &uuid;
1274 prop.len = Uuid::kNumBytes128;
1275
1276 GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
1277 BT_STATUS_SUCCESS, bd_addr, 1, &prop);
1278 } else {
1279 /* If bonded due to cross-key, save the static address too*/
1280 if (is_crosskey) {
1281 log::debug("bonding initiated due to cross key, adding static address");
1282 pairing_cb.static_bdaddr = bd_addr;
1283 }
1284 if (!is_crosskey ||
1285 !(stack_config_get_interface()->get_pts_crosskey_sdp_disable())) {
1286 // Ensure inquiry is stopped before attempting service discovery
1287 btif_dm_cancel_discovery();
1288
1289 /* Trigger SDP on the device */
1290 pairing_cb.sdp_attempts = 1;
1291
1292 if (is_crosskey) {
1293 // If bonding occurred due to cross-key pairing, send address
1294 // consolidate callback
1295 BTM_LogHistory(
1296 kBtmLogTagCallback, bd_addr, "Consolidate",
1297 base::StringPrintf(" <=> %s",
1298 ADDRESS_TO_LOGGABLE_CSTR(pairing_cb.bd_addr)));
1299 GetInterfaceToProfiles()->events->invoke_address_consolidate_cb(
1300 pairing_cb.bd_addr, bd_addr);
1301 } else {
1302 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDED);
1303 }
1304
1305 if (pairing_cb.sdp_over_classic ==
1306 btif_dm_pairing_cb_t::ServiceDiscoveryState::NOT_STARTED) {
1307 log::info("scheduling SDP for {}", bd_addr);
1308 pairing_cb.sdp_over_classic =
1309 btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED;
1310 btif_dm_get_remote_services(bd_addr, BT_TRANSPORT_BR_EDR);
1311 }
1312 }
1313 }
1314 // Do not call bond_state_changed_cb yet. Wait until remote service
1315 // discovery is complete
1316 } else {
1317 log::warn("Bonding failed with failure reason:{}",
1318 hci_reason_code_text(p_auth_cmpl->fail_reason));
1319 bool is_bonded_device_removed = false;
1320 // Map the HCI fail reason to bt status
1321 switch (p_auth_cmpl->fail_reason) {
1322 case HCI_ERR_PAGE_TIMEOUT:
1323 case HCI_ERR_LMP_RESPONSE_TIMEOUT:
1324 if (interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &bd_addr) &&
1325 pairing_cb.timeout_retries) {
1326 log::warn("Pairing timeout; retrying ({}) ...",
1327 pairing_cb.timeout_retries);
1328 --pairing_cb.timeout_retries;
1329 if (addr_type == BLE_ADDR_RANDOM) {
1330 btif_dm_cb_create_bond_le(bd_addr, addr_type);
1331 } else {
1332 btif_dm_cb_create_bond(bd_addr, BT_TRANSPORT_AUTO);
1333 }
1334 return;
1335 }
1336 FALLTHROUGH_INTENDED; /* FALLTHROUGH */
1337 case HCI_ERR_CONNECTION_TOUT:
1338 status = BT_STATUS_RMT_DEV_DOWN;
1339 break;
1340
1341 case HCI_ERR_PAIRING_NOT_ALLOWED:
1342 is_bonded_device_removed = false;
1343 status = BT_STATUS_AUTH_REJECTED;
1344 break;
1345
1346 /* map the auth failure codes, so we can retry pairing if necessary */
1347 case HCI_ERR_AUTH_FAILURE:
1348 case HCI_ERR_KEY_MISSING:
1349 is_bonded_device_removed = false;
1350 [[fallthrough]];
1351 case HCI_ERR_HOST_REJECT_SECURITY:
1352 case HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE:
1353 case HCI_ERR_UNIT_KEY_USED:
1354 case HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED:
1355 case HCI_ERR_INSUFFCIENT_SECURITY:
1356 case HCI_ERR_PEER_USER:
1357 case HCI_ERR_UNSPECIFIED:
1358 log::warn("Authentication fail:{}",
1359 hci_reason_code_text(p_auth_cmpl->fail_reason));
1360 if (pairing_cb.autopair_attempts == 1) {
1361 /* Create the Bond once again */
1362 log::warn("auto pair failed. Reinitiate Bond");
1363 if (addr_type == BLE_ADDR_RANDOM) {
1364 btif_dm_cb_create_bond_le(bd_addr, addr_type);
1365 } else {
1366 btif_dm_cb_create_bond(bd_addr, BT_TRANSPORT_AUTO);
1367 }
1368 return;
1369 } else {
1370 /* if autopair attempts are more than 1, or not attempted */
1371 status = BT_STATUS_AUTH_FAILURE;
1372 }
1373 break;
1374
1375 default:
1376 status = BT_STATUS_UNHANDLED;
1377 }
1378 /* Special Handling for HID Devices */
1379 if (check_cod_hid_major(bd_addr, COD_HID_POINTING)) {
1380 /* Remove Device as bonded in nvram as authentication failed */
1381 log::verbose("removing hid pointing device from nvram");
1382 is_bonded_device_removed = false;
1383 }
1384 // Report bond state change to java only if we are bonding to a device or
1385 // a device is removed from the pairing list.
1386 if (pairing_cb.state == BT_BOND_STATE_BONDING || is_bonded_device_removed) {
1387 bond_state_changed(status, bd_addr, state);
1388 }
1389 }
1390 }
1391
1392 /******************************************************************************
1393 *
1394 * Function btif_dm_search_devices_evt
1395 *
1396 * Description Executes search devices callback events in btif context
1397 *
1398 * Returns void
1399 *
1400 *****************************************************************************/
btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event,tBTA_DM_SEARCH * p_search_data)1401 static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event,
1402 tBTA_DM_SEARCH* p_search_data) {
1403 log::verbose("event={}", dump_dm_search_event(event));
1404
1405 switch (event) {
1406 case BTA_DM_NAME_READ_EVT: {
1407 btif_on_name_read(p_search_data->name_res.bd_addr, HCI_SUCCESS,
1408 p_search_data->name_res.bd_name,
1409 true /* duirng_device_search */);
1410 } break;
1411
1412 case BTA_DM_INQ_RES_EVT: {
1413 /* inquiry result */
1414 bt_bdname_t bdname;
1415 uint8_t remote_name_len;
1416 uint8_t num_uuids = 0, max_num_uuid = 32;
1417 uint8_t uuid_list[32 * Uuid::kNumBytes16];
1418
1419 if (p_search_data->inq_res.inq_result_type != BT_DEVICE_TYPE_BLE) {
1420 p_search_data->inq_res.remt_name_not_required =
1421 check_eir_remote_name(p_search_data, NULL, NULL);
1422 }
1423 RawAddress& bdaddr = p_search_data->inq_res.bd_addr;
1424
1425 log::verbose("addr:{} device_type=0x{:x}", bdaddr,
1426 p_search_data->inq_res.device_type);
1427 bdname.name[0] = 0;
1428
1429 if (!check_eir_remote_name(p_search_data, bdname.name, &remote_name_len))
1430 get_cached_remote_name(p_search_data->inq_res.bd_addr, bdname.name,
1431 &remote_name_len);
1432
1433 /* Check EIR for services */
1434 if (p_search_data->inq_res.p_eir) {
1435 if (!get_btm_client_interface().eir.BTM_GetEirUuidList(
1436 p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len,
1437 Uuid::kNumBytes16, &num_uuids, uuid_list, max_num_uuid)) {
1438 log::debug("Unable to find service uuids in EIR peer:{}", bdaddr);
1439 }
1440 }
1441
1442 {
1443 std::vector<bt_property_t> bt_properties;
1444 uint32_t dev_type;
1445 uint32_t num_properties = 0;
1446 bt_status_t status;
1447 tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
1448
1449 /* RawAddress */
1450 bt_properties.push_back(
1451 bt_property_t{BT_PROPERTY_BDADDR, sizeof(bdaddr), &bdaddr});
1452
1453 /* BD_NAME */
1454 /* Don't send BDNAME if it is empty */
1455 if (bdname.name[0]) {
1456 bt_properties.push_back(bt_property_t{
1457 BT_PROPERTY_BDNAME, static_cast<int>(strlen((char*)bdname.name)),
1458 &bdname});
1459 }
1460
1461 /* DEV_CLASS */
1462 uint32_t cod = devclass2uint(p_search_data->inq_res.dev_class);
1463
1464 if (cod != 0) {
1465 /* Use the existing class of device when the one reported from inquiry
1466 is unclassified. Inquiry results coming from BLE can have an
1467 inferred device class based on the service uuids or appearence. We
1468 don't want this to replace the existing value below when we call
1469 btif_storage_add_remote_device */
1470 uint32_t old_cod = get_cod(&bdaddr);
1471 if (com::android::bluetooth::flags::
1472 do_not_replace_existing_cod_with_uncategorized_cod()) {
1473 if (cod == COD_UNCLASSIFIED && old_cod != 0) {
1474 cod = old_cod;
1475 }
1476 }
1477
1478 if (old_cod != cod) {
1479 log::info("{} CoD: 0x{:06x} -> 0x{:06x}", bdaddr, old_cod, cod);
1480 }
1481 bt_properties.push_back(
1482 bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod});
1483 }
1484
1485 log::verbose("clock_offset is 0x{:x}",
1486 p_search_data->inq_res.clock_offset);
1487 if (p_search_data->inq_res.clock_offset & BTM_CLOCK_OFFSET_VALID) {
1488 btif_set_device_clockoffset(bdaddr, (int)p_search_data->inq_res.clock_offset);
1489 }
1490
1491 /* DEV_TYPE */
1492 /* FixMe: Assumption is that bluetooth.h and BTE enums match */
1493
1494 /* Verify if the device is dual mode in NVRAM */
1495 int stored_device_type = 0;
1496 if (btif_get_device_type(bdaddr, &stored_device_type) &&
1497 ((stored_device_type != BT_DEVICE_TYPE_BREDR &&
1498 p_search_data->inq_res.device_type == BT_DEVICE_TYPE_BREDR) ||
1499 (stored_device_type != BT_DEVICE_TYPE_BLE &&
1500 p_search_data->inq_res.device_type == BT_DEVICE_TYPE_BLE))) {
1501 dev_type = (bt_device_type_t)BT_DEVICE_TYPE_DUMO;
1502 } else {
1503 dev_type = (bt_device_type_t)p_search_data->inq_res.device_type;
1504 }
1505
1506 if (p_search_data->inq_res.device_type == BT_DEVICE_TYPE_BLE) {
1507 addr_type = p_search_data->inq_res.ble_addr_type;
1508 }
1509 bt_properties.push_back(bt_property_t{BT_PROPERTY_TYPE_OF_DEVICE,
1510 sizeof(dev_type), &dev_type});
1511 /* RSSI */
1512 bt_properties.push_back(bt_property_t{BT_PROPERTY_REMOTE_RSSI,
1513 sizeof(int8_t),
1514 &(p_search_data->inq_res.rssi)});
1515
1516 /* CSIP supported device */
1517 bt_properties.push_back(
1518 bt_property_t{BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER,
1519 sizeof(bool), &(p_search_data->inq_res.include_rsi)});
1520
1521 // The default negative value means ASHA capability not found.
1522 // A non-negative value represents ASHA capability information is valid.
1523 // Because ASHA's capability is 1 byte, so int16_t is large enough.
1524 int16_t asha_capability = -1;
1525
1526 // contains ASHA truncated HiSyncId if asha_capability is non-negative
1527 uint32_t asha_truncated_hi_sync_id = 0;
1528
1529 get_asha_service_data(p_search_data->inq_res, asha_capability,
1530 asha_truncated_hi_sync_id);
1531
1532 bt_properties.push_back(
1533 bt_property_t{BT_PROPERTY_REMOTE_ASHA_CAPABILITY, sizeof(int16_t),
1534 &asha_capability});
1535
1536 bt_properties.push_back(
1537 bt_property_t{BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID,
1538 sizeof(uint32_t), &asha_truncated_hi_sync_id});
1539
1540 // Floss expects that EIR uuids are immediately reported when the
1541 // device is found and doesn't wait for the pairing intent.
1542 //
1543 // If a subsequent SDP is completed, the new UUIDs should replace
1544 // the existing UUIDs.
1545 #if TARGET_FLOSS
1546 bool report_eir_uuids = true;
1547 #else
1548 bool report_eir_uuids = false;
1549 #endif
1550 // Scope needs to persist until `invoke_device_found_cb` below.
1551 std::vector<uint8_t> property_value;
1552 /* Cache EIR queried services */
1553 if (num_uuids > 0) {
1554 uint16_t* p_uuid16 = (uint16_t*)uuid_list;
1555 auto uuid_iter = eir_uuids_cache.find(bdaddr);
1556 if (uuid_iter == eir_uuids_cache.end()) {
1557 auto triple = eir_uuids_cache.try_emplace(bdaddr, std::set<Uuid>{});
1558 uuid_iter = std::get<0>(triple);
1559 }
1560 log::info("EIR UUIDs for {}:", bdaddr);
1561 for (int i = 0; i < num_uuids; ++i) {
1562 Uuid uuid = Uuid::From16Bit(p_uuid16[i]);
1563 log::info("{}", uuid.ToString());
1564 uuid_iter->second.insert(uuid);
1565 }
1566
1567 if (report_eir_uuids) {
1568 for (auto uuid : uuid_iter->second) {
1569 auto uuid_128bit = uuid.To128BitBE();
1570 property_value.insert(property_value.end(), uuid_128bit.begin(),
1571 uuid_128bit.end());
1572 }
1573
1574 bt_properties.push_back(bt_property_t{
1575 BT_PROPERTY_UUIDS,
1576 static_cast<int>(uuid_iter->second.size() * Uuid::kNumBytes128),
1577 (void*)property_value.data()});
1578 }
1579 }
1580
1581 // Floss needs appearance for metrics purposes
1582 uint16_t appearance = 0;
1583 if (check_eir_appearance(p_search_data, &appearance)) {
1584 bt_properties.push_back(bt_property_t{
1585 BT_PROPERTY_APPEARANCE, sizeof(appearance), &appearance});
1586 }
1587
1588 status = btif_storage_add_remote_device(&bdaddr, bt_properties.size(),
1589 bt_properties.data());
1590 ASSERTC(status == BT_STATUS_SUCCESS,
1591 "failed to save remote device (inquiry)", status);
1592 status = btif_storage_set_remote_addr_type(&bdaddr, addr_type);
1593 ASSERTC(status == BT_STATUS_SUCCESS,
1594 "failed to save remote addr type (inquiry)", status);
1595
1596 bool restrict_report = osi_property_get_bool(
1597 "bluetooth.restrict_discovered_device.enabled", false);
1598 if (restrict_report &&
1599 p_search_data->inq_res.device_type == BT_DEVICE_TYPE_BLE &&
1600 !(p_search_data->inq_res.ble_evt_type & BTM_BLE_CONNECTABLE_MASK)) {
1601 log::debug("Ble device {} is not connectable", bdaddr);
1602 break;
1603 }
1604
1605 /* Callback to notify upper layer of device */
1606 GetInterfaceToProfiles()->events->invoke_device_found_cb(
1607 bt_properties.size(), bt_properties.data());
1608 }
1609 } break;
1610
1611 case BTA_DM_DISC_CMPL_EVT: {
1612 GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(
1613 BT_DISCOVERY_STOPPED);
1614 } break;
1615 case BTA_DM_SEARCH_CANCEL_CMPL_EVT: {
1616 /* if inquiry is not in progress and we get a cancel event, then
1617 * it means we are done with inquiry, but remote_name fetches are in
1618 * progress
1619 *
1620 * if inquiry is in progress, then we don't want to act on this
1621 * cancel_cmpl_evt
1622 * but instead wait for the cancel_cmpl_evt via the Busy Level
1623 *
1624 */
1625 if (!btif_dm_inquiry_in_progress) {
1626 GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(
1627 BT_DISCOVERY_STOPPED);
1628 }
1629 } break;
1630 default:
1631 log::warn("Unhandled event:{}", bta_dm_search_evt_text(event));
1632 break;
1633 }
1634 }
1635
1636 /* Returns true if |uuid| should be passed as device property */
btif_is_interesting_le_service(bluetooth::Uuid uuid)1637 static bool btif_is_interesting_le_service(bluetooth::Uuid uuid) {
1638 return (uuid.As16Bit() == UUID_SERVCLASS_LE_HID || uuid == UUID_HEARING_AID ||
1639 uuid == UUID_VC || uuid == UUID_CSIS || uuid == UUID_LE_AUDIO ||
1640 uuid == UUID_LE_MIDI || uuid == UUID_HAS || uuid == UUID_BASS ||
1641 uuid == UUID_BATTERY ||
1642 (com::android::bluetooth::flags::android_headtracker_service() &&
1643 uuid == ANDROID_HEADTRACKER_SERVICE_UUID));
1644 }
1645
btif_get_existing_uuids(RawAddress * bd_addr,Uuid * existing_uuids)1646 static bt_status_t btif_get_existing_uuids(RawAddress* bd_addr,
1647 Uuid* existing_uuids) {
1648 bt_property_t tmp_prop;
1649 BTIF_STORAGE_FILL_PROPERTY(&tmp_prop, BT_PROPERTY_UUIDS,
1650 sizeof(existing_uuids), existing_uuids);
1651
1652 return btif_storage_get_remote_device_property(bd_addr, &tmp_prop);
1653 }
1654
btif_should_ignore_uuid(const Uuid & uuid)1655 static bool btif_should_ignore_uuid(const Uuid& uuid) {
1656 return uuid.IsEmpty() || uuid.IsBase();
1657 }
1658
btif_is_gatt_service_discovery_post_pairing(const RawAddress bd_addr)1659 static bool btif_is_gatt_service_discovery_post_pairing(const RawAddress bd_addr) {
1660 if (!com::android::bluetooth::flags::
1661 reset_pairing_only_for_related_service_discovery()) {
1662 if (bd_addr == pairing_cb.bd_addr || bd_addr == pairing_cb.static_bdaddr) {
1663 if (pairing_cb.gatt_over_le !=
1664 btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED) {
1665 log::error(
1666 "gatt_over_le should be SCHEDULED, did someone clear the control "
1667 "block for {} ?",
1668 bd_addr);
1669 }
1670
1671 return true;
1672 }
1673
1674 return false;
1675 }
1676
1677 return ((bd_addr == pairing_cb.bd_addr ||
1678 bd_addr == pairing_cb.static_bdaddr) &&
1679 (pairing_cb.gatt_over_le ==
1680 btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED));
1681 }
1682
btif_merge_existing_uuids(RawAddress & addr,std::set<Uuid> * uuids)1683 static void btif_merge_existing_uuids(RawAddress& addr, std::set<Uuid>* uuids) {
1684 Uuid existing_uuids[BT_MAX_NUM_UUIDS] = {};
1685 bt_status_t lookup_result = btif_get_existing_uuids(&addr, existing_uuids);
1686
1687 if (lookup_result == BT_STATUS_FAIL) return;
1688
1689 for (int i = 0; i < BT_MAX_NUM_UUIDS; i++) {
1690 Uuid uuid = existing_uuids[i];
1691 if (btif_should_ignore_uuid(uuid)) {
1692 continue;
1693 }
1694 if (btif_is_interesting_le_service(uuid)) {
1695 log::info("interesting le service {} insert", uuid.ToString());
1696 uuids->insert(uuid);
1697 }
1698 }
1699 }
1700
btif_on_service_discovery_results(RawAddress bd_addr,const std::vector<bluetooth::Uuid> & uuids_param,tBTA_STATUS result)1701 static void btif_on_service_discovery_results(
1702 RawAddress bd_addr, const std::vector<bluetooth::Uuid>& uuids_param,
1703 tBTA_STATUS result) {
1704 bt_property_t prop;
1705 std::vector<uint8_t> property_value;
1706 std::set<Uuid> uuids;
1707 bool a2dp_sink_capable = false;
1708
1709 bool results_for_bonding_device =
1710 (bd_addr == pairing_cb.bd_addr || bd_addr == pairing_cb.static_bdaddr);
1711
1712 if (results_for_bonding_device && result != BTA_SUCCESS &&
1713 pairing_cb.state == BT_BOND_STATE_BONDED &&
1714 pairing_cb.sdp_attempts < BTIF_DM_MAX_SDP_ATTEMPTS_AFTER_PAIRING) {
1715 if (pairing_cb.sdp_attempts) {
1716 log::warn("SDP failed after bonding re-attempting for {}", bd_addr);
1717 pairing_cb.sdp_attempts++;
1718 if (com::android::bluetooth::flags::force_bredr_for_sdp_retry()) {
1719 btif_dm_get_remote_services(bd_addr, BT_TRANSPORT_BR_EDR);
1720 } else {
1721 btif_dm_get_remote_services(bd_addr, BT_TRANSPORT_AUTO);
1722 }
1723 } else {
1724 log::warn("SDP triggered by someone failed when bonding");
1725 }
1726 return;
1727 }
1728
1729 if (results_for_bonding_device) {
1730 log::info("SDP finished for {}:", bd_addr);
1731 pairing_cb.sdp_over_classic =
1732 btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED;
1733 }
1734
1735 prop.type = BT_PROPERTY_UUIDS;
1736 prop.len = 0;
1737 if ((result == BTA_SUCCESS) && !uuids_param.empty()) {
1738 log::info("New UUIDs for {}:", bd_addr);
1739 for (const auto& uuid : uuids_param) {
1740 if (btif_should_ignore_uuid(uuid)) {
1741 continue;
1742 }
1743 log::info("uuid:{}", uuid.ToString());
1744 uuids.insert(uuid);
1745 }
1746
1747 if (results_for_bonding_device) {
1748 btif_merge_existing_uuids(pairing_cb.static_bdaddr, &uuids);
1749 btif_merge_existing_uuids(pairing_cb.bd_addr, &uuids);
1750 } else {
1751 btif_merge_existing_uuids(bd_addr, &uuids);
1752 }
1753
1754 for (auto& uuid : uuids) {
1755 auto uuid_128bit = uuid.To128BitBE();
1756 property_value.insert(property_value.end(), uuid_128bit.begin(),
1757 uuid_128bit.end());
1758 if (uuid == UUID_A2DP_SINK) {
1759 a2dp_sink_capable = true;
1760 }
1761 }
1762 prop.val = (void*)property_value.data();
1763 prop.len = Uuid::kNumBytes128 * uuids.size();
1764 }
1765
1766 bool skip_reporting_wait_for_le = false;
1767 /* If we are doing service discovery for device that just bonded, that is
1768 * capable of a2dp, and both sides can do LE Audio, and it haven't
1769 * finished GATT over LE yet, then wait for LE service discovery to finish
1770 * before before passing services to upper layers. */
1771 if (results_for_bonding_device && a2dp_sink_capable &&
1772 pairing_cb.gatt_over_le !=
1773 btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED &&
1774 is_le_audio_capable_during_service_discovery(bd_addr)) {
1775 skip_reporting_wait_for_le = true;
1776 }
1777
1778 /* onUuidChanged requires getBondedDevices to be populated.
1779 ** bond_state_changed needs to be sent prior to remote_device_property
1780 */
1781 size_t num_eir_uuids = 0U;
1782 Uuid uuid = {};
1783 if (results_for_bonding_device && pairing_cb.state == BT_BOND_STATE_BONDED &&
1784 pairing_cb.sdp_attempts) {
1785 log::info("SDP search done for {}", bd_addr);
1786 pairing_cb.sdp_attempts = 0;
1787
1788 // Send UUIDs discovered through EIR to Java to unblock pairing intent
1789 // when SDP failed
1790 if (result != BTA_SUCCESS) {
1791 auto uuids_iter = eir_uuids_cache.find(bd_addr);
1792 if (uuids_iter != eir_uuids_cache.end()) {
1793 num_eir_uuids = uuids_iter->second.size();
1794 log::info("SDP failed, send {} EIR UUIDs to unblock bonding {}",
1795 num_eir_uuids, bd_addr);
1796 for (auto eir_uuid : uuids_iter->second) {
1797 auto uuid_128bit = eir_uuid.To128BitBE();
1798 property_value.insert(property_value.end(), uuid_128bit.begin(),
1799 uuid_128bit.end());
1800 }
1801 eir_uuids_cache.erase(uuids_iter);
1802 }
1803 if (num_eir_uuids > 0) {
1804 prop.val = (void*)property_value.data();
1805 prop.len = num_eir_uuids * Uuid::kNumBytes128;
1806 } else {
1807 log::warn("SDP failed and we have no EIR UUIDs to report either");
1808 prop.val = &uuid;
1809 prop.len = Uuid::kNumBytes128;
1810 }
1811 }
1812
1813 if (!skip_reporting_wait_for_le) {
1814 // Both SDP and bonding are done, clear pairing control block in case
1815 // it is not already cleared
1816 pairing_cb = {};
1817 log::debug("clearing btif pairing_cb");
1818 }
1819 }
1820
1821 const tBTA_STATUS bta_status = result;
1822 BTM_LogHistory(kBtmLogTagSdp, bd_addr, "Discovered services",
1823 base::StringPrintf("bta_status:%s sdp_uuids:%zu eir_uuids:%zu",
1824 bta_status_text(bta_status).c_str(),
1825 uuids_param.size(), num_eir_uuids));
1826
1827 if (!uuids_param.empty() || num_eir_uuids != 0) {
1828 /* Also write this to the NVRAM */
1829 const bt_status_t ret =
1830 btif_storage_set_remote_device_property(&bd_addr, &prop);
1831 ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret);
1832
1833 if (skip_reporting_wait_for_le) {
1834 log::info(
1835 "Bonding LE Audio sink - must wait for le services discovery to pass "
1836 "all services to java {}",
1837 bd_addr);
1838 /* For LE Audio capable devices, we care more about passing GATT LE
1839 * services than about just finishing pairing. Service discovery
1840 * should be scheduled when LE pairing finishes, by call to
1841 * btif_dm_get_remote_services(bd_addr, BT_TRANSPORT_LE) */
1842 return;
1843 }
1844
1845 /* Send the event to the BTIF */
1846 GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
1847 BT_STATUS_SUCCESS, bd_addr, 1, &prop);
1848 }
1849 }
1850
btif_on_gatt_results(RawAddress bd_addr,BD_NAME bd_name,std::vector<bluetooth::Uuid> & services,bool transport_le)1851 void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name,
1852 std::vector<bluetooth::Uuid>& services,
1853 bool transport_le) {
1854 std::vector<bt_property_t> prop;
1855 std::vector<uint8_t> property_value;
1856 std::set<Uuid> uuids;
1857 RawAddress static_addr_copy = pairing_cb.static_bdaddr;
1858 bool lea_supported = is_le_audio_capable_during_service_discovery(bd_addr);
1859
1860 if (transport_le) {
1861 log::info("New GATT over LE UUIDs for {}:", bd_addr);
1862 BTM_LogHistory(kBtmLogTag, bd_addr,
1863 "Discovered GATT services using LE transport");
1864 if (btif_is_gatt_service_discovery_post_pairing(bd_addr)) {
1865 pairing_cb.gatt_over_le =
1866 btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED;
1867
1868 if (pairing_cb.sdp_over_classic !=
1869 btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED) {
1870 // Both SDP and bonding are either done, or not scheduled,
1871 // we are safe to clear the service discovery part of CB.
1872 log::debug("clearing pairing_cb");
1873 pairing_cb = {};
1874 }
1875
1876 if (lea_supported) {
1877 /* LE Audio profile should relax parameters when it connects. If
1878 * profile is not enabled, relax parameters after timeout. */
1879 log::debug("Scheduling conn params unlock for {}", bd_addr);
1880 do_in_main_thread_delayed(
1881 FROM_HERE,
1882 base::BindOnce(
1883 [](RawAddress bd_addr) {
1884 L2CA_LockBleConnParamsForProfileConnection(bd_addr, false);
1885 },
1886 bd_addr),
1887 std::chrono::seconds(15));
1888 }
1889 }
1890 } else {
1891 log::debug("New GATT over SDP UUIDs for {}:", bd_addr);
1892 BTM_LogHistory(kBtmLogTag, bd_addr,
1893 "Discovered GATT services using SDP transport");
1894 }
1895
1896 for (Uuid uuid : services) {
1897 if (btif_is_interesting_le_service(uuid)) {
1898 if (btif_should_ignore_uuid(uuid)) {
1899 continue;
1900 }
1901 log::info("index:{} uuid:{}", static_cast<int>(uuids.size()),
1902 uuid.ToString());
1903 uuids.insert(uuid);
1904 }
1905 }
1906
1907 if (uuids.empty()) {
1908 log::info("No well known GATT services discovered");
1909
1910 /* If services were returned as part of SDP discovery, we will
1911 * immediately send them with rest of SDP results in
1912 * on_service_discovery_results
1913 */
1914 if (!transport_le) {
1915 return;
1916 }
1917
1918 if (lea_supported) {
1919 if (bluetooth::common::init_flags::
1920 sdp_return_classic_services_when_le_discovery_fails_is_enabled()) {
1921 log::info(
1922 "Will return Classic SDP results, if done, to unblock bonding");
1923 } else {
1924 // LEA device w/o this flag
1925 // TODO: we might want to remove bond or do some action on
1926 // half-discovered device
1927 log::warn("No GATT service found for the LE Audio device {}", bd_addr);
1928 return;
1929 }
1930 } else {
1931 log::info("LE audio not supported, no need to report any UUIDs");
1932 return;
1933 }
1934 }
1935
1936 Uuid existing_uuids[BT_MAX_NUM_UUIDS] = {};
1937
1938 // Look up UUIDs using pseudo address (either RPA or static address)
1939 bt_status_t existing_lookup_result =
1940 btif_get_existing_uuids(&bd_addr, existing_uuids);
1941
1942 if (existing_lookup_result != BT_STATUS_FAIL) {
1943 log::info("Got some existing UUIDs by address {}", bd_addr);
1944
1945 for (int i = 0; i < BT_MAX_NUM_UUIDS; i++) {
1946 Uuid uuid = existing_uuids[i];
1947 if (uuid.IsEmpty()) {
1948 continue;
1949 }
1950 uuids.insert(uuid);
1951 }
1952 }
1953
1954 if (bd_addr != static_addr_copy) {
1955 // Look up UUID using static address, if different than sudo address
1956 existing_lookup_result =
1957 btif_get_existing_uuids(&static_addr_copy, existing_uuids);
1958 if (existing_lookup_result != BT_STATUS_FAIL) {
1959 log::info("Got some existing UUIDs by static address {}",
1960 static_addr_copy);
1961 for (int i = 0; i < BT_MAX_NUM_UUIDS; i++) {
1962 Uuid uuid = existing_uuids[i];
1963 if (uuid.IsEmpty()) {
1964 continue;
1965 }
1966 uuids.insert(uuid);
1967 }
1968 }
1969 }
1970
1971 for (auto& uuid : uuids) {
1972 auto uuid_128bit = uuid.To128BitBE();
1973 property_value.insert(property_value.end(), uuid_128bit.begin(),
1974 uuid_128bit.end());
1975 }
1976
1977 prop.push_back(bt_property_t{
1978 BT_PROPERTY_UUIDS, static_cast<int>(Uuid::kNumBytes128 * uuids.size()),
1979 (void*)property_value.data()});
1980
1981 /* Also write this to the NVRAM */
1982 bt_status_t ret = btif_storage_set_remote_device_property(&bd_addr, &prop[0]);
1983 ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret);
1984
1985 /* Remote name update */
1986 if (!com::android::bluetooth::flags::
1987 separate_service_and_device_discovery() &&
1988 strnlen((const char*)bd_name, BD_NAME_LEN)) {
1989 prop.push_back(bt_property_t{
1990 BT_PROPERTY_BDNAME,
1991 static_cast<int>(strnlen((char*)bd_name, BD_NAME_LEN)), bd_name});
1992
1993 ret = btif_storage_set_remote_device_property(&bd_addr, &prop[1]);
1994 ASSERTC(ret == BT_STATUS_SUCCESS, "failed to save remote device property",
1995 ret);
1996 }
1997
1998 if (!transport_le) {
1999 /* If services were returned as part of SDP discovery, we will immediately
2000 * send them with rest of SDP results in on_service_discovery_results */
2001 return;
2002 } else {
2003 if (pairing_cb.sdp_over_classic ==
2004 btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED &&
2005 com::android::bluetooth::flags::bta_dm_discover_both()) {
2006 /* Don't report services yet, they will be reported together once SDP
2007 * finishes. */
2008 log::info("will report services later, with SDP results {}", bd_addr);
2009 return;
2010 }
2011 }
2012
2013 /* Send the event to the BTIF */
2014 GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
2015 BT_STATUS_SUCCESS, bd_addr, prop.size(), prop.data());
2016 }
2017
btif_on_name_read(RawAddress bd_addr,tHCI_ERROR_CODE hci_status,const BD_NAME bd_name,bool during_device_search)2018 static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status,
2019 const BD_NAME bd_name,
2020 bool during_device_search) {
2021 // Differentiate between merged callbacks
2022 if (!during_device_search
2023 // New fix after refactor, this callback is needed for the fix to work
2024 &&
2025 !com::android::bluetooth::flags::separate_service_and_device_discovery()
2026 // Original fix, this callback should not be called if RNR should not be
2027 // called
2028 &&
2029 !com::android::bluetooth::flags::rnr_present_during_service_discovery()) {
2030 log::info("Skipping name read event - called on bad callback.");
2031 return;
2032 }
2033
2034 if (hci_status != HCI_SUCCESS) {
2035 log::warn("Received RNR event with bad status addr:{} hci_status:{}",
2036 bd_addr, hci_error_code_text(hci_status));
2037 return;
2038 }
2039 if (bd_name[0] == '\0') {
2040 log::warn("Received RNR event without valid name addr:{}", bd_addr);
2041 return;
2042 }
2043
2044 // Needs 3 properties if during_device_search is true
2045 std::vector<bt_property_t> properties;
2046
2047 properties.push_back(
2048 bt_property_t{BT_PROPERTY_BDNAME,
2049 static_cast<int>(strnlen((char*)bd_name, BD_NAME_LEN)),
2050 (void*)(bd_name)});
2051
2052 const bt_status_t status =
2053 btif_storage_set_remote_device_property(&bd_addr, properties.data());
2054 log::assert_that(status == BT_STATUS_SUCCESS,
2055 "Failed to save remote device property status:{}",
2056 bt_status_text(status));
2057 GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
2058 status, bd_addr, properties.size(), properties.data());
2059 log::info("Callback for read name event addr:{} name:{}", bd_addr,
2060 PRIVATE_NAME(reinterpret_cast<char const*>(bd_name)));
2061
2062 if (!during_device_search) {
2063 return;
2064 }
2065
2066 uint32_t cod = get_cod(&bd_addr);
2067 if (cod != 0) {
2068 properties.push_back(
2069 bt_property_t{BT_PROPERTY_BDADDR, sizeof(bd_addr), &bd_addr});
2070 properties.push_back(
2071 bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(uint32_t), &cod});
2072 log::debug("report new device to JNI");
2073 GetInterfaceToProfiles()->events->invoke_device_found_cb(properties.size(),
2074 properties.data());
2075 } else {
2076 log::info(
2077 "Skipping device found callback because cod is zero addr:{} name:{}",
2078 bd_addr, PRIVATE_NAME(reinterpret_cast<char const*>(bd_name)));
2079 }
2080 }
2081
btif_on_name_read_from_btm(const RawAddress & bd_addr,DEV_CLASS,BD_NAME bd_name)2082 void btif_on_name_read_from_btm(const RawAddress& bd_addr, DEV_CLASS /* dc */,
2083 BD_NAME bd_name) {
2084 log::info("{} {}", bd_addr, reinterpret_cast<char const*>(bd_name));
2085 btif_on_name_read(bd_addr, HCI_SUCCESS, bd_name,
2086 false /* duirng_device_search */);
2087 }
2088
btif_on_did_received(RawAddress bd_addr,uint8_t vendor_id_src,uint16_t vendor_id,uint16_t product_id,uint16_t version)2089 void btif_on_did_received(RawAddress bd_addr, uint8_t vendor_id_src,
2090 uint16_t vendor_id, uint16_t product_id,
2091 uint16_t version) {
2092 bt_vendor_product_info_t vp_info{
2093 .vendor_id_src = vendor_id_src,
2094 .vendor_id = vendor_id,
2095 .product_id = product_id,
2096 .version = version,
2097 };
2098
2099 bt_property_t prop_did{
2100 .type = BT_PROPERTY_VENDOR_PRODUCT_INFO,
2101 .len = sizeof(vp_info),
2102 .val = &vp_info,
2103 };
2104
2105 bt_status_t ret =
2106 btif_storage_set_remote_device_property(&bd_addr, &prop_did);
2107 ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret);
2108
2109 /* Send the event to the BTIF */
2110 GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
2111 BT_STATUS_SUCCESS, bd_addr, 1, &prop_did);
2112 }
2113
BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE status)2114 void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE status) {
2115 btif_dm_inquiry_in_progress =
2116 (status == tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED);
2117
2118 if (status == tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED) {
2119 GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(
2120 BT_DISCOVERY_STARTED);
2121 } else if (status == tBTM_INQUIRY_STATE::BTM_INQUIRY_CANCELLED) {
2122 GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(
2123 BT_DISCOVERY_STOPPED);
2124 }
2125 }
2126
BTIF_dm_enable()2127 void BTIF_dm_enable() {
2128 BD_NAME bdname;
2129 bt_status_t status;
2130 bt_property_t prop;
2131 prop.type = BT_PROPERTY_BDNAME;
2132 prop.len = BD_NAME_LEN;
2133 prop.val = (void*)bdname;
2134
2135 status = btif_storage_get_adapter_property(&prop);
2136 if (status == BT_STATUS_SUCCESS) {
2137 /* A name exists in the storage. Make this the device name */
2138 BTA_DmSetDeviceName((const char*)prop.val);
2139 } else {
2140 /* Storage does not have a name yet.
2141 * Use the default name and write it to the chip
2142 */
2143 BTA_DmSetDeviceName(btif_get_default_local_name());
2144 }
2145
2146 /* Enable or disable local privacy */
2147 bool ble_privacy_enabled =
2148 osi_property_get_bool(PROPERTY_BLE_PRIVACY_ENABLED, /*default=*/true);
2149
2150 log::info("Local BLE Privacy enabled:{}", ble_privacy_enabled);
2151 BTA_DmBleConfigLocalPrivacy(ble_privacy_enabled);
2152
2153 if (com::android::bluetooth::flags::separate_service_and_device_discovery()) {
2154 BTM_SecAddRmtNameNotifyCallback(btif_on_name_read_from_btm);
2155 }
2156
2157 /* for each of the enabled services in the mask, trigger the profile
2158 * enable */
2159 tBTA_SERVICE_MASK service_mask = btif_get_enabled_services_mask();
2160 for (uint32_t i = 0; i <= BTA_MAX_SERVICE_ID; i++) {
2161 if (service_mask & (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(i))) {
2162 btif_in_execute_service_request(i, true);
2163 }
2164 }
2165 /* clear control blocks */
2166 pairing_cb = {};
2167 pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
2168
2169 // Enable address consolidation.
2170 btif_storage_load_le_devices();
2171
2172 /* This function will also trigger the adapter_properties_cb
2173 ** and bonded_devices_info_cb
2174 */
2175 btif_storage_load_bonded_devices();
2176 bluetooth::bqr::EnableBtQualityReport(get_main());
2177 btif_enable_bluetooth_evt();
2178 }
2179
BTIF_dm_disable()2180 void BTIF_dm_disable() {
2181 if (com::android::bluetooth::flags::separate_service_and_device_discovery()) {
2182 BTM_SecDeleteRmtNameNotifyCallback(&btif_on_name_read_from_btm);
2183 }
2184
2185 /* for each of the enabled services in the mask, trigger the profile
2186 * disable */
2187 tBTA_SERVICE_MASK service_mask = btif_get_enabled_services_mask();
2188 for (uint32_t i = 0; i <= BTA_MAX_SERVICE_ID; i++) {
2189 if (service_mask & (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(i))) {
2190 btif_in_execute_service_request(i, false);
2191 }
2192 }
2193 bluetooth::bqr::EnableBtQualityReport(nullptr);
2194 log::info("Stack device manager shutdown finished");
2195 future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
2196 }
2197
2198 /*******************************************************************************
2199 *
2200 * Function btif_dm_sec_evt
2201 *
2202 * Description Executes security related events
2203 *
2204 * Returns void
2205 *
2206 ******************************************************************************/
btif_dm_sec_evt(tBTA_DM_SEC_EVT event,tBTA_DM_SEC * p_data)2207 void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) {
2208 RawAddress bd_addr;
2209
2210 log::verbose("ev:{}", dump_dm_event(event));
2211
2212 switch (event) {
2213 case BTA_DM_PIN_REQ_EVT:
2214 btif_dm_pin_req_evt(&p_data->pin_req);
2215 break;
2216
2217 case BTA_DM_AUTH_CMPL_EVT:
2218 btif_dm_auth_cmpl_evt(&p_data->auth_cmpl);
2219 break;
2220
2221 case BTA_DM_BOND_CANCEL_CMPL_EVT:
2222 if (is_bonding_or_sdp()) {
2223 bd_addr = pairing_cb.bd_addr;
2224 btm_set_bond_type_dev(pairing_cb.bd_addr, BOND_TYPE_UNKNOWN);
2225 bond_state_changed((bt_status_t)p_data->bond_cancel_cmpl.result,
2226 bd_addr, BT_BOND_STATE_NONE);
2227 }
2228 break;
2229
2230 case BTA_DM_SP_CFM_REQ_EVT:
2231 btif_dm_ssp_cfm_req_evt(&p_data->cfm_req);
2232 break;
2233 case BTA_DM_SP_KEY_NOTIF_EVT:
2234 btif_dm_ssp_key_notif_evt(&p_data->key_notif);
2235 break;
2236
2237 case BTA_DM_DEV_UNPAIRED_EVT:
2238 bd_addr = p_data->dev_unpair.bd_addr;
2239 btm_set_bond_type_dev(p_data->dev_unpair.bd_addr, BOND_TYPE_UNKNOWN);
2240
2241 GetInterfaceToProfiles()->removeDeviceFromProfiles(bd_addr);
2242 btif_storage_remove_bonded_device(&bd_addr);
2243 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_NONE);
2244 break;
2245
2246 case BTA_DM_BLE_KEY_EVT:
2247 log::verbose("BTA_DM_BLE_KEY_EVT key_type=0x{:02x}",
2248 p_data->ble_key.key_type);
2249
2250 /* If this pairing is by-product of local initiated GATT client Read or
2251 Write,
2252 BTA would not have sent BTA_DM_BLE_SEC_REQ_EVT event and Bond state would
2253 not
2254 have setup properly. Setup pairing_cb and notify App about Bonding state
2255 now*/
2256 if (pairing_cb.state != BT_BOND_STATE_BONDING) {
2257 log::verbose("Bond state not sent to App so far.Notify the app now");
2258 bond_state_changed(BT_STATUS_SUCCESS, p_data->ble_key.bd_addr,
2259 BT_BOND_STATE_BONDING);
2260 } else if (pairing_cb.bd_addr != p_data->ble_key.bd_addr) {
2261 log::error("BD mismatch discard BLE key_type={}",
2262 p_data->ble_key.key_type);
2263 break;
2264 }
2265
2266 switch (p_data->ble_key.key_type) {
2267 case BTM_LE_KEY_PENC:
2268 log::verbose("Rcv BTM_LE_KEY_PENC");
2269 pairing_cb.ble.is_penc_key_rcvd = true;
2270 pairing_cb.ble.penc_key = p_data->ble_key.p_key_value->penc_key;
2271 break;
2272
2273 case BTM_LE_KEY_PID:
2274 log::verbose("Rcv BTM_LE_KEY_PID");
2275 pairing_cb.ble.is_pid_key_rcvd = true;
2276 pairing_cb.ble.pid_key = p_data->ble_key.p_key_value->pid_key;
2277 break;
2278
2279 case BTM_LE_KEY_PCSRK:
2280 log::verbose("Rcv BTM_LE_KEY_PCSRK");
2281 pairing_cb.ble.is_pcsrk_key_rcvd = true;
2282 pairing_cb.ble.pcsrk_key = p_data->ble_key.p_key_value->pcsrk_key;
2283 break;
2284
2285 case BTM_LE_KEY_LENC:
2286 log::verbose("Rcv BTM_LE_KEY_LENC");
2287 pairing_cb.ble.is_lenc_key_rcvd = true;
2288 pairing_cb.ble.lenc_key = p_data->ble_key.p_key_value->lenc_key;
2289 break;
2290
2291 case BTM_LE_KEY_LCSRK:
2292 log::verbose("Rcv BTM_LE_KEY_LCSRK");
2293 pairing_cb.ble.is_lcsrk_key_rcvd = true;
2294 pairing_cb.ble.lcsrk_key = p_data->ble_key.p_key_value->lcsrk_key;
2295 break;
2296
2297 case BTM_LE_KEY_LID:
2298 log::verbose("Rcv BTM_LE_KEY_LID");
2299 pairing_cb.ble.is_lidk_key_rcvd = true;
2300 break;
2301
2302 default:
2303 log::error("unknown BLE key type (0x{:02x})",
2304 p_data->ble_key.key_type);
2305 break;
2306 }
2307 break;
2308 case BTA_DM_BLE_CONSENT_REQ_EVT:
2309 log::verbose("BTA_DM_BLE_CONSENT_REQ_EVT");
2310 btif_dm_ble_sec_req_evt(&p_data->ble_req, true);
2311 break;
2312 case BTA_DM_BLE_SEC_REQ_EVT:
2313 log::verbose("BTA_DM_BLE_SEC_REQ_EVT");
2314 btif_dm_ble_sec_req_evt(&p_data->ble_req, false);
2315 break;
2316 case BTA_DM_BLE_PASSKEY_NOTIF_EVT:
2317 log::verbose("BTA_DM_BLE_PASSKEY_NOTIF_EVT");
2318 btif_dm_ble_key_notif_evt(&p_data->key_notif);
2319 break;
2320 case BTA_DM_BLE_PASSKEY_REQ_EVT:
2321 log::verbose("BTA_DM_BLE_PASSKEY_REQ_EVT");
2322 btif_dm_ble_passkey_req_evt(&p_data->pin_req);
2323 break;
2324 case BTA_DM_BLE_NC_REQ_EVT:
2325 log::verbose("BTA_DM_BLE_PASSKEY_REQ_EVT");
2326 btif_dm_ble_key_nc_req_evt(&p_data->key_notif);
2327 break;
2328 case BTA_DM_BLE_OOB_REQ_EVT:
2329 log::verbose("BTA_DM_BLE_OOB_REQ_EVT");
2330 btif_dm_ble_oob_req_evt(&p_data->rmt_oob);
2331 break;
2332 case BTA_DM_BLE_SC_OOB_REQ_EVT:
2333 log::verbose("BTA_DM_BLE_SC_OOB_REQ_EVT");
2334 btif_dm_ble_sc_oob_req_evt(&p_data->rmt_oob);
2335 break;
2336 case BTA_DM_BLE_SC_CR_LOC_OOB_EVT:
2337 log::verbose("BTA_DM_BLE_SC_CR_LOC_OOB_EVT");
2338 btif_dm_proc_loc_oob(BT_TRANSPORT_LE, true,
2339 p_data->local_oob_data.local_oob_c,
2340 p_data->local_oob_data.local_oob_r);
2341 break;
2342
2343 case BTA_DM_BLE_LOCAL_IR_EVT:
2344 log::verbose("BTA_DM_BLE_LOCAL_IR_EVT");
2345 ble_local_key_cb.is_id_keys_rcvd = true;
2346 ble_local_key_cb.id_keys.irk = p_data->ble_id_keys.irk;
2347 ble_local_key_cb.id_keys.ir = p_data->ble_id_keys.ir;
2348 ble_local_key_cb.id_keys.dhk = p_data->ble_id_keys.dhk;
2349 btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.irk,
2350 BTIF_DM_LE_LOCAL_KEY_IRK);
2351 btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.ir,
2352 BTIF_DM_LE_LOCAL_KEY_IR);
2353 btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.dhk,
2354 BTIF_DM_LE_LOCAL_KEY_DHK);
2355 break;
2356 case BTA_DM_BLE_LOCAL_ER_EVT:
2357 log::verbose("BTA_DM_BLE_LOCAL_ER_EVT");
2358 ble_local_key_cb.is_er_rcvd = true;
2359 ble_local_key_cb.er = p_data->ble_er;
2360 btif_storage_add_ble_local_key(ble_local_key_cb.er,
2361 BTIF_DM_LE_LOCAL_KEY_ER);
2362 break;
2363
2364 case BTA_DM_BLE_AUTH_CMPL_EVT:
2365 log::verbose("BTA_DM_BLE_AUTH_CMPL_EVT");
2366 btif_dm_ble_auth_cmpl_evt(&p_data->auth_cmpl);
2367 break;
2368
2369 case BTA_DM_LE_ADDR_ASSOC_EVT:
2370 GetInterfaceToProfiles()->events->invoke_le_address_associate_cb(
2371 p_data->proc_id_addr.pairing_bda, p_data->proc_id_addr.id_addr);
2372 break;
2373
2374 case BTA_DM_SIRK_VERIFICATION_REQ_EVT:
2375 GetInterfaceToProfiles()->events->invoke_le_address_associate_cb(
2376 p_data->proc_id_addr.pairing_bda, p_data->proc_id_addr.id_addr);
2377 break;
2378
2379 case BTA_DM_KEY_MISSING_EVT:
2380 GetInterfaceToProfiles()->events->invoke_key_missing_cb(
2381 p_data->key_missing.bd_addr);
2382 break;
2383
2384 default:
2385 log::warn("unhandled event({})", event);
2386 break;
2387 }
2388 }
2389
2390 /*******************************************************************************
2391 *
2392 * Function bte_dm_acl_evt
2393 *
2394 * Description BTIF handler for ACL up/down, identity address report events
2395 *
2396 * Returns void
2397 *
2398 ******************************************************************************/
btif_dm_acl_evt(tBTA_DM_ACL_EVT event,tBTA_DM_ACL * p_data)2399 void btif_dm_acl_evt(tBTA_DM_ACL_EVT event, tBTA_DM_ACL* p_data) {
2400 RawAddress bd_addr;
2401
2402 switch (event) {
2403 case BTA_DM_LINK_UP_EVT:
2404 bd_addr = p_data->link_up.bd_addr;
2405 log::verbose("BTA_DM_LINK_UP_EVT. Sending BT_ACL_STATE_CONNECTED");
2406
2407 btif_update_remote_version_property(&bd_addr);
2408
2409 GetInterfaceToProfiles()->events->invoke_acl_state_changed_cb(
2410 BT_STATUS_SUCCESS, bd_addr, BT_ACL_STATE_CONNECTED,
2411 (int)p_data->link_up.transport_link_type, HCI_SUCCESS,
2412 btm_is_acl_locally_initiated()
2413 ? bt_conn_direction_t::BT_CONN_DIRECTION_OUTGOING
2414 : bt_conn_direction_t::BT_CONN_DIRECTION_INCOMING,
2415 p_data->link_up.acl_handle);
2416
2417 if (p_data->link_up.transport_link_type == BT_TRANSPORT_LE &&
2418 pairing_cb.bd_addr == bd_addr &&
2419 is_device_le_audio_capable(bd_addr)) {
2420 L2CA_LockBleConnParamsForProfileConnection(bd_addr, true);
2421 }
2422 break;
2423
2424 case BTA_DM_LINK_UP_FAILED_EVT:
2425 GetInterfaceToProfiles()->events->invoke_acl_state_changed_cb(
2426 BT_STATUS_FAIL, p_data->link_up_failed.bd_addr,
2427 BT_ACL_STATE_DISCONNECTED, p_data->link_up_failed.transport_link_type,
2428 p_data->link_up_failed.status,
2429 btm_is_acl_locally_initiated()
2430 ? bt_conn_direction_t::BT_CONN_DIRECTION_OUTGOING
2431 : bt_conn_direction_t::BT_CONN_DIRECTION_INCOMING,
2432 INVALID_ACL_HANDLE);
2433 break;
2434
2435 case BTA_DM_LINK_DOWN_EVT: {
2436 bd_addr = p_data->link_down.bd_addr;
2437 btm_set_bond_type_dev(p_data->link_down.bd_addr, BOND_TYPE_UNKNOWN);
2438 GetInterfaceToProfiles()->onLinkDown(bd_addr);
2439
2440 bt_conn_direction_t direction;
2441 switch (btm_get_acl_disc_reason_code()) {
2442 case HCI_ERR_PEER_USER:
2443 case HCI_ERR_REMOTE_LOW_RESOURCE:
2444 case HCI_ERR_REMOTE_POWER_OFF:
2445 direction = bt_conn_direction_t::BT_CONN_DIRECTION_INCOMING;
2446 break;
2447 case HCI_ERR_CONN_CAUSE_LOCAL_HOST:
2448 case HCI_ERR_HOST_REJECT_SECURITY:
2449 direction = bt_conn_direction_t::BT_CONN_DIRECTION_OUTGOING;
2450 break;
2451 default:
2452 direction = bt_conn_direction_t::BT_CONN_DIRECTION_UNKNOWN;
2453 }
2454 GetInterfaceToProfiles()->events->invoke_acl_state_changed_cb(
2455 BT_STATUS_SUCCESS, bd_addr, BT_ACL_STATE_DISCONNECTED,
2456 (int)p_data->link_down.transport_link_type,
2457 static_cast<bt_hci_error_code_t>(btm_get_acl_disc_reason_code()),
2458 direction, INVALID_ACL_HANDLE);
2459 log::debug(
2460 "Sent BT_ACL_STATE_DISCONNECTED upward as ACL link down event "
2461 "device:{} reason:{}",
2462 bd_addr,
2463 hci_reason_code_text(
2464 static_cast<tHCI_REASON>(btm_get_acl_disc_reason_code())));
2465 } break;
2466 case BTA_DM_LE_FEATURES_READ:
2467 btif_get_adapter_property(BT_PROPERTY_LOCAL_LE_FEATURES);
2468 break;
2469
2470
2471 default: {
2472 log::error("Unexpected tBTA_DM_ACL_EVT:{}", event);
2473 } break;
2474
2475 }
2476 }
2477
2478 /*******************************************************************************
2479 *
2480 * Function bta_energy_info_cb
2481 *
2482 * Description Switches context from BTE to BTIF for DM energy info event
2483 *
2484 * Returns void
2485 *
2486 ******************************************************************************/
bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time,tBTM_BLE_RX_TIME_MS rx_time,tBTM_BLE_IDLE_TIME_MS idle_time,tBTM_BLE_ENERGY_USED energy_used,tBTM_CONTRL_STATE ctrl_state,tBTA_STATUS status)2487 static void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time,
2488 tBTM_BLE_RX_TIME_MS rx_time,
2489 tBTM_BLE_IDLE_TIME_MS idle_time,
2490 tBTM_BLE_ENERGY_USED energy_used,
2491 tBTM_CONTRL_STATE ctrl_state,
2492 tBTA_STATUS status) {
2493 log::verbose(
2494 "energy_info_cb-Status:{},state={},tx_t={}, rx_t={}, "
2495 "idle_time={},used={}",
2496 status, ctrl_state, tx_time, rx_time, idle_time, energy_used);
2497
2498 if (uid_set != nullptr) {
2499 bt_activity_energy_info energy_info;
2500 energy_info.status = status;
2501 energy_info.ctrl_state = ctrl_state;
2502 energy_info.rx_time = rx_time;
2503 energy_info.tx_time = tx_time;
2504 energy_info.idle_time = idle_time;
2505 energy_info.energy_used = energy_used;
2506
2507 bt_uid_traffic_t* data = uid_set_read_and_clear(uid_set);
2508 GetInterfaceToProfiles()->events->invoke_energy_info_cb(energy_info, data);
2509 } else {
2510 log::warn("Energy info event dropped as module is inactive");
2511 }
2512 }
2513
2514 /*****************************************************************************
2515 *
2516 * btif api functions (no context switch)
2517 *
2518 ****************************************************************************/
2519
2520 /*******************************************************************************
2521 *
2522 * Function btif_dm_start_discovery
2523 *
2524 * Description Start device discovery/inquiry
2525 *
2526 ******************************************************************************/
btif_dm_start_discovery(void)2527 void btif_dm_start_discovery(void) {
2528 log::verbose("start device discover/inquiry");
2529
2530 BTM_LogHistory(
2531 kBtmLogTag, RawAddress::kEmpty, "Device discovery",
2532 base::StringPrintf("is_request_queued:%c",
2533 bta_dm_is_search_request_queued() ? 'T' : 'F'));
2534
2535 /* no race here because we're guaranteed to be in the main thread */
2536 if (bta_dm_is_search_request_queued()) {
2537 log::info("skipping start discovery because a request is queued");
2538 return;
2539 }
2540
2541 /* Will be enabled to true once inquiry busy level has been received */
2542 btif_dm_inquiry_in_progress = false;
2543 /* find nearby devices */
2544 BTA_DmSearch(btif_dm_search_devices_evt);
2545 power_telemetry::GetInstance().LogScanStarted();
2546 }
2547
2548 /*******************************************************************************
2549 *
2550 * Function btif_dm_cancel_discovery
2551 *
2552 * Description Cancels search
2553 *
2554 ******************************************************************************/
btif_dm_cancel_discovery(void)2555 void btif_dm_cancel_discovery(void) {
2556 log::info("Cancel search");
2557 BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Cancel discovery");
2558
2559 BTA_DmSearchCancel();
2560 }
2561
btif_dm_pairing_is_busy()2562 bool btif_dm_pairing_is_busy() {
2563 return pairing_cb.state != BT_BOND_STATE_NONE;
2564 }
2565
2566 /*******************************************************************************
2567 *
2568 * Function btif_dm_create_bond
2569 *
2570 * Description Initiate bonding with the specified device
2571 *
2572 ******************************************************************************/
btif_dm_create_bond(const RawAddress bd_addr,int transport)2573 void btif_dm_create_bond(const RawAddress bd_addr, int transport) {
2574 log::verbose("bd_addr={}, transport={}", bd_addr, transport);
2575
2576 BTM_LogHistory(
2577 kBtmLogTag, bd_addr, "Create bond",
2578 base::StringPrintf("transport:%s", bt_transport_text(transport).c_str()));
2579
2580 btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CREATE_BOND,
2581 pairing_cb.state);
2582
2583 pairing_cb.timeout_retries = NUM_TIMEOUT_RETRIES;
2584 btif_dm_cb_create_bond(bd_addr, transport);
2585 }
2586
2587 /*******************************************************************************
2588 *
2589 * Function btif_dm_create_bond_le
2590 *
2591 * Description Initiate bonding with the specified device over le transport
2592 *
2593 ******************************************************************************/
btif_dm_create_bond_le(const RawAddress bd_addr,tBLE_ADDR_TYPE addr_type)2594 void btif_dm_create_bond_le(const RawAddress bd_addr,
2595 tBLE_ADDR_TYPE addr_type) {
2596 log::verbose("bd_addr={}, addr_type={}", bd_addr, addr_type);
2597 const tBLE_BD_ADDR ble_bd_addr{
2598 .type = addr_type,
2599 .bda = bd_addr,
2600 };
2601 BTM_LogHistory(
2602 kBtmLogTag, ble_bd_addr, "Create bond",
2603 base::StringPrintf("transport:%s",
2604 bt_transport_text(BT_TRANSPORT_LE).c_str()));
2605
2606 btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CREATE_BOND,
2607 pairing_cb.state);
2608
2609 pairing_cb.timeout_retries = NUM_TIMEOUT_RETRIES;
2610 btif_dm_cb_create_bond_le(bd_addr, addr_type);
2611 }
2612
2613 /*******************************************************************************
2614 *
2615 * Function btif_dm_create_bond_out_of_band
2616 *
2617 * Description Initiate bonding with the specified device using out of band
2618 * data
2619 *
2620 ******************************************************************************/
btif_dm_create_bond_out_of_band(const RawAddress bd_addr,tBT_TRANSPORT transport,const bt_oob_data_t p192_data,const bt_oob_data_t p256_data)2621 void btif_dm_create_bond_out_of_band(const RawAddress bd_addr,
2622 tBT_TRANSPORT transport,
2623 const bt_oob_data_t p192_data,
2624 const bt_oob_data_t p256_data) {
2625 bt_oob_data_t empty_data;
2626 memset(&empty_data, 0, sizeof(empty_data));
2627
2628 oob_cb.bdaddr = bd_addr;
2629 oob_cb.transport = transport;
2630 oob_cb.data_present = (int)BTM_OOB_NONE;
2631 if (memcmp(&p192_data, &empty_data, sizeof(p192_data)) != 0) {
2632 memcpy(&oob_cb.p192_data, &p192_data, sizeof(bt_oob_data_t));
2633 oob_cb.data_present = (int)BTM_OOB_PRESENT_192;
2634 }
2635
2636 if (memcmp(&p256_data, &empty_data, sizeof(p256_data)) != 0) {
2637 memcpy(&oob_cb.p256_data, &p256_data, sizeof(bt_oob_data_t));
2638 if (oob_cb.data_present == (int)BTM_OOB_PRESENT_192) {
2639 oob_cb.data_present = (int)BTM_OOB_PRESENT_192_AND_256;
2640 } else {
2641 oob_cb.data_present = (int)BTM_OOB_PRESENT_256;
2642 }
2643 }
2644
2645 BTM_LogHistory(
2646 kBtmLogTag, bd_addr, "Create bond",
2647 base::StringPrintf("transport:%s oob:%s",
2648 bt_transport_text(transport).c_str(),
2649 btm_oob_data_text(oob_cb.data_present).c_str()));
2650
2651 uint8_t empty[] = {0, 0, 0, 0, 0, 0, 0};
2652 switch (transport) {
2653 case BT_TRANSPORT_BR_EDR:
2654 // TODO(182162589): Flesh out classic impl in legacy BTMSec
2655 // Nothing to do yet, but not an error
2656
2657 // The controller only supports P192
2658 switch (oob_cb.data_present) {
2659 case BTM_OOB_PRESENT_192_AND_256:
2660 log::info("Have both P192 and P256");
2661 [[fallthrough]];
2662 case BTM_OOB_PRESENT_192:
2663 log::info("Using P192");
2664 break;
2665 case BTM_OOB_PRESENT_256:
2666 log::info("Using P256");
2667 // TODO(181889116):
2668 // Upgrade to support p256 (for now we just ignore P256)
2669 // because the controllers do not yet support it.
2670 bond_state_changed(BT_STATUS_UNSUPPORTED, bd_addr,
2671 BT_BOND_STATE_NONE);
2672 return;
2673 default:
2674 log::error("Invalid data present for controller:{}",
2675 oob_cb.data_present);
2676 bond_state_changed(BT_STATUS_PARM_INVALID, bd_addr,
2677 BT_BOND_STATE_NONE);
2678 return;
2679 }
2680 pairing_cb.is_local_initiated = true;
2681 log::error("Classic not implemented yet");
2682 bond_state_changed(BT_STATUS_UNSUPPORTED, bd_addr, BT_BOND_STATE_NONE);
2683 return;
2684 case BT_TRANSPORT_LE: {
2685 // Guess default RANDOM for address type for LE
2686 tBLE_ADDR_TYPE address_type = BLE_ADDR_RANDOM;
2687 log::info("Using LE Transport");
2688 switch (oob_cb.data_present) {
2689 case BTM_OOB_PRESENT_192_AND_256:
2690 log::info("Have both P192 and P256");
2691 [[fallthrough]];
2692 // Always prefer 256 for LE
2693 case BTM_OOB_PRESENT_256:
2694 log::info("Using P256");
2695 // If we have an address, lets get the type
2696 if (memcmp(p256_data.address, empty, 7) != 0) {
2697 /* byte no 7 is address type in LE Bluetooth Address OOB data */
2698 address_type = static_cast<tBLE_ADDR_TYPE>(p256_data.address[6]);
2699 }
2700 break;
2701 case BTM_OOB_PRESENT_192:
2702 log::info("Using P192");
2703 // If we have an address, lets get the type
2704 if (memcmp(p192_data.address, empty, 7) != 0) {
2705 /* byte no 7 is address type in LE Bluetooth Address OOB data */
2706 address_type = static_cast<tBLE_ADDR_TYPE>(p192_data.address[6]);
2707 }
2708 break;
2709 }
2710 pairing_cb.is_local_initiated = true;
2711 get_btm_client_interface().security.BTM_SecAddBleDevice(
2712 bd_addr, BT_DEVICE_TYPE_BLE, address_type);
2713 BTA_DmBond(bd_addr, address_type, transport, BT_DEVICE_TYPE_BLE);
2714 break;
2715 }
2716 default:
2717 log::error("Invalid transport: {}", transport);
2718 bond_state_changed(BT_STATUS_PARM_INVALID, bd_addr, BT_BOND_STATE_NONE);
2719 return;
2720 }
2721 }
2722
2723 /*******************************************************************************
2724 *
2725 * Function btif_dm_cancel_bond
2726 *
2727 * Description Initiate bonding with the specified device
2728 *
2729 ******************************************************************************/
btif_dm_cancel_bond(const RawAddress bd_addr)2730 void btif_dm_cancel_bond(const RawAddress bd_addr) {
2731 log::verbose("bd_addr={}", bd_addr);
2732
2733 BTM_LogHistory(kBtmLogTag, bd_addr, "Cancel bond");
2734
2735 btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CANCEL_BOND,
2736 pairing_cb.state);
2737
2738 /* TODO:
2739 ** 1. Restore scan modes
2740 ** 2. special handling for HID devices
2741 */
2742 if (is_bonding_or_sdp()) {
2743 if (pairing_cb.is_ssp) {
2744 if (pairing_cb.is_le_only) {
2745 BTA_DmBleSecurityGrant(bd_addr, BTA_DM_SEC_PAIR_NOT_SPT);
2746 } else {
2747 BTA_DmConfirm(bd_addr, false);
2748 BTA_DmBondCancel(bd_addr);
2749 btif_storage_remove_bonded_device(&bd_addr);
2750 }
2751 } else {
2752 if (pairing_cb.is_le_only) {
2753 BTA_DmBondCancel(bd_addr);
2754 } else {
2755 BTA_DmPinReply(bd_addr, false, 0, NULL);
2756 }
2757 /* Cancel bonding, in case it is in ACL connection setup state */
2758 BTA_DmBondCancel(bd_addr);
2759 }
2760 }
2761 }
2762
2763 /*******************************************************************************
2764 *
2765 * Function btif_dm_hh_open_failed
2766 *
2767 * Description informs the upper layers if the HH have failed during
2768 * bonding
2769 *
2770 * Returns none
2771 *
2772 ******************************************************************************/
2773
btif_dm_hh_open_failed(RawAddress * bdaddr)2774 void btif_dm_hh_open_failed(RawAddress* bdaddr) {
2775 if (pairing_cb.state == BT_BOND_STATE_BONDING &&
2776 *bdaddr == pairing_cb.bd_addr) {
2777 bond_state_changed(BT_STATUS_RMT_DEV_DOWN, *bdaddr, BT_BOND_STATE_NONE);
2778 }
2779 }
2780
2781 /*******************************************************************************
2782 *
2783 * Function btif_dm_remove_bond
2784 *
2785 * Description Removes bonding with the specified device
2786 *
2787 ******************************************************************************/
2788
btif_dm_remove_bond(const RawAddress bd_addr)2789 void btif_dm_remove_bond(const RawAddress bd_addr) {
2790 log::verbose("bd_addr={}", bd_addr);
2791
2792 BTM_LogHistory(kBtmLogTag, bd_addr, "Remove bond");
2793
2794 btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_REMOVE_BOND,
2795 pairing_cb.state);
2796
2797 // special handling for HID devices
2798 // VUP needs to be sent if its a HID Device. The HID HOST module will check if
2799 // there is a valid hid connection with this bd_addr. If yes VUP will be
2800 // issued.
2801 #if (BTA_HH_INCLUDED == TRUE)
2802 tAclLinkSpec link_spec;
2803 link_spec.addrt.bda = bd_addr;
2804 link_spec.transport = BT_TRANSPORT_AUTO;
2805 link_spec.addrt.type = BLE_ADDR_PUBLIC;
2806
2807 if (GetInterfaceToProfiles()->profileSpecific_HACK->btif_hh_virtual_unplug(
2808 link_spec) != BT_STATUS_SUCCESS)
2809 #endif
2810 {
2811 log::debug("Removing HH device");
2812 BTA_DmRemoveDevice(bd_addr);
2813 }
2814 }
2815
2816 /*******************************************************************************
2817 *
2818 * Function btif_dm_pin_reply
2819 *
2820 * Description BT legacy pairing - PIN code reply
2821 *
2822 ******************************************************************************/
2823
btif_dm_pin_reply(const RawAddress bd_addr,uint8_t accept,uint8_t pin_len,bt_pin_code_t pin_code)2824 void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept,
2825 uint8_t pin_len, bt_pin_code_t pin_code) {
2826 log::verbose("accept={}", accept);
2827
2828 if (pairing_cb.is_le_only) {
2829 int i;
2830 uint32_t passkey = 0;
2831 int multi[] = {100000, 10000, 1000, 100, 10, 1};
2832 for (i = 0; i < 6; i++) {
2833 passkey += (multi[i] * (pin_code.pin[i] - '0'));
2834 }
2835 // TODO:
2836 // FIXME: should we hide part of passkey here?
2837 log::verbose("btif_dm_pin_reply: passkey: {}", passkey);
2838 BTA_DmBlePasskeyReply(bd_addr, accept, passkey);
2839
2840 } else {
2841 BTA_DmPinReply(bd_addr, accept, pin_len, pin_code.pin);
2842 if (accept) pairing_cb.pin_code_len = pin_len;
2843 }
2844 }
2845
2846 /*******************************************************************************
2847 *
2848 * Function btif_dm_ssp_reply
2849 *
2850 * Description BT SSP Reply - Just Works, Numeric Comparison & Passkey
2851 * Entry
2852 *
2853 ******************************************************************************/
btif_dm_ssp_reply(const RawAddress bd_addr,bt_ssp_variant_t variant,uint8_t accept)2854 void btif_dm_ssp_reply(const RawAddress bd_addr, bt_ssp_variant_t variant,
2855 uint8_t accept) {
2856 log::verbose("accept={}", accept);
2857 BTM_LogHistory(
2858 kBtmLogTag, bd_addr, "Ssp reply",
2859 base::StringPrintf(
2860 "originator:%s variant:%d accept:%c le:%c numeric_comparison:%c",
2861 (pairing_cb.is_local_initiated) ? "local" : "remote", variant,
2862 (accept) ? 'Y' : 'N', (pairing_cb.is_le_only) ? 'T' : 'F',
2863 (pairing_cb.is_le_nc) ? 'T' : 'F'));
2864 if (pairing_cb.is_le_only) {
2865 if (pairing_cb.is_le_nc) {
2866 BTA_DmBleConfirmReply(bd_addr, accept);
2867 } else {
2868 if (accept)
2869 BTA_DmBleSecurityGrant(bd_addr, BTA_DM_SEC_GRANTED);
2870 else
2871 BTA_DmBleSecurityGrant(bd_addr, BTA_DM_SEC_PAIR_NOT_SPT);
2872 }
2873 } else {
2874 BTA_DmConfirm(bd_addr, accept);
2875 }
2876 }
2877
2878 /*******************************************************************************
2879 *
2880 * Function btif_dm_get_local_class_of_device
2881 *
2882 * Description Reads the system property configured class of device
2883 *
2884 * Returns A DEV_CLASS containing the current class of device.
2885 * If no value is present, or the value is malformed
2886 * the default kEmpty value will be used
2887 *
2888 ******************************************************************************/
btif_dm_get_local_class_of_device()2889 DEV_CLASS btif_dm_get_local_class_of_device() {
2890 /* A class of device is a {SERVICE_CLASS, MAJOR_CLASS, MINOR_CLASS}
2891 *
2892 * The input is expected to be a string of the following format:
2893 * <decimal number>,<decimal number>,<decimal number>
2894 *
2895 * For example, "90,2,12" (Hex: 0x5A, 0x2, 0xC)
2896 *
2897 * Notice there is always two commas and no spaces.
2898 */
2899 char prop_cod[PROPERTY_VALUE_MAX];
2900 osi_property_get(PROPERTY_CLASS_OF_DEVICE, prop_cod, "");
2901
2902 // If the property is empty, use the default
2903 if (prop_cod[0] == '\0') {
2904 log::error("COD property is empty");
2905 return kDevClassUnclassified;
2906 }
2907
2908 // Start reading the contents of the property string. If at any point anything
2909 // is malformed, use the default.
2910 DEV_CLASS temp_device_class;
2911 int i = 0;
2912 int j = 0;
2913 for (;;) {
2914 // Build a string of all the chars until the next comma, null, or end of the
2915 // buffer is reached. If any char is not a digit, then return the default.
2916 std::string value;
2917 while (i < PROPERTY_VALUE_MAX && prop_cod[i] != ',' &&
2918 prop_cod[i] != '\0') {
2919 char c = prop_cod[i++];
2920 if (!std::isdigit(c)) {
2921 log::error("COD malformed, '{:c}' is a non-digit", c);
2922 return kDevClassUnclassified;
2923 }
2924 value += c;
2925 }
2926
2927 // If we hit the end and it wasn't null terminated then return the default
2928 if (i == PROPERTY_VALUE_MAX && prop_cod[PROPERTY_VALUE_MAX - 1] != '\0') {
2929 log::error("COD malformed, value was truncated");
2930 return kDevClassUnclassified;
2931 }
2932
2933 // Each number in the list must be one byte, meaning 0 (0x00) -> 255 (0xFF)
2934 if (value.size() > 3 || value.size() == 0) {
2935 log::error("COD malformed, '{}' must be between [0, 255]", value);
2936 return kDevClassUnclassified;
2937 }
2938
2939 // Grab the value. If it's too large, then return the default
2940 uint32_t uint32_val = static_cast<uint32_t>(std::stoul(value.c_str()));
2941 if (uint32_val > 0xFF) {
2942 log::error("COD malformed, '{}' must be between [0, 255]", value);
2943 return kDevClassUnclassified;
2944 }
2945
2946 // Otherwise, it's safe to use
2947 temp_device_class[j++] = uint32_val;
2948
2949 // If we've reached 3 numbers then make sure we're at a null terminator
2950 if (j >= 3) {
2951 if (prop_cod[i] != '\0') {
2952 log::error("COD malformed, more than three numbers");
2953 return kDevClassUnclassified;
2954 }
2955 break;
2956 }
2957
2958 // If we're at a null terminator then we're done
2959 if (prop_cod[i] == '\0') {
2960 break;
2961 }
2962
2963 // Otherwise, skip over the comma
2964 ++i;
2965 }
2966
2967 // We must have read exactly 3 numbers
2968 DEV_CLASS device_class = kDevClassUnclassified;
2969 if (j == 3) {
2970 device_class[0] = temp_device_class[0];
2971 device_class[1] = temp_device_class[1];
2972 device_class[2] = temp_device_class[2];
2973 } else {
2974 log::error("COD malformed, fewer than three numbers");
2975 }
2976
2977 log::debug(
2978 "Using class of device '0x{:x}, 0x{:x}, 0x{:x}' from CoD system property",
2979 device_class[0], device_class[1], device_class[2]);
2980
2981 #ifdef __ANDROID__
2982 // Per BAP 1.0.1, 8.2.3. Device discovery, the stack needs to set Class of
2983 // Device (CoD) field Major Service Class bit 14 to 0b1 when Unicast Server,
2984 // Unicast Client, Broadcast Source, Broadcast Sink, Scan Delegator, or
2985 // Broadcast Assistant is supported on this device
2986 if (android::sysprop::BluetoothProperties::isProfileBapUnicastClientEnabled()
2987 .value_or(false) ||
2988 android::sysprop::BluetoothProperties::
2989 isProfileBapBroadcastAssistEnabled()
2990 .value_or(false) ||
2991 android::sysprop::BluetoothProperties::
2992 isProfileBapBroadcastSourceEnabled()
2993 .value_or(false)) {
2994 device_class[1] |= 0x01 << 6;
2995 } else {
2996 device_class[1] &= ~(0x01 << 6);
2997 }
2998 log::debug(
2999 "Check LE audio enabled status, update class of device to '0x{:x}, "
3000 "0x{:x}, 0x{:x}'",
3001 device_class[0], device_class[1], device_class[2]);
3002 #endif
3003 return device_class;
3004 }
3005
3006 /*******************************************************************************
3007 *
3008 * Function btif_dm_get_adapter_property
3009 *
3010 * Description Queries the BTA for the adapter property
3011 *
3012 * Returns bt_status_t
3013 *
3014 ******************************************************************************/
btif_dm_get_adapter_property(bt_property_t * prop)3015 bt_status_t btif_dm_get_adapter_property(bt_property_t* prop) {
3016 log::verbose("type=0x{:x}", prop->type);
3017 switch (prop->type) {
3018 case BT_PROPERTY_BDNAME: {
3019 bt_bdname_t* bd_name = (bt_bdname_t*)prop->val;
3020 strncpy((char*)bd_name->name, (char*)btif_get_default_local_name(),
3021 sizeof(bd_name->name) - 1);
3022 bd_name->name[sizeof(bd_name->name) - 1] = 0;
3023 prop->len = strlen((char*)bd_name->name);
3024 } break;
3025
3026 case BT_PROPERTY_ADAPTER_SCAN_MODE: {
3027 /* if the storage does not have it. Most likely app never set it. Default
3028 * is NONE */
3029 bt_scan_mode_t* mode = (bt_scan_mode_t*)prop->val;
3030 *mode = BT_SCAN_MODE_NONE;
3031 prop->len = sizeof(bt_scan_mode_t);
3032 } break;
3033
3034 case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: {
3035 uint32_t* tmt = (uint32_t*)prop->val;
3036 *tmt = 120; /* default to 120s, if not found in NV */
3037 prop->len = sizeof(uint32_t);
3038 } break;
3039
3040 default:
3041 prop->len = 0;
3042 return BT_STATUS_FAIL;
3043 }
3044 return BT_STATUS_SUCCESS;
3045 }
3046
btif_on_name_read_legacy(RawAddress bd_addr,tHCI_ERROR_CODE hci_status,const BD_NAME bd_name)3047 static void btif_on_name_read_legacy(RawAddress bd_addr,
3048 tHCI_ERROR_CODE hci_status,
3049 const BD_NAME bd_name) {
3050 btif_on_name_read(bd_addr, hci_status, bd_name,
3051 false /* during_device_search */);
3052 };
3053
3054 /*******************************************************************************
3055 *
3056 * Function btif_dm_get_remote_services
3057 *
3058 * Description Start SDP to get remote services by transport
3059 *
3060 * Returns bt_status_t
3061 *
3062 ******************************************************************************/
btif_dm_get_remote_services(RawAddress remote_addr,const int transport)3063 void btif_dm_get_remote_services(RawAddress remote_addr, const int transport) {
3064 log::verbose("transport={}, remote_addr={}", bt_transport_text(transport),
3065 remote_addr);
3066
3067 BTM_LogHistory(
3068 kBtmLogTag, remote_addr, "Service discovery",
3069 base::StringPrintf("transport:%s", bt_transport_text(transport).c_str()));
3070
3071 BTA_DmDiscover(
3072 remote_addr,
3073 service_discovery_callbacks{
3074 .on_gatt_results = btif_on_gatt_results,
3075 .on_did_received = btif_on_did_received,
3076 .on_name_read = btif_on_name_read_legacy,
3077 .on_service_discovery_results = btif_on_service_discovery_results},
3078 transport);
3079 }
3080
btif_dm_enable_service(tBTA_SERVICE_ID service_id,bool enable)3081 void btif_dm_enable_service(tBTA_SERVICE_ID service_id, bool enable) {
3082 bt_status_t status = btif_in_execute_service_request(service_id, enable);
3083 if (status == BT_STATUS_SUCCESS) {
3084 bt_property_t property;
3085 Uuid local_uuids[BT_MAX_NUM_UUIDS];
3086
3087 /* Now send the UUID_PROPERTY_CHANGED event to the upper layer */
3088 BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_UUIDS,
3089 sizeof(local_uuids), local_uuids);
3090 btif_storage_get_adapter_property(&property);
3091 GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(
3092 BT_STATUS_SUCCESS, 1, &property);
3093 }
3094 return;
3095 }
3096
btif_dm_proc_io_req(tBTM_AUTH_REQ * p_auth_req,bool is_orig)3097 void btif_dm_proc_io_req(tBTM_AUTH_REQ* p_auth_req, bool is_orig) {
3098 uint8_t yes_no_bit = BTA_AUTH_SP_YES & *p_auth_req;
3099 /* if local initiated:
3100 ** 1. set DD + MITM
3101 ** if remote initiated:
3102 ** 1. Copy over the auth_req from peer's io_rsp
3103 ** 2. Set the MITM if peer has it set or if peer has DisplayYesNo
3104 *(iPhone)
3105 ** as a fallback set MITM+GB if peer had MITM set
3106 */
3107
3108 log::verbose("original p_auth_req={}", *p_auth_req);
3109 if (pairing_cb.is_local_initiated) {
3110 /* if initing/responding to a dedicated bonding, use dedicate bonding bit */
3111 *p_auth_req = BTA_AUTH_DD_BOND | BTA_AUTH_SP_YES;
3112 } else if (!is_orig) {
3113 /* peer initiated paring. They probably know what they want.
3114 ** Copy the mitm from peer device.
3115 */
3116 log::debug("peer initiated, setting p_auth_req to peer's: {}",
3117 pairing_cb.auth_req);
3118 *p_auth_req = (pairing_cb.auth_req & BTA_AUTH_BONDS);
3119
3120 /* copy over the MITM bit as well. In addition if the peer has DisplayYesNo,
3121 * force MITM */
3122 if ((yes_no_bit) || (pairing_cb.io_cap & BTM_IO_CAP_IO))
3123 *p_auth_req |= BTA_AUTH_SP_YES;
3124 } else if (yes_no_bit) {
3125 /* set the general bonding bit for stored device */
3126 *p_auth_req = BTA_AUTH_GEN_BOND | yes_no_bit;
3127 }
3128 log::verbose("updated p_auth_req={}", *p_auth_req);
3129 }
3130
btif_dm_proc_io_rsp(const RawAddress &,tBTM_IO_CAP io_cap,tBTM_OOB_DATA,tBTM_AUTH_REQ auth_req)3131 void btif_dm_proc_io_rsp(const RawAddress& /* bd_addr */, tBTM_IO_CAP io_cap,
3132 tBTM_OOB_DATA /* oob_data */, tBTM_AUTH_REQ auth_req) {
3133 if (auth_req & BTA_AUTH_BONDS) {
3134 log::debug("auth_req:{}", auth_req);
3135 pairing_cb.auth_req = auth_req;
3136 pairing_cb.io_cap = io_cap;
3137 }
3138 }
3139
btif_dm_set_oob_for_io_req(tBTM_OOB_DATA * p_has_oob_data)3140 void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* p_has_oob_data) {
3141 if (is_empty_128bit(oob_cb.p192_data.c)) {
3142 *p_has_oob_data = false;
3143 } else {
3144 *p_has_oob_data = true;
3145 }
3146 log::verbose("*p_has_oob_data={}", *p_has_oob_data);
3147 }
3148
btif_dm_set_oob_for_le_io_req(const RawAddress & bd_addr,tBTM_OOB_DATA * p_has_oob_data,tBTM_LE_AUTH_REQ * p_auth_req)3149 void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr,
3150 tBTM_OOB_DATA* p_has_oob_data,
3151 tBTM_LE_AUTH_REQ* p_auth_req) {
3152 switch (oob_cb.data_present) {
3153 case BTM_OOB_PRESENT_192_AND_256:
3154 log::info("Have both P192 and P256");
3155 [[fallthrough]];
3156 // Always prefer 256 for LE
3157 case BTM_OOB_PRESENT_256:
3158 log::info("Using P256");
3159 if (!is_empty_128bit(oob_cb.p256_data.c) &&
3160 !is_empty_128bit(oob_cb.p256_data.r)) {
3161 /* make sure OOB data is for this particular device */
3162 if (bd_addr == oob_cb.bdaddr) {
3163 *p_auth_req = ((*p_auth_req) | BTM_LE_AUTH_REQ_SC_ONLY);
3164 *p_has_oob_data = true;
3165 } else {
3166 *p_has_oob_data = false;
3167 log::warn("P256-1: Remote address didn't match OOB data address");
3168 }
3169 } else if (!is_empty_128bit(oob_cb.p256_data.sm_tk)) {
3170 /* We have security manager TK */
3171
3172 /* make sure OOB data is for this particular device */
3173 if (bd_addr == oob_cb.bdaddr) {
3174 // When using OOB with TK, SC Secure Connections bit must be disabled.
3175 tBTM_LE_AUTH_REQ mask = ~BTM_LE_AUTH_REQ_SC_ONLY;
3176 *p_auth_req = ((*p_auth_req) & mask);
3177 *p_has_oob_data = true;
3178 } else {
3179 *p_has_oob_data = false;
3180 log::warn("P256-2: Remote address didn't match OOB data address");
3181 }
3182 } else {
3183 *p_has_oob_data = false;
3184 }
3185 break;
3186 case BTM_OOB_PRESENT_192:
3187 log::info("Using P192");
3188 if (!is_empty_128bit(oob_cb.p192_data.c) &&
3189 !is_empty_128bit(oob_cb.p192_data.r)) {
3190 /* make sure OOB data is for this particular device */
3191 if (bd_addr == oob_cb.bdaddr) {
3192 *p_auth_req = ((*p_auth_req) | BTM_LE_AUTH_REQ_SC_ONLY);
3193 *p_has_oob_data = true;
3194 } else {
3195 *p_has_oob_data = false;
3196 log::warn("P192-1: Remote address didn't match OOB data address");
3197 }
3198 } else if (!is_empty_128bit(oob_cb.p192_data.sm_tk)) {
3199 /* We have security manager TK */
3200
3201 /* make sure OOB data is for this particular device */
3202 if (bd_addr == oob_cb.bdaddr) {
3203 // When using OOB with TK, SC Secure Connections bit must be disabled.
3204 tBTM_LE_AUTH_REQ mask = ~BTM_LE_AUTH_REQ_SC_ONLY;
3205 *p_auth_req = ((*p_auth_req) & mask);
3206 *p_has_oob_data = true;
3207 } else {
3208 *p_has_oob_data = false;
3209 log::warn("P192-2: Remote address didn't match OOB data address");
3210 }
3211 } else {
3212 *p_has_oob_data = false;
3213 }
3214 break;
3215 }
3216 log::verbose("*p_has_oob_data={}", *p_has_oob_data);
3217 }
3218
btif_dm_load_local_oob(void)3219 void btif_dm_load_local_oob(void) {
3220 char prop_oob[PROPERTY_VALUE_MAX];
3221 osi_property_get("service.brcm.bt.oob", prop_oob, "3");
3222 log::verbose("prop_oob = {}", prop_oob);
3223 if (prop_oob[0] != '3') {
3224 if (is_empty_128bit(oob_cb.p192_data.c)) {
3225 log::verbose("read OOB, call BTA_DmLocalOob()");
3226 BTA_DmLocalOob();
3227 }
3228 }
3229 }
3230
3231 static bool waiting_on_oob_advertiser_start = false;
3232 static std::optional<uint8_t> oob_advertiser_id_;
stop_oob_advertiser()3233 static void stop_oob_advertiser() {
3234 // For chasing an advertising bug b/237023051
3235 log::debug("oob_advertiser_id: {}", oob_advertiser_id_.value());
3236 auto advertiser = bluetooth::shim::get_ble_advertiser_instance();
3237 advertiser->Unregister(oob_advertiser_id_.value());
3238 oob_advertiser_id_ = {};
3239 }
3240
3241 /*******************************************************************************
3242 *
3243 * Function btif_dm_generate_local_oob_data
3244 *
3245 * Description Initiate oob data fetch from controller
3246 *
3247 * Parameters transport; Classic or LE
3248 *
3249 ******************************************************************************/
btif_dm_generate_local_oob_data(tBT_TRANSPORT transport)3250 void btif_dm_generate_local_oob_data(tBT_TRANSPORT transport) {
3251 log::debug("Transport {}", bt_transport_text(transport));
3252 if (transport == BT_TRANSPORT_BR_EDR) {
3253 BTM_ReadLocalOobData();
3254 } else if (transport == BT_TRANSPORT_LE) {
3255 // Call create data first, so we don't have to hold on to the address for
3256 // the state machine lifecycle. Rather, lets create the data, then start
3257 // advertising then request the address.
3258 if (!waiting_on_oob_advertiser_start) {
3259 // For chasing an advertising bug b/237023051
3260 log::debug("oob_advertiser_id: {}", oob_advertiser_id_.value_or(255));
3261 if (oob_advertiser_id_.has_value()) {
3262 stop_oob_advertiser();
3263 }
3264 waiting_on_oob_advertiser_start = true;
3265 if (!SMP_CrLocScOobData()) {
3266 waiting_on_oob_advertiser_start = false;
3267 GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
3268 transport, false, Octet16{}, Octet16{}, RawAddress{}, 0x00);
3269 }
3270 } else {
3271 GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
3272 transport, false, Octet16{}, Octet16{}, RawAddress{}, 0x00);
3273 }
3274 }
3275 }
3276
3277 // Step Four: CallBack from Step Three
get_address_callback(tBT_TRANSPORT transport,bool is_valid,const Octet16 & c,const Octet16 & r,uint8_t address_type,RawAddress address)3278 static void get_address_callback(tBT_TRANSPORT transport, bool is_valid,
3279 const Octet16& c, const Octet16& r,
3280 uint8_t address_type, RawAddress address) {
3281 GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
3282 transport, is_valid, c, r, address, address_type);
3283 waiting_on_oob_advertiser_start = false;
3284 }
3285
3286 // Step Three: CallBack from Step Two, advertise and get address
start_advertising_callback(uint8_t id,tBT_TRANSPORT transport,bool is_valid,const Octet16 & c,const Octet16 & r,tBTM_STATUS status)3287 static void start_advertising_callback(uint8_t id, tBT_TRANSPORT transport,
3288 bool is_valid, const Octet16& c,
3289 const Octet16& r, tBTM_STATUS status) {
3290 if (status != 0) {
3291 log::info("OOB get advertiser ID failed with status {}", status);
3292 GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
3293 transport, false, c, r, RawAddress{}, 0x00);
3294 SMP_ClearLocScOobData();
3295 waiting_on_oob_advertiser_start = false;
3296 oob_advertiser_id_ = {};
3297 return;
3298 }
3299 log::debug("OOB advertiser with id {}", id);
3300 auto advertiser = bluetooth::shim::get_ble_advertiser_instance();
3301 advertiser->GetOwnAddress(
3302 id, base::Bind(&get_address_callback, transport, is_valid, c, r));
3303 }
3304
timeout_cb(uint8_t id,tBTM_STATUS status)3305 static void timeout_cb(uint8_t id, tBTM_STATUS status) {
3306 log::info("OOB advertiser with id {} timed out with status {}", id, status);
3307 auto advertiser = bluetooth::shim::get_ble_advertiser_instance();
3308 advertiser->Unregister(id);
3309 SMP_ClearLocScOobData();
3310 waiting_on_oob_advertiser_start = false;
3311 oob_advertiser_id_ = {};
3312 }
3313
3314 // Step Two: CallBack from Step One, advertise and get address
id_status_callback(tBT_TRANSPORT transport,bool is_valid,const Octet16 & c,const Octet16 & r,uint8_t id,tBTM_STATUS status)3315 static void id_status_callback(tBT_TRANSPORT transport, bool is_valid,
3316 const Octet16& c, const Octet16& r, uint8_t id,
3317 tBTM_STATUS status) {
3318 if (status != 0) {
3319 log::info("OOB get advertiser ID failed with status {}", status);
3320 GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
3321 transport, false, c, r, RawAddress{}, 0x00);
3322 SMP_ClearLocScOobData();
3323 waiting_on_oob_advertiser_start = false;
3324 oob_advertiser_id_ = {};
3325 return;
3326 }
3327
3328 oob_advertiser_id_ = id;
3329 log::info("oob_advertiser_id: {}", id);
3330
3331 auto advertiser = bluetooth::shim::get_ble_advertiser_instance();
3332 AdvertiseParameters parameters{};
3333 parameters.advertising_event_properties =
3334 0x0045 /* connectable, discoverable, tx power */;
3335 parameters.min_interval = 0xa0; // 100 ms
3336 parameters.max_interval = 0x500; // 800 ms
3337 parameters.channel_map = 0x7; // Use all the channels
3338 parameters.tx_power = 0; // 0 dBm
3339 parameters.primary_advertising_phy = 1;
3340 parameters.secondary_advertising_phy = 2;
3341 parameters.scan_request_notification_enable = 0;
3342 parameters.own_address_type = BLE_ADDR_RANDOM;
3343
3344 std::vector<uint8_t> advertisement{0x02, 0x01 /* Flags */,
3345 0x02 /* Connectable */};
3346 std::vector<uint8_t> scan_data{};
3347
3348 advertiser->StartAdvertising(
3349 id,
3350 base::Bind(&start_advertising_callback, id, transport, is_valid, c, r),
3351 parameters, advertisement, scan_data, 120 /* timeout_s */,
3352 base::Bind(&timeout_cb, id));
3353 }
3354
3355 // Step One: Start the advertiser
start_oob_advertiser(tBT_TRANSPORT transport,bool is_valid,const Octet16 & c,const Octet16 & r)3356 static void start_oob_advertiser(tBT_TRANSPORT transport, bool is_valid,
3357 const Octet16& c, const Octet16& r) {
3358 auto advertiser = bluetooth::shim::get_ble_advertiser_instance();
3359 advertiser->RegisterAdvertiser(
3360 base::Bind(&id_status_callback, transport, is_valid, c, r));
3361 }
3362
btif_dm_proc_loc_oob(tBT_TRANSPORT transport,bool is_valid,const Octet16 & c,const Octet16 & r)3363 void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid,
3364 const Octet16& c, const Octet16& r) {
3365 // is_valid is important for deciding which OobDataCallback function to use
3366 if (!is_valid) {
3367 GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
3368 transport, false, c, r, RawAddress{}, 0x00);
3369 waiting_on_oob_advertiser_start = false;
3370 return;
3371 }
3372 if (transport == BT_TRANSPORT_LE) {
3373 // Now that we have the data, lets start advertising and get the address.
3374 start_oob_advertiser(transport, is_valid, c, r);
3375 } else {
3376 GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
3377 transport, is_valid, c, r,
3378 bluetooth::ToRawAddress(
3379 bluetooth::shim::GetController()->GetMacAddress()),
3380 0x00);
3381 }
3382 }
3383
3384 /*******************************************************************************
3385 *
3386 * Function btif_dm_get_smp_config
3387 *
3388 * Description Retrieve the SMP pairing options from the bt_stack.conf
3389 * file. To provide specific pairing options for the host
3390 * add a node with label "SmpOptions" to the config file
3391 * and assign it a comma separated list of 5 values in the
3392 * format: auth, io, ikey, rkey, ksize, oob
3393 * eg: PTS_SmpOptions=0xD,0x4,0xf,0xf,0x10
3394 *
3395 * Parameters: tBTE_APPL_CFG*: pointer to struct defining pairing options
3396 *
3397 * Returns true if the options were successfully read, else false
3398 *
3399 ******************************************************************************/
btif_dm_get_smp_config(tBTE_APPL_CFG * p_cfg)3400 bool btif_dm_get_smp_config(tBTE_APPL_CFG* p_cfg) {
3401 const std::string* recv = stack_config_get_interface()->get_pts_smp_options();
3402 if (!recv) {
3403 log::warn("SMP pairing options not found in stack configuration");
3404 return false;
3405 }
3406
3407 char conf[64];
3408 char* pch;
3409 char* endptr;
3410
3411 strncpy(conf, recv->c_str(), 64);
3412 conf[63] = 0; // null terminate
3413
3414 pch = strtok(conf, ",");
3415 if (pch != NULL)
3416 p_cfg->ble_auth_req = (uint8_t)strtoul(pch, &endptr, 16);
3417 else
3418 return false;
3419
3420 pch = strtok(NULL, ",");
3421 if (pch != NULL)
3422 p_cfg->ble_io_cap = (uint8_t)strtoul(pch, &endptr, 16);
3423 else
3424 return false;
3425
3426 pch = strtok(NULL, ",");
3427 if (pch != NULL)
3428 p_cfg->ble_init_key = (uint8_t)strtoul(pch, &endptr, 16);
3429 else
3430 return false;
3431
3432 pch = strtok(NULL, ",");
3433 if (pch != NULL)
3434 p_cfg->ble_resp_key = (uint8_t)strtoul(pch, &endptr, 16);
3435 else
3436 return false;
3437
3438 pch = strtok(NULL, ",");
3439 if (pch != NULL)
3440 p_cfg->ble_max_key_size = (uint8_t)strtoul(pch, &endptr, 16);
3441 else
3442 return false;
3443
3444 return true;
3445 }
3446
btif_dm_proc_rmt_oob(const RawAddress & bd_addr,Octet16 * p_c,Octet16 * p_r)3447 bool btif_dm_proc_rmt_oob(const RawAddress& bd_addr, Octet16* p_c,
3448 Octet16* p_r) {
3449 const char* path_a = "/data/misc/bluedroid/LOCAL/a.key";
3450 const char* path_b = "/data/misc/bluedroid/LOCAL/b.key";
3451 const char* path = NULL;
3452 char prop_oob[PROPERTY_VALUE_MAX];
3453 osi_property_get("service.brcm.bt.oob", prop_oob, "3");
3454 log::debug("prop_oob = {}", prop_oob);
3455 if (prop_oob[0] == '1')
3456 path = path_b;
3457 else if (prop_oob[0] == '2')
3458 path = path_a;
3459 if (!path) {
3460 log::debug("can't open path!");
3461 return false;
3462 }
3463
3464 FILE* fp = fopen(path, "rb");
3465 if (fp == NULL) {
3466 log::debug("failed to read OOB keys from {}", path);
3467 return false;
3468 }
3469
3470 log::verbose("read OOB data from {}", path);
3471 (void)fread(p_c->data(), 1, OCTET16_LEN, fp);
3472 (void)fread(p_r->data(), 1, OCTET16_LEN, fp);
3473 fclose(fp);
3474
3475 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
3476 return true;
3477 }
3478
btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF * p_ssp_key_notif)3479 static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) {
3480 RawAddress bd_addr;
3481 int dev_type;
3482
3483 log::verbose("addr:{}", p_ssp_key_notif->bd_addr);
3484
3485 /* Remote name update */
3486 if (!btif_get_device_type(p_ssp_key_notif->bd_addr, &dev_type)) {
3487 dev_type = BT_DEVICE_TYPE_BLE;
3488 }
3489 btif_dm_update_ble_remote_properties(p_ssp_key_notif->bd_addr,
3490 p_ssp_key_notif->bd_name, kDevClassEmpty,
3491 (tBT_DEVICE_TYPE)dev_type);
3492 bd_addr = p_ssp_key_notif->bd_addr;
3493
3494 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
3495 pairing_cb.is_ssp = false;
3496
3497 BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
3498 base::StringPrintf("passkey:%u", p_ssp_key_notif->passkey));
3499
3500 GetInterfaceToProfiles()->events->invoke_ssp_request_cb(
3501 bd_addr, BT_SSP_VARIANT_PASSKEY_NOTIFICATION, p_ssp_key_notif->passkey);
3502 }
3503
btif_dm_ble_is_temp_pairing(RawAddress & bd_addr,bool ctkd)3504 static bool btif_dm_ble_is_temp_pairing(RawAddress& bd_addr, bool ctkd) {
3505 if (btm_get_bond_type_dev(bd_addr) == BOND_TYPE_TEMPORARY) {
3506 if (!com::android::bluetooth::flags::ignore_bond_type_for_le()) {
3507 return true;
3508 }
3509
3510 return ctkd;
3511 }
3512
3513 return false;
3514 }
3515
btif_model_name_known(const RawAddress & bd_addr)3516 static bool btif_model_name_known(const RawAddress& bd_addr) {
3517 bt_property_t prop;
3518 bt_bdname_t model_name;
3519 BTIF_STORAGE_FILL_PROPERTY(&prop, BT_PROPERTY_REMOTE_MODEL_NUM,
3520 sizeof(model_name), &model_name);
3521
3522 if (btif_storage_get_remote_device_property(&bd_addr, &prop) !=
3523 BT_STATUS_SUCCESS ||
3524 prop.len == 0) {
3525 log::info("Device {} no cached model name", bd_addr);
3526 return false;
3527 }
3528
3529 return true;
3530 }
3531
read_dis_cback(const RawAddress & bd_addr,tDIS_VALUE * p_dis_value)3532 static void read_dis_cback(const RawAddress& bd_addr, tDIS_VALUE* p_dis_value) {
3533 if (p_dis_value == nullptr) {
3534 log::warn("received unexpected/error DIS callback");
3535 return;
3536 }
3537
3538 if (!(p_dis_value->attr_mask & DIS_ATTR_MODEL_NUM_BIT)) {
3539 log::warn("unknown bit, mask: {}", (int)p_dis_value->attr_mask);
3540 return;
3541 }
3542
3543 for (int i = 0; i < DIS_MAX_STRING_DATA; i++) {
3544 if (p_dis_value->data_string[i] == nullptr) continue;
3545
3546 bt_property_t prop;
3547 prop.type = BT_PROPERTY_REMOTE_MODEL_NUM;
3548 prop.val = p_dis_value->data_string[i];
3549 prop.len = strlen((char*)prop.val);
3550
3551 log::info("Device {}, model name: {}", bd_addr, (char*)prop.val);
3552
3553 btif_storage_set_remote_device_property(&bd_addr, &prop);
3554 GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
3555 BT_STATUS_SUCCESS, bd_addr, 1, &prop);
3556 }
3557 }
3558
3559 /*******************************************************************************
3560 *
3561 * Function btif_dm_ble_auth_cmpl_evt
3562 *
3563 * Description Executes authentication complete event in btif context
3564 *
3565 * Returns void
3566 *
3567 ******************************************************************************/
btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL * p_auth_cmpl)3568 static void btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) {
3569 /* Save link key, if not temporary */
3570 bt_status_t status = BT_STATUS_FAIL;
3571 bt_bond_state_t state = BT_BOND_STATE_NONE;
3572
3573 RawAddress bd_addr = p_auth_cmpl->bd_addr;
3574
3575 /* Clear OOB data */
3576 memset(&oob_cb, 0, sizeof(oob_cb));
3577
3578 if ((p_auth_cmpl->success) && (p_auth_cmpl->key_present)) {
3579 /* store keys */
3580 }
3581 if (p_auth_cmpl->success) {
3582 status = BT_STATUS_SUCCESS;
3583 state = BT_BOND_STATE_BONDED;
3584 tBLE_ADDR_TYPE addr_type;
3585
3586 if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) !=
3587 BT_STATUS_SUCCESS)
3588 btif_storage_set_remote_addr_type(&bd_addr, p_auth_cmpl->addr_type);
3589
3590 /* Test for temporary bonding */
3591 if (btif_dm_ble_is_temp_pairing(bd_addr, p_auth_cmpl->is_ctkd)) {
3592 log::debug("sending BT_BOND_STATE_NONE for Temp pairing");
3593 btif_storage_remove_bonded_device(&bd_addr);
3594 state = BT_BOND_STATE_NONE;
3595 } else {
3596 btif_dm_save_ble_bonding_keys(bd_addr);
3597
3598 if (com::android::bluetooth::flags::read_model_num_fix() &&
3599 is_le_audio_capable_during_service_discovery(bd_addr) &&
3600 !btif_model_name_known(bd_addr) &&
3601 BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
3602 log::info("Read model name for le audio capable device");
3603 if (!DIS_ReadDISInfo(bd_addr, read_dis_cback, DIS_ATTR_MODEL_NUM_BIT)) {
3604 log::warn("Read DIS failed");
3605 }
3606 }
3607
3608 if (pairing_cb.gatt_over_le ==
3609 btif_dm_pairing_cb_t::ServiceDiscoveryState::NOT_STARTED) {
3610 log::info("scheduling GATT discovery over LE for {}", bd_addr);
3611 pairing_cb.gatt_over_le =
3612 btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED;
3613 btif_dm_get_remote_services(bd_addr, BT_TRANSPORT_LE);
3614 } else {
3615 log::info(
3616 "skipping GATT discovery over LE - was already scheduled or "
3617 "finished for {}, state: {}",
3618 bd_addr, pairing_cb.gatt_over_le);
3619 }
3620 }
3621 } else {
3622 /* Map the HCI fail reason to bt status */
3623 // TODO This is not a proper use of the type
3624 uint8_t fail_reason = static_cast<uint8_t>(p_auth_cmpl->fail_reason);
3625 log::error("LE authentication for {} failed with reason {}", bd_addr,
3626 p_auth_cmpl->fail_reason);
3627 switch (fail_reason) {
3628 case BTA_DM_AUTH_SMP_PAIR_AUTH_FAIL:
3629 case BTA_DM_AUTH_SMP_CONFIRM_VALUE_FAIL:
3630 case BTA_DM_AUTH_SMP_UNKNOWN_ERR:
3631 btif_dm_remove_ble_bonding_keys();
3632 status = BT_STATUS_AUTH_FAILURE;
3633 break;
3634
3635 case BTA_DM_AUTH_SMP_CONN_TOUT: {
3636 if (!p_auth_cmpl->is_ctkd && btm_sec_is_a_bonded_dev(bd_addr)) {
3637 log::warn(
3638 "Bonded device addr={}, timed out - will not remove the keys",
3639 bd_addr);
3640 // Don't send state change to upper layers - otherwise Java think we
3641 // unbonded, and will disconnect HID profile.
3642 return;
3643 }
3644 log::info(
3645 "Removing ble bonding keys on SMP_CONN_TOUT during crosskey: {}",
3646 p_auth_cmpl->is_ctkd);
3647 btif_dm_remove_ble_bonding_keys();
3648 status = BT_STATUS_AUTH_FAILURE;
3649 break;
3650 }
3651 case BTA_DM_AUTH_SMP_PAIR_NOT_SUPPORT:
3652 status = BT_STATUS_AUTH_REJECTED;
3653 break;
3654 default:
3655 btif_dm_remove_ble_bonding_keys();
3656 status = BT_STATUS_UNHANDLED;
3657 break;
3658 }
3659 }
3660 if (state == BT_BOND_STATE_BONDED && !pairing_cb.static_bdaddr.IsEmpty() &&
3661 bd_addr != pairing_cb.static_bdaddr) {
3662 // Report RPA bonding state to Java in crosskey paring
3663 bond_state_changed(status, bd_addr, BT_BOND_STATE_BONDING);
3664 }
3665 bond_state_changed(status, bd_addr, state);
3666 // TODO(240451061): Calling `stop_oob_advertiser();` gets command
3667 // disallowed...
3668 }
3669
btif_dm_load_ble_local_keys(void)3670 void btif_dm_load_ble_local_keys(void) {
3671 memset(&ble_local_key_cb, 0, sizeof(btif_dm_local_key_cb_t));
3672
3673 if (btif_storage_get_ble_local_key(
3674 BTIF_DM_LE_LOCAL_KEY_ER, &ble_local_key_cb.er) == BT_STATUS_SUCCESS) {
3675 ble_local_key_cb.is_er_rcvd = true;
3676 log::verbose("BLE ER key loaded");
3677 }
3678
3679 if ((btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IR,
3680 &ble_local_key_cb.id_keys.ir) ==
3681 BT_STATUS_SUCCESS) &&
3682 (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IRK,
3683 &ble_local_key_cb.id_keys.irk) ==
3684 BT_STATUS_SUCCESS) &&
3685 (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_DHK,
3686 &ble_local_key_cb.id_keys.dhk) ==
3687 BT_STATUS_SUCCESS)) {
3688 ble_local_key_cb.is_id_keys_rcvd = true;
3689 log::verbose("BLE ID keys loaded");
3690 }
3691 }
btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK * p_key_mask,Octet16 * p_er,tBTA_BLE_LOCAL_ID_KEYS * p_id_keys)3692 void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask,
3693 Octet16* p_er,
3694 tBTA_BLE_LOCAL_ID_KEYS* p_id_keys) {
3695 log::assert_that(p_key_mask != nullptr,
3696 "assert failed: p_key_mask != nullptr");
3697 if (ble_local_key_cb.is_er_rcvd) {
3698 log::assert_that(p_er != nullptr, "assert failed: p_er != nullptr");
3699 *p_er = ble_local_key_cb.er;
3700 *p_key_mask |= BTA_BLE_LOCAL_KEY_TYPE_ER;
3701 }
3702
3703 if (ble_local_key_cb.is_id_keys_rcvd) {
3704 log::assert_that(p_id_keys != nullptr,
3705 "assert failed: p_id_keys != nullptr");
3706 p_id_keys->ir = ble_local_key_cb.id_keys.ir;
3707 p_id_keys->irk = ble_local_key_cb.id_keys.irk;
3708 p_id_keys->dhk = ble_local_key_cb.id_keys.dhk;
3709 *p_key_mask |= BTA_BLE_LOCAL_KEY_TYPE_ID;
3710 }
3711 log::verbose("*p_key_mask=0x{:02x}", *p_key_mask);
3712 }
3713
btif_dm_save_ble_bonding_keys(RawAddress & bd_addr)3714 static void btif_dm_save_ble_bonding_keys(RawAddress& bd_addr) {
3715 log::verbose("{}", bd_addr);
3716
3717 if (bd_addr.IsEmpty()) {
3718 log::warn("bd_addr is empty");
3719 return;
3720 }
3721
3722 if (pairing_cb.ble.is_penc_key_rcvd) {
3723 btif_storage_add_ble_bonding_key(
3724 &bd_addr, (uint8_t*)&pairing_cb.ble.penc_key, BTM_LE_KEY_PENC,
3725 sizeof(tBTM_LE_PENC_KEYS));
3726 }
3727
3728 if (pairing_cb.ble.is_pid_key_rcvd) {
3729 btif_storage_add_ble_bonding_key(&bd_addr,
3730 (uint8_t*)&pairing_cb.ble.pid_key,
3731 BTM_LE_KEY_PID, sizeof(tBTM_LE_PID_KEYS));
3732 }
3733
3734 if (pairing_cb.ble.is_pcsrk_key_rcvd) {
3735 btif_storage_add_ble_bonding_key(
3736 &bd_addr, (uint8_t*)&pairing_cb.ble.pcsrk_key, BTM_LE_KEY_PCSRK,
3737 sizeof(tBTM_LE_PCSRK_KEYS));
3738 }
3739
3740 if (pairing_cb.ble.is_lenc_key_rcvd) {
3741 btif_storage_add_ble_bonding_key(
3742 &bd_addr, (uint8_t*)&pairing_cb.ble.lenc_key, BTM_LE_KEY_LENC,
3743 sizeof(tBTM_LE_LENC_KEYS));
3744 }
3745
3746 if (pairing_cb.ble.is_lcsrk_key_rcvd) {
3747 btif_storage_add_ble_bonding_key(
3748 &bd_addr, (uint8_t*)&pairing_cb.ble.lcsrk_key, BTM_LE_KEY_LCSRK,
3749 sizeof(tBTM_LE_LCSRK_KEYS));
3750 }
3751
3752 if (pairing_cb.ble.is_lidk_key_rcvd) {
3753 uint8_t empty[] = {};
3754 btif_storage_add_ble_bonding_key(&bd_addr, empty, BTM_LE_KEY_LID, 0);
3755 }
3756 }
3757
btif_dm_remove_ble_bonding_keys(void)3758 static void btif_dm_remove_ble_bonding_keys(void) {
3759 log::verbose("removing ble bonding keys");
3760
3761 RawAddress bd_addr = pairing_cb.bd_addr;
3762 btif_storage_remove_ble_bonding_keys(&bd_addr);
3763 }
3764
3765 /*******************************************************************************
3766 *
3767 * Function btif_dm_ble_sec_req_evt
3768 *
3769 * Description Eprocess security request event in btif context
3770 *
3771 * Returns void
3772 *
3773 ******************************************************************************/
btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ * p_ble_req,bool is_consent)3774 static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req,
3775 bool is_consent) {
3776 int dev_type;
3777
3778 log::verbose("addr:{}", p_ble_req->bd_addr);
3779
3780 if (!is_consent && pairing_cb.state == BT_BOND_STATE_BONDING) {
3781 log::warn("Discard security request");
3782 return;
3783 }
3784
3785 /* Remote name update */
3786 if (!btif_get_device_type(p_ble_req->bd_addr, &dev_type)) {
3787 dev_type = BT_DEVICE_TYPE_BLE;
3788 }
3789 btif_dm_update_ble_remote_properties(p_ble_req->bd_addr, p_ble_req->bd_name,
3790 kDevClassEmpty,
3791 (tBT_DEVICE_TYPE)dev_type);
3792
3793 RawAddress bd_addr = p_ble_req->bd_addr;
3794
3795 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
3796
3797 pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
3798 pairing_cb.is_le_only = true;
3799 pairing_cb.is_le_nc = false;
3800 pairing_cb.is_ssp = true;
3801 btm_set_bond_type_dev(p_ble_req->bd_addr, pairing_cb.bond_type);
3802
3803 BTM_LogHistory(kBtmLogTagCallback, bd_addr, "SSP ble request",
3804 "BT_SSP_VARIANT_CONSENT");
3805
3806 GetInterfaceToProfiles()->events->invoke_ssp_request_cb(
3807 bd_addr, BT_SSP_VARIANT_CONSENT, 0);
3808 }
3809
3810 /*******************************************************************************
3811 *
3812 * Function btif_dm_ble_passkey_req_evt
3813 *
3814 * Description Executes pin request event in btif context
3815 *
3816 * Returns void
3817 *
3818 ******************************************************************************/
btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ * p_pin_req)3819 static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ* p_pin_req) {
3820 bt_bdname_t bd_name;
3821 uint32_t cod;
3822 int dev_type;
3823
3824 /* Remote name update */
3825 if (!btif_get_device_type(p_pin_req->bd_addr, &dev_type)) {
3826 dev_type = BT_DEVICE_TYPE_BLE;
3827 }
3828 btif_dm_update_ble_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name,
3829 kDevClassEmpty,
3830 (tBT_DEVICE_TYPE)dev_type);
3831
3832 RawAddress bd_addr = p_pin_req->bd_addr;
3833 bd_name_copy(bd_name.name, p_pin_req->bd_name);
3834
3835 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
3836 pairing_cb.is_le_only = true;
3837
3838 cod = COD_UNCLASSIFIED;
3839
3840 BTM_LogHistory(kBtmLogTagCallback, bd_addr, "PIN request",
3841 base::StringPrintf("name:'%s'", PRIVATE_NAME(bd_name.name)));
3842
3843 GetInterfaceToProfiles()->events->invoke_pin_request_cb(bd_addr, bd_name, cod,
3844 false);
3845 }
btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF * p_notif_req)3846 static void btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF* p_notif_req) {
3847 /* TODO implement key notification for numeric comparison */
3848
3849 RawAddress bd_addr = p_notif_req->bd_addr;
3850 log::verbose("addr:{}", bd_addr);
3851
3852 /* Remote name update */
3853 btif_update_remote_properties(p_notif_req->bd_addr, p_notif_req->bd_name,
3854 kDevClassEmpty, BT_DEVICE_TYPE_BLE);
3855
3856 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
3857 pairing_cb.is_ssp = false;
3858 pairing_cb.is_le_only = true;
3859 pairing_cb.is_le_nc = true;
3860
3861 BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
3862 base::StringPrintf("passkey:%u", p_notif_req->passkey));
3863
3864 GetInterfaceToProfiles()->events->invoke_ssp_request_cb(
3865 bd_addr, BT_SSP_VARIANT_PASSKEY_CONFIRMATION, p_notif_req->passkey);
3866 }
3867
btif_dm_ble_oob_req_evt(tBTA_DM_SP_RMT_OOB * req_oob_type)3868 static void btif_dm_ble_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) {
3869 log::verbose("addr:{}", req_oob_type->bd_addr);
3870
3871 RawAddress bd_addr = req_oob_type->bd_addr;
3872 /* We already checked if OOB data is present in
3873 * btif_dm_set_oob_for_le_io_req, but check here again. If it's not present
3874 * do nothing, pairing will timeout.
3875 */
3876 if (is_empty_128bit(oob_cb.p192_data.sm_tk)) {
3877 return;
3878 }
3879
3880 /* make sure OOB data is for this particular device */
3881 if (req_oob_type->bd_addr != oob_cb.bdaddr) {
3882 log::warn("remote address didn't match OOB data address");
3883 return;
3884 }
3885
3886 /* Remote name update */
3887 btif_update_remote_properties(req_oob_type->bd_addr, req_oob_type->bd_name,
3888 kDevClassEmpty, BT_DEVICE_TYPE_BLE);
3889
3890 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
3891 pairing_cb.is_ssp = false;
3892 pairing_cb.is_le_only = true;
3893 pairing_cb.is_le_nc = false;
3894
3895 BTM_BleOobDataReply(req_oob_type->bd_addr, 0, 16, oob_cb.p192_data.sm_tk);
3896 }
3897
btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB * req_oob_type)3898 static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) {
3899 RawAddress bd_addr = req_oob_type->bd_addr;
3900 log::verbose("bd_addr: {}", bd_addr);
3901 log::verbose("oob_cb.bdaddr: {}", oob_cb.bdaddr);
3902
3903 /* make sure OOB data is for this particular device */
3904 if (req_oob_type->bd_addr != oob_cb.bdaddr) {
3905 log::error("remote address didn't match OOB data address");
3906 return;
3907 }
3908
3909 /* We already checked if OOB data is present in
3910 * btif_dm_set_oob_for_le_io_req, but check here again. If it's not present
3911 * do nothing, pairing will timeout.
3912 */
3913 bt_oob_data_t oob_data_to_use = {};
3914 switch (oob_cb.data_present) {
3915 case BTM_OOB_PRESENT_192_AND_256:
3916 log::info("Have both P192 and P256");
3917 [[fallthrough]];
3918 // Always prefer 256 for LE
3919 case BTM_OOB_PRESENT_256:
3920 log::info("Using P256");
3921 if (is_empty_128bit(oob_cb.p256_data.c) &&
3922 is_empty_128bit(oob_cb.p256_data.r)) {
3923 log::warn("P256 LE SC OOB data is empty");
3924 return;
3925 }
3926 oob_data_to_use = oob_cb.p256_data;
3927 break;
3928 case BTM_OOB_PRESENT_192:
3929 log::info("Using P192");
3930 if (is_empty_128bit(oob_cb.p192_data.c) &&
3931 is_empty_128bit(oob_cb.p192_data.r)) {
3932 log::warn("P192 LE SC OOB data is empty");
3933 return;
3934 }
3935 oob_data_to_use = oob_cb.p192_data;
3936 break;
3937 }
3938
3939 /* Remote name update */
3940 btif_update_remote_properties(req_oob_type->bd_addr,
3941 oob_data_to_use.device_name, kDevClassEmpty,
3942 BT_DEVICE_TYPE_BLE);
3943
3944 bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
3945 pairing_cb.is_ssp = false;
3946 // TODO: we can derive classic pairing from this one
3947 pairing_cb.is_le_only = true;
3948 pairing_cb.is_le_nc = false;
3949 BTM_BleSecureConnectionOobDataReply(req_oob_type->bd_addr, oob_data_to_use.c,
3950 oob_data_to_use.r);
3951 }
3952
btif_dm_update_ble_remote_properties(const RawAddress & bd_addr,BD_NAME bd_name,DEV_CLASS dev_class,tBT_DEVICE_TYPE dev_type)3953 void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr,
3954 BD_NAME bd_name, DEV_CLASS dev_class,
3955 tBT_DEVICE_TYPE dev_type) {
3956 btif_update_remote_properties(bd_addr, bd_name, dev_class, dev_type);
3957 }
3958
btif_dm_ble_tx_test_cback(void * p)3959 static void btif_dm_ble_tx_test_cback(void* p) {
3960 char* p_param = (char*)p;
3961 uint8_t status;
3962 STREAM_TO_UINT8(status, p_param);
3963 GetInterfaceToProfiles()->events->invoke_le_test_mode_cb(
3964 (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0);
3965 }
3966
btif_dm_ble_rx_test_cback(void * p)3967 static void btif_dm_ble_rx_test_cback(void* p) {
3968 char* p_param = (char*)p;
3969 uint8_t status;
3970 STREAM_TO_UINT8(status, p_param);
3971 GetInterfaceToProfiles()->events->invoke_le_test_mode_cb(
3972 (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0);
3973 }
3974
btif_dm_ble_test_end_cback(void * p)3975 static void btif_dm_ble_test_end_cback(void* p) {
3976 char* p_param = (char*)p;
3977 uint8_t status;
3978 uint16_t count = 0;
3979 STREAM_TO_UINT8(status, p_param);
3980 if (status == 0) STREAM_TO_UINT16(count, p_param);
3981 GetInterfaceToProfiles()->events->invoke_le_test_mode_cb(
3982 (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, count);
3983 }
3984
btif_ble_transmitter_test(uint8_t tx_freq,uint8_t test_data_len,uint8_t packet_payload)3985 void btif_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len,
3986 uint8_t packet_payload) {
3987 BTM_BleTransmitterTest(tx_freq, test_data_len, packet_payload,
3988 btif_dm_ble_tx_test_cback);
3989 }
3990
btif_ble_receiver_test(uint8_t rx_freq)3991 void btif_ble_receiver_test(uint8_t rx_freq) {
3992 BTM_BleReceiverTest(rx_freq, btif_dm_ble_rx_test_cback);
3993 }
3994
btif_ble_test_end()3995 void btif_ble_test_end() { BTM_BleTestEnd(btif_dm_ble_test_end_cback); }
3996
btif_dm_on_disable()3997 void btif_dm_on_disable() {
3998 /* cancel any pending pairing requests */
3999 if (is_bonding_or_sdp()) {
4000 log::verbose("Cancel pending pairing request");
4001 btif_dm_cancel_bond(pairing_cb.bd_addr);
4002 }
4003 }
4004
4005 /*******************************************************************************
4006 *
4007 * Function btif_dm_read_energy_info
4008 *
4009 * Description Reads the energy info from controller
4010 *
4011 * Returns void
4012 *
4013 ******************************************************************************/
btif_dm_read_energy_info()4014 void btif_dm_read_energy_info() { BTA_DmBleGetEnergyInfo(bta_energy_info_cb); }
4015
btif_get_default_local_name()4016 static const char* btif_get_default_local_name() {
4017 if (btif_default_local_name[0] == '\0') {
4018 int max_len = sizeof(btif_default_local_name) - 1;
4019
4020 char prop_name[PROPERTY_VALUE_MAX];
4021 osi_property_get(PROPERTY_DEFAULT_DEVICE_NAME, prop_name, "");
4022 strncpy(btif_default_local_name, prop_name, max_len);
4023
4024 // If no value was placed in the btif_default_local_name then use model name
4025 if (btif_default_local_name[0] == '\0') {
4026 char prop_model[PROPERTY_VALUE_MAX];
4027 osi_property_get(PROPERTY_PRODUCT_MODEL, prop_model, "");
4028 strncpy(btif_default_local_name, prop_model, max_len);
4029 }
4030 btif_default_local_name[max_len] = '\0';
4031 }
4032 return btif_default_local_name;
4033 }
4034
btif_stats_add_bond_event(const RawAddress & bd_addr,bt_bond_function_t function,bt_bond_state_t state)4035 static void btif_stats_add_bond_event(const RawAddress& bd_addr,
4036 bt_bond_function_t function,
4037 bt_bond_state_t state) {
4038 std::unique_lock<std::mutex> lock(bond_event_lock);
4039
4040 btif_bond_event_t* event = &btif_dm_bond_events[btif_events_end_index];
4041 event->bd_addr = bd_addr;
4042 event->function = function;
4043 event->state = state;
4044 clock_gettime(CLOCK_REALTIME, &event->timestamp);
4045
4046 btif_num_bond_events++;
4047 btif_events_end_index =
4048 (btif_events_end_index + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1);
4049 if (btif_events_end_index == btif_events_start_index) {
4050 btif_events_start_index =
4051 (btif_events_start_index + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1);
4052 }
4053
4054 int type;
4055 btif_get_device_type(bd_addr, &type);
4056
4057 bluetooth::common::device_type_t device_type;
4058 switch (type) {
4059 case BT_DEVICE_TYPE_BREDR:
4060 device_type = bluetooth::common::DEVICE_TYPE_BREDR;
4061 break;
4062 case BT_DEVICE_TYPE_BLE:
4063 device_type = bluetooth::common::DEVICE_TYPE_LE;
4064 break;
4065 case BT_DEVICE_TYPE_DUMO:
4066 device_type = bluetooth::common::DEVICE_TYPE_DUMO;
4067 break;
4068 default:
4069 device_type = bluetooth::common::DEVICE_TYPE_UNKNOWN;
4070 break;
4071 }
4072
4073 uint32_t cod = get_cod(&bd_addr);
4074 uint64_t ts =
4075 event->timestamp.tv_sec * 1000 + event->timestamp.tv_nsec / 1000000;
4076 bluetooth::common::BluetoothMetricsLogger::GetInstance()->LogPairEvent(
4077 0, ts, cod, device_type);
4078 }
4079
btif_debug_bond_event_dump(int fd)4080 void btif_debug_bond_event_dump(int fd) {
4081 std::unique_lock<std::mutex> lock(bond_event_lock);
4082 dprintf(fd, "\nBond Events: \n");
4083 dprintf(fd, " Total Number of events: %zu\n", btif_num_bond_events);
4084 if (btif_num_bond_events > 0)
4085 dprintf(fd,
4086 " Time address Function State\n");
4087
4088 for (size_t i = btif_events_start_index; i != btif_events_end_index;
4089 i = (i + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1)) {
4090 btif_bond_event_t* event = &btif_dm_bond_events[i];
4091
4092 char eventtime[20];
4093 char temptime[20];
4094 struct tm* tstamp = localtime(&event->timestamp.tv_sec);
4095 strftime(temptime, sizeof(temptime), "%H:%M:%S", tstamp);
4096 snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime,
4097 event->timestamp.tv_nsec / 1000000);
4098
4099 const char* func_name;
4100 switch (event->function) {
4101 case BTIF_DM_FUNC_CREATE_BOND:
4102 func_name = "btif_dm_create_bond";
4103 break;
4104 case BTIF_DM_FUNC_REMOVE_BOND:
4105 func_name = "btif_dm_remove_bond";
4106 break;
4107 case BTIF_DM_FUNC_BOND_STATE_CHANGED:
4108 func_name = "bond_state_changed ";
4109 break;
4110 case BTIF_DM_FUNC_CANCEL_BOND:
4111 func_name = "btif_dm_cancel_bond";
4112 break;
4113 default:
4114 func_name = "Invalid value ";
4115 break;
4116 }
4117
4118 const char* bond_state;
4119 switch (event->state) {
4120 case BT_BOND_STATE_NONE:
4121 bond_state = "BOND_STATE_NONE";
4122 break;
4123 case BT_BOND_STATE_BONDING:
4124 bond_state = "BOND_STATE_BONDING";
4125 break;
4126 case BT_BOND_STATE_BONDED:
4127 bond_state = "BOND_STATE_BONDED";
4128 break;
4129 default:
4130 bond_state = "Invalid bond state";
4131 break;
4132 }
4133
4134 dprintf(fd, " %s %s %s %s\n", eventtime,
4135 ADDRESS_TO_LOGGABLE_CSTR(event->bd_addr), func_name, bond_state);
4136 }
4137 }
4138
btif_get_device_type(const RawAddress & bda,int * p_device_type)4139 bool btif_get_device_type(const RawAddress& bda, int* p_device_type) {
4140 if (p_device_type == NULL) return false;
4141
4142 std::string addrstr = bda.ToString();
4143 const char* bd_addr_str = addrstr.c_str();
4144
4145 if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_DEV_TYPE,
4146 p_device_type))
4147 return false;
4148 tBT_DEVICE_TYPE device_type = static_cast<tBT_DEVICE_TYPE>(*p_device_type);
4149 log::debug("bd_addr:{} device_type:{}", bda, DeviceTypeText(device_type));
4150
4151 return true;
4152 }
4153
btif_get_address_type(const RawAddress & bda,tBLE_ADDR_TYPE * p_addr_type)4154 bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type) {
4155 if (p_addr_type == NULL) return false;
4156
4157 std::string addrstr = bda.ToString();
4158 const char* bd_addr_str = addrstr.c_str();
4159
4160 int val = 0;
4161 if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_ADDR_TYPE, &val))
4162 return false;
4163 *p_addr_type = static_cast<tBLE_ADDR_TYPE>(val);
4164 log::debug("bd_addr:{}[{}]", bda, AddressTypeText(*p_addr_type));
4165 return true;
4166 }
4167
btif_check_device_in_inquiry_db(const RawAddress & address)4168 void btif_check_device_in_inquiry_db(const RawAddress& address) {
4169 tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
4170 int device_type = 0;
4171
4172 if (btif_get_address_type(address, &addr_type) &&
4173 btif_get_device_type(address, &device_type) &&
4174 device_type != BT_DEVICE_TYPE_BREDR) {
4175 BTA_DmAddBleDevice(address, addr_type, device_type);
4176 }
4177 }
4178
btif_dm_clear_event_filter()4179 void btif_dm_clear_event_filter() { BTA_DmClearEventFilter(); }
4180
btif_dm_clear_event_mask()4181 void btif_dm_clear_event_mask() { BTA_DmClearEventMask(); }
4182
btif_dm_clear_filter_accept_list()4183 void btif_dm_clear_filter_accept_list() { BTA_DmClearFilterAcceptList(); }
4184
btif_dm_disconnect_all_acls()4185 void btif_dm_disconnect_all_acls() { BTA_DmDisconnectAllAcls(); }
4186
btif_dm_le_rand(bluetooth::hci::LeRandCallback callback)4187 void btif_dm_le_rand(bluetooth::hci::LeRandCallback callback) {
4188 BTA_DmLeRand(std::move(callback));
4189 }
4190
btif_dm_set_event_filter_connection_setup_all_devices()4191 void btif_dm_set_event_filter_connection_setup_all_devices() {
4192 // Autoplumbed
4193 BTA_DmSetEventFilterConnectionSetupAllDevices();
4194 }
4195
btif_dm_allow_wake_by_hid(std::vector<RawAddress> classic_addrs,std::vector<std::pair<RawAddress,uint8_t>> le_addrs)4196 void btif_dm_allow_wake_by_hid(
4197 std::vector<RawAddress> classic_addrs,
4198 std::vector<std::pair<RawAddress, uint8_t>> le_addrs) {
4199 BTA_DmAllowWakeByHid(std::move(classic_addrs), std::move(le_addrs));
4200 }
4201
btif_dm_restore_filter_accept_list(std::vector<std::pair<RawAddress,uint8_t>> le_devices)4202 void btif_dm_restore_filter_accept_list(
4203 std::vector<std::pair<RawAddress, uint8_t>> le_devices) {
4204 // Autoplumbed
4205 BTA_DmRestoreFilterAcceptList(std::move(le_devices));
4206 }
4207
btif_dm_set_default_event_mask_except(uint64_t mask,uint64_t le_mask)4208 void btif_dm_set_default_event_mask_except(uint64_t mask, uint64_t le_mask) {
4209 // Autoplumbed
4210 BTA_DmSetDefaultEventMaskExcept(mask, le_mask);
4211 }
4212
btif_dm_set_event_filter_inquiry_result_all_devices()4213 void btif_dm_set_event_filter_inquiry_result_all_devices() {
4214 // Autoplumbed
4215 BTA_DmSetEventFilterInquiryResultAllDevices();
4216 }
4217
btif_dm_metadata_changed(const RawAddress & remote_bd_addr,int key,std::vector<uint8_t> value)4218 void btif_dm_metadata_changed(const RawAddress& remote_bd_addr, int key,
4219 std::vector<uint8_t> value) {
4220 static const int METADATA_LE_AUDIO = 26;
4221 /* If METADATA_LE_AUDIO is present, device is LE Audio capable */
4222 if (key == METADATA_LE_AUDIO) {
4223 log::info("Device is LE Audio Capable {}", remote_bd_addr);
4224 metadata_cb.le_audio_cache.insert_or_assign(remote_bd_addr, value);
4225
4226 // TODO(b/334067583): Remove this DIS read when b/334067583 is fixed
4227 if (com::android::bluetooth::flags::read_model_num_fix() &&
4228 !btif_model_name_known(remote_bd_addr) &&
4229 BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_LE)) {
4230 log::info("Read model name for le audio capable device");
4231 if (!DIS_ReadDISInfo(remote_bd_addr, read_dis_cback,
4232 DIS_ATTR_MODEL_NUM_BIT)) {
4233 log::warn("Read DIS failed");
4234 }
4235 }
4236 }
4237 }
4238
4239 namespace bluetooth {
4240 namespace legacy {
4241 namespace testing {
4242
bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time,tBTM_BLE_RX_TIME_MS rx_time,tBTM_BLE_IDLE_TIME_MS idle_time,tBTM_BLE_ENERGY_USED energy_used,tBTM_CONTRL_STATE ctrl_state,tBTA_STATUS status)4243 void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time,
4244 tBTM_BLE_RX_TIME_MS rx_time,
4245 tBTM_BLE_IDLE_TIME_MS idle_time,
4246 tBTM_BLE_ENERGY_USED energy_used,
4247 tBTM_CONTRL_STATE ctrl_state, tBTA_STATUS status) {
4248 ::bta_energy_info_cb(tx_time, rx_time, idle_time, energy_used, ctrl_state,
4249 status);
4250 }
4251
btif_on_name_read(RawAddress bd_addr,tHCI_ERROR_CODE hci_status,const BD_NAME bd_name,bool during_device_search)4252 void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status,
4253 const BD_NAME bd_name, bool during_device_search) {
4254 ::btif_on_name_read(bd_addr, hci_status, bd_name, during_device_search);
4255 }
4256
4257 } // namespace testing
4258 } // namespace legacy
4259 } // namespace bluetooth
4260