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