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