1 /******************************************************************************
2  *
3  *  Copyright (c) 2014 The Android Open Source Project
4  *  Copyright 2009-2012 Broadcom Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 /*******************************************************************************
21  *
22  *  Filename:      btif_storage.c
23  *
24  *  Description:   Stores the local BT adapter and remote device properties in
25  *                 NVRAM storage, typically as xml file in the
26  *                 mobile's filesystem
27  *
28  *
29  */
30 
31 #define LOG_TAG "bt_btif_storage"
32 #include "btif/include/btif_storage.h"
33 
34 #include <alloca.h>
35 #include <bluetooth/log.h>
36 #include <com_android_bluetooth_flags.h>
37 #ifndef TARGET_FLOSS
38 #include <cutils/multiuser.h>
39 #endif
40 #include <stdlib.h>
41 #include <string.h>
42 #include <time.h>
43 #include <unistd.h>
44 
45 #include <unordered_set>
46 #include <vector>
47 
48 #include "btif/include/btif_api.h"
49 #include "btif/include/btif_config.h"
50 #include "btif/include/btif_util.h"
51 #include "btif/include/core_callbacks.h"
52 #include "btif/include/stack_manager_t.h"
53 #include "hci/controller_interface.h"
54 #include "internal_include/bt_target.h"
55 #include "main/shim/entry.h"
56 #include "main/shim/helpers.h"
57 #include "osi/include/allocator.h"
58 #include "stack/include/bt_octets.h"
59 #include "stack/include/bt_uuid16.h"
60 #include "storage/config_keys.h"
61 #include "types/bluetooth/uuid.h"
62 #include "types/raw_address.h"
63 
64 /* This is a local property to add a device found */
65 #define BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP 0xFF
66 
67 // Default user ID to use when real user ID is not available
68 #define BTIF_STORAGE_RESTRICTED_USER_ID_DEFAULT 1
69 
70 // TODO(b/369381361) Enfore -Wmissing-prototypes
71 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
72 
73 using base::Bind;
74 using bluetooth::Uuid;
75 using namespace bluetooth;
76 
77 /*******************************************************************************
78  *  Constants & Macros
79  ******************************************************************************/
80 
81 struct BtifStorageKey {
82   uint8_t type;
83   const std::string& name;
84   uint8_t size;
85 };
86 static const BtifStorageKey BTIF_STORAGE_LE_KEYS[] = {
87         {BTM_LE_KEY_PENC, BTIF_STORAGE_KEY_LE_KEY_PENC, sizeof(tBTM_LE_PENC_KEYS)},
88         {BTM_LE_KEY_PID, BTIF_STORAGE_KEY_LE_KEY_PID, sizeof(tBTM_LE_PID_KEYS)},
89         {BTM_LE_KEY_PCSRK, BTIF_STORAGE_KEY_LE_KEY_PCSRK, sizeof(tBTM_LE_PCSRK_KEYS)},
90         {BTM_LE_KEY_LENC, BTIF_STORAGE_KEY_LE_KEY_LENC, sizeof(tBTM_LE_LENC_KEYS)},
91         {BTM_LE_KEY_LCSRK, BTIF_STORAGE_KEY_LE_KEY_LCSRK, sizeof(tBTM_LE_LCSRK_KEYS)},
92         {BTM_LE_KEY_LID, BTIF_STORAGE_KEY_LE_KEY_LID, sizeof(tBTM_LE_PID_KEYS)},
93 };
94 static const BtifStorageKey BTIF_STORAGE_LOCAL_LE_KEYS[] = {
95         {BTIF_DM_LE_LOCAL_KEY_IR, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IR, sizeof(Octet16)},
96         {BTIF_DM_LE_LOCAL_KEY_IRK, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK, sizeof(Octet16)},
97         {BTIF_DM_LE_LOCAL_KEY_DHK, BTIF_STORAGE_KEY_LE_LOCAL_KEY_DHK, sizeof(Octet16)},
98         {BTIF_DM_LE_LOCAL_KEY_ER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_ER, sizeof(Octet16)},
99 };
100 
101 /*******************************************************************************
102  *  External functions
103  ******************************************************************************/
104 
105 void btif_gatts_add_bonded_dev_from_nv(const RawAddress& bda);
106 
107 /*******************************************************************************
108  *  Internal Functions
109  ******************************************************************************/
110 
111 static bool btif_has_ble_keys(const std::string& bdstr);
112 
113 /*******************************************************************************
114  *  Static functions
115  ******************************************************************************/
116 
btif_storage_get_user_id()117 static int btif_storage_get_user_id() {
118   if (!com::android::bluetooth::flags::guest_mode_bond()) {
119     return BTIF_STORAGE_RESTRICTED_USER_ID_DEFAULT;
120   }
121 #ifdef TARGET_FLOSS
122   return BTIF_STORAGE_RESTRICTED_USER_ID_DEFAULT;
123 #else
124   return multiuser_get_user_id(getuid());
125 #endif
126 }
127 
btif_storage_set_mode(RawAddress * remote_bd_addr)128 static void btif_storage_set_mode(RawAddress* remote_bd_addr) {
129   std::string bdstr = remote_bd_addr->ToString();
130   if (GetInterfaceToProfiles()->config->isRestrictedMode()) {
131     int user_id = btif_storage_get_user_id();
132     log::info("{} added by user {}, will be removed on exiting restricted mode", *remote_bd_addr,
133               user_id);
134     btif_config_set_int(bdstr, BTIF_STORAGE_KEY_RESTRICTED, user_id);
135   }
136 }
137 
prop2cfg(const RawAddress * remote_bd_addr,bt_property_t * prop)138 static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) {
139   std::string bdstr;
140   if (remote_bd_addr) {
141     bdstr = remote_bd_addr->ToString();
142   }
143 
144   char value[1024];
145   if (prop->len <= 0 || prop->len > static_cast<int>(sizeof(value)) - 1) {
146     log::warn(
147             "Unable to save property to configuration file type:{},  len:{} is "
148             "invalid",
149             prop->type, prop->len);
150     return false;
151   }
152   switch (prop->type) {
153     case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
154       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_TIMESTAMP, static_cast<int>(time(NULL)));
155       break;
156     case BT_PROPERTY_BDNAME: {
157       int name_length = prop->len > BD_NAME_LEN ? BD_NAME_LEN : prop->len;
158       strncpy(value, reinterpret_cast<char*>(prop->val), name_length);
159       value[name_length] = '\0';
160       if (remote_bd_addr) {
161         btif_config_set_str(bdstr, BTIF_STORAGE_KEY_NAME, value);
162       } else {
163         btif_config_set_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_NAME, value);
164       }
165       break;
166     }
167     case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
168       strncpy(value, reinterpret_cast<char*>(prop->val), prop->len);
169       value[prop->len] = '\0';
170       btif_config_set_str(bdstr, BTIF_STORAGE_KEY_ALIAS, value);
171       break;
172     case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT:
173       btif_config_set_int(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_DISC_TIMEOUT,
174                           *reinterpret_cast<int*>(prop->val));
175       break;
176     case BT_PROPERTY_CLASS_OF_DEVICE:
177       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_CLASS, *reinterpret_cast<int*>(prop->val));
178       break;
179     case BT_PROPERTY_TYPE_OF_DEVICE:
180       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, *reinterpret_cast<int*>(prop->val));
181       break;
182     case BT_PROPERTY_UUIDS: {
183       std::string val;
184       size_t cnt = (prop->len) / sizeof(Uuid);
185       for (size_t i = 0; i < cnt; i++) {
186         val += (reinterpret_cast<Uuid*>(prop->val) + i)->ToString() + " ";
187       }
188       btif_config_set_str(bdstr, BTIF_STORAGE_KEY_REMOTE_SERVICE, val);
189       break;
190     }
191     case BT_PROPERTY_REMOTE_VERSION_INFO: {
192       bt_remote_version_t* info = reinterpret_cast<bt_remote_version_t*>(prop->val);
193 
194       if (!info) {
195         return false;
196       }
197 
198       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, info->manufacturer);
199       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, info->version);
200       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, info->sub_ver);
201     } break;
202     case BT_PROPERTY_APPEARANCE: {
203       int val = *reinterpret_cast<uint16_t*>(prop->val);
204       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_APPEARANCE, val);
205     } break;
206     case BT_PROPERTY_VENDOR_PRODUCT_INFO: {
207       bt_vendor_product_info_t* info = reinterpret_cast<bt_vendor_product_info_t*>(prop->val);
208       if (!info) {
209         return false;
210       }
211 
212       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID_SOURCE, info->vendor_id_src);
213       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID, info->vendor_id);
214       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_PRODUCT_ID, info->product_id);
215       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_VERSION, info->version);
216     } break;
217     case BT_PROPERTY_REMOTE_MODEL_NUM: {
218       strncpy(value, reinterpret_cast<char*>(prop->val), prop->len);
219       value[prop->len] = '\0';
220       btif_config_set_str(bdstr, BTIF_STORAGE_KEY_DIS_MODEL_NUM, value);
221     } break;
222     case BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED:
223       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_SECURE_CONNECTIONS_SUPPORTED,
224                           *reinterpret_cast<uint8_t*>(prop->val));
225       break;
226     case BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE:
227       btif_config_set_int(bdstr, BTIF_STORAGE_KEY_MAX_SESSION_KEY_SIZE,
228                           *reinterpret_cast<uint8_t*>(prop->val));
229       break;
230     default:
231       log::error("Unknown prop type:{}", prop->type);
232       return false;
233   }
234 
235   return true;
236 }
237 
cfg2prop(const RawAddress * remote_bd_addr,bt_property_t * prop)238 static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) {
239   std::string bdstr;
240   if (remote_bd_addr) {
241     bdstr = remote_bd_addr->ToString();
242   }
243   if (prop->len <= 0) {
244     log::warn("Invalid property read from configuration file type:{}, len:{}", prop->type,
245               prop->len);
246     return false;
247   }
248   bool ret = false;
249   switch (prop->type) {
250     case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
251       if (prop->len >= static_cast<int>(sizeof(int))) {
252         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_TIMESTAMP,
253                                   reinterpret_cast<int*>(prop->val));
254       }
255       break;
256     case BT_PROPERTY_BDNAME: {
257       int len = prop->len;
258       if (remote_bd_addr) {
259         ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_NAME, reinterpret_cast<char*>(prop->val),
260                                   &len);
261       } else {
262         ret = btif_config_get_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_NAME,
263                                   reinterpret_cast<char*>(prop->val), &len);
264       }
265       if (ret && len && len <= prop->len) {
266         prop->len = len - 1;
267       } else {
268         prop->len = 0;
269         ret = false;
270       }
271       break;
272     }
273     case BT_PROPERTY_REMOTE_FRIENDLY_NAME: {
274       int len = prop->len;
275       ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_ALIAS, reinterpret_cast<char*>(prop->val),
276                                 &len);
277       if (ret && len && len <= prop->len) {
278         prop->len = len - 1;
279       } else {
280         prop->len = 0;
281         ret = false;
282       }
283       break;
284     }
285     case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT:
286       if (prop->len >= static_cast<int>(sizeof(int))) {
287         ret = btif_config_get_int(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_DISC_TIMEOUT,
288                                   reinterpret_cast<int*>(prop->val));
289       }
290       break;
291     case BT_PROPERTY_CLASS_OF_DEVICE:
292       if (prop->len >= static_cast<int>(sizeof(int))) {
293         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_CLASS,
294                                   reinterpret_cast<int*>(prop->val));
295       }
296       break;
297     case BT_PROPERTY_TYPE_OF_DEVICE:
298       if (prop->len >= static_cast<int>(sizeof(int))) {
299         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE,
300                                   reinterpret_cast<int*>(prop->val));
301       }
302       break;
303     case BT_PROPERTY_UUIDS: {
304       char value[1280];
305       int size = sizeof(value);
306       if (btif_config_get_str(bdstr, BTIF_STORAGE_KEY_REMOTE_SERVICE, value, &size)) {
307         Uuid* p_uuid = reinterpret_cast<Uuid*>(prop->val);
308         size_t num_uuids = btif_split_uuids_string(value, p_uuid, BT_MAX_NUM_UUIDS);
309         prop->len = num_uuids * sizeof(Uuid);
310         ret = true;
311       } else {
312         prop->val = NULL;
313         prop->len = 0;
314       }
315     } break;
316 
317     case BT_PROPERTY_REMOTE_VERSION_INFO: {
318       bt_remote_version_t* info = reinterpret_cast<bt_remote_version_t*>(prop->val);
319 
320       if (prop->len >= static_cast<int>(sizeof(bt_remote_version_t))) {
321         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, &info->manufacturer);
322 
323         if (ret) {
324           ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, &info->version);
325         }
326 
327         if (ret) {
328           ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, &info->sub_ver);
329         }
330       }
331     } break;
332 
333     case BT_PROPERTY_APPEARANCE: {
334       int val;
335 
336       if (prop->len >= static_cast<int>(sizeof(uint16_t))) {
337         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_APPEARANCE, &val);
338         *reinterpret_cast<uint16_t*>(prop->val) = (uint16_t)val;
339       }
340     } break;
341 
342     case BT_PROPERTY_VENDOR_PRODUCT_INFO: {
343       bt_vendor_product_info_t* info = reinterpret_cast<bt_vendor_product_info_t*>(prop->val);
344       int val;
345 
346       if (prop->len >= static_cast<int>(sizeof(bt_vendor_product_info_t))) {
347         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID_SOURCE, &val);
348         info->vendor_id_src = static_cast<uint8_t>(val);
349 
350         if (ret) {
351           ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID, &val);
352           info->vendor_id = static_cast<uint16_t>(val);
353         }
354         if (ret) {
355           ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_PRODUCT_ID, &val);
356           info->product_id = static_cast<uint16_t>(val);
357         }
358         if (ret) {
359           ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_VERSION, &val);
360           info->version = static_cast<uint16_t>(val);
361         }
362       }
363     } break;
364 
365     case BT_PROPERTY_REMOTE_MODEL_NUM: {
366       int len = prop->len;
367       ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_DIS_MODEL_NUM,
368                                 reinterpret_cast<char*>(prop->val), &len);
369       if (ret && len && len <= prop->len) {
370         prop->len = len - 1;
371       } else {
372         prop->len = 0;
373         ret = false;
374       }
375     } break;
376 
377     case BT_PROPERTY_REMOTE_ADDR_TYPE: {
378       int val;
379 
380       if (prop->len >= static_cast<int>(sizeof(uint8_t))) {
381         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_ADDR_TYPE, &val);
382         *reinterpret_cast<uint8_t*>(prop->val) = (uint8_t)val;
383       }
384     } break;
385 
386     case BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED: {
387       int val;
388 
389       if (prop->len >= static_cast<int>(sizeof(uint8_t))) {
390         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_SECURE_CONNECTIONS_SUPPORTED, &val);
391         *reinterpret_cast<uint8_t*>(prop->val) = (uint8_t)val;
392       }
393     } break;
394 
395     case BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE: {
396       int val;
397 
398       if (prop->len >= static_cast<int>(sizeof(uint8_t))) {
399         ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_MAX_SESSION_KEY_SIZE, &val);
400         *reinterpret_cast<uint8_t*>(prop->val) = (uint8_t)val;
401       }
402     } break;
403 
404     default:
405       log::error("Unknown prop type:{}", prop->type);
406       return false;
407   }
408   return ret;
409 }
410 
411 /*******************************************************************************
412  *
413  * Function         btif_in_fetch_bonded_devices
414  *
415  * Description      Helper function to fetch the bonded devices
416  *                  from NVRAM
417  *
418  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
419  *
420  ******************************************************************************/
btif_in_fetch_bonded_device(const std::string & bdstr)421 bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr) {
422   bool bt_linkkey_file_found = false;
423 
424   LinkKey link_key;
425   size_t size = link_key.size();
426   if (btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), &size)) {
427     int linkkey_type;
428     if (btif_config_get_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, &linkkey_type)) {
429       bt_linkkey_file_found = true;
430     } else {
431       bt_linkkey_file_found = false;
432     }
433   }
434   if ((btif_in_fetch_bonded_ble_device(bdstr, false, NULL) != BT_STATUS_SUCCESS) &&
435       (!bt_linkkey_file_found)) {
436     return BT_STATUS_DEVICE_NOT_FOUND;
437   }
438   return BT_STATUS_SUCCESS;
439 }
440 
441 /*******************************************************************************
442  *
443  * Function         btif_in_fetch_bonded_devices
444  *
445  * Description      Internal helper function to fetch the bonded devices
446  *                  from NVRAM
447  *
448  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
449  *
450  ******************************************************************************/
btif_in_fetch_bonded_devices(btif_bonded_devices_t * p_bonded_devices,int add)451 static bt_status_t btif_in_fetch_bonded_devices(btif_bonded_devices_t* p_bonded_devices, int add) {
452   memset(p_bonded_devices, 0, sizeof(btif_bonded_devices_t));
453 
454   bool bt_linkkey_file_found = false;
455   int device_type;
456 
457   for (const auto& bd_addr : btif_config_get_paired_devices()) {
458     auto name = bd_addr.ToString();
459 
460     log::verbose("Remote device:{}", bd_addr);
461     LinkKey link_key;
462     size_t size = sizeof(link_key);
463     if (btif_config_get_bin(name, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), &size)) {
464       int linkkey_type;
465       if (btif_config_get_int(name, BTIF_STORAGE_KEY_LINK_KEY_TYPE, &linkkey_type)) {
466         if (add) {
467           DEV_CLASS dev_class = {0, 0, 0};
468           int cod;
469           int pin_length = 0;
470           if (btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_CLASS, &cod)) {
471             dev_class = uint2devclass((uint32_t)cod);
472           }
473           btif_config_get_int(name, BTIF_STORAGE_KEY_PIN_LENGTH, &pin_length);
474           BTA_DmAddDevice(bd_addr, dev_class, link_key, (uint8_t)linkkey_type, pin_length);
475 
476           if (btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_TYPE, &device_type) &&
477               (device_type == BT_DEVICE_TYPE_DUMO)) {
478             btif_gatts_add_bonded_dev_from_nv(bd_addr);
479           }
480         }
481         bt_linkkey_file_found = true;
482         if (p_bonded_devices->num_devices < BTM_SEC_MAX_DEVICE_RECORDS) {
483           p_bonded_devices->devices[p_bonded_devices->num_devices++] = bd_addr;
484         } else {
485           log::warn("Exceed the max number of bonded devices");
486         }
487       } else {
488         bt_linkkey_file_found = false;
489       }
490     }
491     if (!btif_in_fetch_bonded_ble_device(name, add, p_bonded_devices) && !bt_linkkey_file_found) {
492       log::verbose("No link key or ble key found for device:{}", bd_addr);
493     }
494   }
495   return BT_STATUS_SUCCESS;
496 }
497 
btif_read_le_key(const uint8_t key_type,const size_t key_len,RawAddress bd_addr,const tBLE_ADDR_TYPE addr_type,const bool add_key,bool * device_added,bool * key_found)498 static void btif_read_le_key(const uint8_t key_type, const size_t key_len, RawAddress bd_addr,
499                              const tBLE_ADDR_TYPE addr_type, const bool add_key, bool* device_added,
500                              bool* key_found) {
501   log::assert_that(device_added != nullptr, "assert failed: device_added != nullptr");
502   log::assert_that(key_found != nullptr, "assert failed: key_found != nullptr");
503 
504   tBTA_LE_KEY_VALUE key;
505   memset(&key, 0, sizeof(key));
506 
507   if (btif_storage_get_ble_bonding_key(bd_addr, key_type, reinterpret_cast<uint8_t*>(&key),
508                                        key_len) == BT_STATUS_SUCCESS) {
509     if (add_key) {
510       if (!*device_added) {
511         BTA_DmAddBleDevice(bd_addr, addr_type, BT_DEVICE_TYPE_BLE);
512         *device_added = true;
513       }
514 
515       log::verbose("Adding key type {} for {}", key_type, bd_addr);
516       BTA_DmAddBleKey(bd_addr, &key, key_type);
517     }
518 
519     *key_found = true;
520   }
521 }
522 
523 /*******************************************************************************
524  * Functions
525  *
526  * Functions are synchronous and can be called by both from internal modules
527  * such as BTIF_DM and by external entiries from HAL via BTIF_context_switch.
528  * For OUT parameters, the caller is expected to provide the memory.
529  * Caller is expected to provide a valid pointer to 'property->value' based on
530  * the property->type.
531  ******************************************************************************/
532 
533 /*******************************************************************************
534  *
535  * Function         btif_split_uuids_string
536  *
537  * Description      Internal helper function to split the string of UUIDs
538  *                  read from the NVRAM to an array
539  *
540  * Returns          Number of UUIDs parsed from the supplied string
541  *
542  ******************************************************************************/
btif_split_uuids_string(const char * str,bluetooth::Uuid * p_uuid,size_t max_uuids)543 size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, size_t max_uuids) {
544   log::assert_that(str != nullptr, "assert failed: str != nullptr");
545   log::assert_that(p_uuid != nullptr, "assert failed: p_uuid != nullptr");
546 
547   size_t num_uuids = 0;
548   while (str && num_uuids < max_uuids) {
549     bool is_valid;
550     bluetooth::Uuid tmp = Uuid::FromString(std::string(str, Uuid::kString128BitLen), &is_valid);
551     if (!is_valid) {
552       break;
553     }
554 
555     *p_uuid = tmp;
556     p_uuid++;
557 
558     num_uuids++;
559     str = strchr(str, ' ');
560     if (str) {
561       str++;
562     }
563   }
564 
565   return num_uuids;
566 }
567 
568 /** Helper function for fetching a bt_property of the adapter. */
btif_storage_get_adapter_prop(bt_property_type_t type,void * buf,int size,bt_property_t * property)569 bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, int size,
570                                           bt_property_t* property) {
571   property->type = type;
572   property->val = buf;
573   property->len = size;
574   return btif_storage_get_adapter_property(property);
575 }
576 
577 /*******************************************************************************
578  *
579  * Function         btif_storage_get_adapter_property
580  *
581  * Description      BTIF storage API - Fetches the adapter property->type
582  *                  from NVRAM and fills property->val.
583  *                  Caller should provide memory for property->val and
584  *                  set the property->val
585  *
586  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
587  *                  BT_STATUS_FAIL otherwise
588  *
589  ******************************************************************************/
btif_storage_get_adapter_property(bt_property_t * property)590 bt_status_t btif_storage_get_adapter_property(bt_property_t* property) {
591   /* Special handling for adapter address and BONDED_DEVICES */
592   if (property->type == BT_PROPERTY_BDADDR) {
593     RawAddress* bd_addr = reinterpret_cast<RawAddress*>(property->val);
594     /* Fetch the local BD ADDR */
595     if (bluetooth::shim::GetController() == nullptr) {
596       log::error("Controller not ready! Unable to return Bluetooth Address");
597       *bd_addr = RawAddress::kEmpty;
598       return BT_STATUS_NOT_READY;
599     } else {
600       log::info("Controller ready!");
601       *bd_addr = bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress());
602     }
603     property->len = RawAddress::kLength;
604     return BT_STATUS_SUCCESS;
605   } else if (property->type == BT_PROPERTY_ADAPTER_BONDED_DEVICES) {
606     btif_bonded_devices_t bonded_devices;
607 
608     btif_in_fetch_bonded_devices(&bonded_devices, 0);
609 
610     log::verbose("BT_PROPERTY_ADAPTER_BONDED_DEVICES: Number of bonded devices={}",
611                  bonded_devices.num_devices);
612 
613     property->len = bonded_devices.num_devices * RawAddress::kLength;
614     memcpy(property->val, bonded_devices.devices, property->len);
615 
616     /* if there are no bonded_devices, then length shall be 0 */
617     return BT_STATUS_SUCCESS;
618   } else if (property->type == BT_PROPERTY_UUIDS) {
619     /* publish list of local supported services */
620     Uuid* p_uuid = reinterpret_cast<Uuid*>(property->val);
621     uint32_t num_uuids = 0;
622     uint32_t i;
623 
624     tBTA_SERVICE_MASK service_mask = btif_get_enabled_services_mask();
625     log::info("Service_mask=0x{:x}", service_mask);
626     for (i = 0; i < BTA_MAX_SERVICE_ID; i++) {
627       /* This should eventually become a function when more services are enabled
628        */
629       if (service_mask & (tBTA_SERVICE_MASK)(1 << i)) {
630         switch (i) {
631           case BTA_HFP_SERVICE_ID: {
632             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_AG_HANDSFREE);
633             num_uuids++;
634           }
635             FALLTHROUGH_INTENDED; /* FALLTHROUGH */
636           /* intentional fall through: Send both BFP & HSP UUIDs if HFP is
637            * enabled */
638           case BTA_HSP_SERVICE_ID: {
639             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY);
640             num_uuids++;
641           } break;
642           case BTA_A2DP_SOURCE_SERVICE_ID: {
643             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_AUDIO_SOURCE);
644             num_uuids++;
645           } break;
646           case BTA_A2DP_SINK_SERVICE_ID: {
647             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_AUDIO_SINK);
648             num_uuids++;
649           } break;
650           case BTA_PBAP_SERVICE_ID: {
651             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_PBAP_PSE);
652             num_uuids++;
653           } break;
654           case BTA_HFP_HS_SERVICE_ID: {
655             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_HF_HANDSFREE);
656             num_uuids++;
657           } break;
658           case BTA_MAP_SERVICE_ID: {
659             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_MESSAGE_ACCESS);
660             num_uuids++;
661           } break;
662           case BTA_MN_SERVICE_ID: {
663             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_MESSAGE_NOTIFICATION);
664             num_uuids++;
665           } break;
666           case BTA_PCE_SERVICE_ID: {
667             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_PBAP_PCE);
668             num_uuids++;
669           } break;
670         }
671       }
672     }
673     property->len = (num_uuids) * sizeof(Uuid);
674     return BT_STATUS_SUCCESS;
675   }
676 
677   /* fall through for other properties */
678   if (!cfg2prop(NULL, property)) {
679     return btif_dm_get_adapter_property(property);
680   }
681   return BT_STATUS_SUCCESS;
682 }
683 
684 /*******************************************************************************
685  *
686  * Function         btif_storage_set_adapter_property
687  *
688  * Description      BTIF storage API - Stores the adapter property
689  *                  to NVRAM
690  *
691  * Returns          BT_STATUS_SUCCESS if the store was successful,
692  *                  BT_STATUS_FAIL otherwise
693  *
694  ******************************************************************************/
btif_storage_set_adapter_property(bt_property_t * property)695 bt_status_t btif_storage_set_adapter_property(bt_property_t* property) {
696   return prop2cfg(NULL, property) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
697 }
698 
699 /** Helper function for fetching a bt_property of a remote device. */
btif_storage_get_remote_prop(RawAddress * remote_addr,bt_property_type_t type,void * buf,int size,bt_property_t * property)700 bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, bt_property_type_t type,
701                                          void* buf, int size, bt_property_t* property) {
702   property->type = type;
703   property->val = buf;
704   property->len = size;
705   return btif_storage_get_remote_device_property(remote_addr, property);
706 }
707 
708 /*******************************************************************************
709  *
710  * Function         btif_storage_get_remote_device_property
711  *
712  * Description      BTIF storage API - Fetches the remote device property->type
713  *                  from NVRAM and fills property->val.
714  *                  Caller should provide memory for property->val and
715  *                  set the property->val
716  *
717  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
718  *                  BT_STATUS_FAIL otherwise
719  *
720  ******************************************************************************/
btif_storage_get_remote_device_property(const RawAddress * remote_bd_addr,bt_property_t * property)721 bt_status_t btif_storage_get_remote_device_property(const RawAddress* remote_bd_addr,
722                                                     bt_property_t* property) {
723   return cfg2prop(remote_bd_addr, property) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
724 }
725 /*******************************************************************************
726  *
727  * Function         btif_storage_set_remote_device_property
728  *
729  * Description      BTIF storage API - Stores the remote device property
730  *                  to NVRAM
731  *
732  * Returns          BT_STATUS_SUCCESS if the store was successful,
733  *                  BT_STATUS_FAIL otherwise
734  *
735  ******************************************************************************/
btif_storage_set_remote_device_property(const RawAddress * remote_bd_addr,bt_property_t * property)736 bt_status_t btif_storage_set_remote_device_property(const RawAddress* remote_bd_addr,
737                                                     bt_property_t* property) {
738   return prop2cfg(remote_bd_addr, property) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
739 }
740 
741 /*******************************************************************************
742  *
743  * Function         btif_storage_add_remote_device
744  *
745  * Description      BTIF storage API - Adds a newly discovered device to NVRAM
746  *                  along with the timestamp. Also, stores the various
747  *                  properties - RSSI, BDADDR, NAME (if found in EIR)
748  *
749  * Returns          BT_STATUS_SUCCESS if the store was successful,
750  *                  BT_STATUS_FAIL otherwise
751  *
752  ******************************************************************************/
btif_storage_add_remote_device(const RawAddress * remote_bd_addr,uint32_t num_properties,bt_property_t * properties)753 bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr,
754                                            uint32_t num_properties, bt_property_t* properties) {
755   uint32_t i = 0;
756   /* TODO: If writing a property, fails do we go back undo the earlier
757    * written properties? */
758   for (i = 0; i < num_properties; i++) {
759     /* Ignore properties that are not stored in DB */
760     if (properties[i].type == BT_PROPERTY_REMOTE_RSSI ||
761         properties[i].type == BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER ||
762         properties[i].type == BT_PROPERTY_REMOTE_ASHA_CAPABILITY ||
763         properties[i].type == BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID) {
764       continue;
765     }
766 
767     /* address for remote device needs special handling as we also store
768      * timestamp */
769     if (properties[i].type == BT_PROPERTY_BDADDR) {
770       bt_property_t addr_prop;
771       memcpy(&addr_prop, &properties[i], sizeof(bt_property_t));
772       addr_prop.type = (bt_property_type_t)BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP;
773       btif_storage_set_remote_device_property(remote_bd_addr, &addr_prop);
774     } else {
775       btif_storage_set_remote_device_property(remote_bd_addr, &properties[i]);
776     }
777   }
778   return BT_STATUS_SUCCESS;
779 }
780 
781 /*******************************************************************************
782  *
783  * Function         btif_storage_add_bonded_device
784  *
785  * Description      BTIF storage API - Adds the newly bonded device to NVRAM
786  *                  along with the link-key, Key type and Pin key length
787  *
788  * Returns          BT_STATUS_SUCCESS if the store was successful,
789  *                  BT_STATUS_FAIL otherwise
790  *
791  ******************************************************************************/
792 
btif_storage_add_bonded_device(RawAddress * remote_bd_addr,LinkKey link_key,uint8_t key_type,uint8_t pin_length)793 bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, LinkKey link_key,
794                                            uint8_t key_type, uint8_t pin_length) {
795   std::string bdstr = remote_bd_addr->ToString();
796   bool ret = btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, static_cast<int>(key_type));
797   ret &= btif_config_set_int(bdstr, BTIF_STORAGE_KEY_PIN_LENGTH, static_cast<int>(pin_length));
798   ret &= btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), link_key.size());
799 
800   if (ret) {
801     btif_storage_set_mode(remote_bd_addr);
802   }
803   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
804 }
805 
806 /*******************************************************************************
807  *
808  * Function         btif_storage_remove_bonded_device
809  *
810  * Description      BTIF storage API - Deletes the bonded device from NVRAM
811  *
812  * Returns          BT_STATUS_SUCCESS if the deletion was successful,
813  *                  BT_STATUS_FAIL otherwise
814  *
815  ******************************************************************************/
btif_storage_remove_bonded_device(const RawAddress * remote_bd_addr)816 bt_status_t btif_storage_remove_bonded_device(const RawAddress* remote_bd_addr) {
817   std::string bdstr = remote_bd_addr->ToString();
818   log::info("Removing bonded device addr={}", *remote_bd_addr);
819 
820   btif_config_remove_device(bdstr);
821 
822   return BT_STATUS_SUCCESS;
823 }
824 
825 /* Some devices hardcode sample LTK value from spec, instead of generating one.
826  * Treat such devices as insecure, and remove such bonds when bluetooth
827  * restarts. Removing them after disconnection is handled separately.
828  *
829  * We still allow such devices to bond in order to give the user a chance to
830  * update firmware.
831  */
remove_devices_with_sample_ltk()832 static void remove_devices_with_sample_ltk() {
833   std::vector<RawAddress> bad_ltk;
834   for (const auto& bd_addr : btif_config_get_paired_devices()) {
835     auto name = bd_addr.ToString();
836 
837     tBTA_LE_KEY_VALUE key;
838     memset(&key, 0, sizeof(key));
839 
840     if (btif_storage_get_ble_bonding_key(bd_addr, BTM_LE_KEY_PENC, reinterpret_cast<uint8_t*>(&key),
841                                          sizeof(tBTM_LE_PENC_KEYS)) == BT_STATUS_SUCCESS) {
842       if (is_sample_ltk(key.penc_key.ltk)) {
843         bad_ltk.push_back(bd_addr);
844       }
845     }
846   }
847 
848   for (RawAddress address : bad_ltk) {
849     log::error("Removing bond to device using test TLK: {}", address);
850 
851     btif_storage_remove_bonded_device(&address);
852   }
853 }
854 
855 /*******************************************************************************
856  *
857  * Function         btif_storage_load_le_devices
858  *
859  * Description      BTIF storage API - Loads all LE-only and Dual Mode devices
860  *                  from NVRAM. This API invokes the adaper_properties_cb.
861  *                  It also invokes invoke_address_consolidate_cb
862  *                  to consolidate each Dual Mode device and
863  *                  invoke_le_address_associate_cb to associate each LE-only
864  *                  device between its RPA, identity address, and identity address type.
865  *
866  ******************************************************************************/
btif_storage_load_le_devices(void)867 void btif_storage_load_le_devices(void) {
868   btif_bonded_devices_t bonded_devices;
869   btif_in_fetch_bonded_devices(&bonded_devices, 1);
870   std::unordered_set<RawAddress> bonded_addresses;
871   for (uint16_t i = 0; i < bonded_devices.num_devices; i++) {
872     bonded_addresses.insert(bonded_devices.devices[i]);
873   }
874 
875   std::vector<std::tuple<RawAddress, RawAddress, tBLE_ADDR_TYPE>> consolidated_devices;
876   for (uint16_t i = 0; i < bonded_devices.num_devices; i++) {
877     // RawAddress* p_remote_addr;
878     tBTA_LE_KEY_VALUE key = {};
879     if (btif_storage_get_ble_bonding_key(bonded_devices.devices[i], BTM_LE_KEY_PID,
880                                          reinterpret_cast<uint8_t*>(&key),
881                                          sizeof(tBTM_LE_PID_KEYS)) == BT_STATUS_SUCCESS) {
882       if (bonded_devices.devices[i] != key.pid_key.identity_addr) {
883         log::info("Found device with a known identity address {} {}", bonded_devices.devices[i],
884                   key.pid_key.identity_addr);
885 
886         if (bonded_devices.devices[i].IsEmpty() || key.pid_key.identity_addr.IsEmpty()) {
887           log::warn("Address is empty! Skip");
888         } else {
889           consolidated_devices.emplace_back(bonded_devices.devices[i], key.pid_key.identity_addr,
890                                             key.pid_key.identity_addr_type);
891         }
892       }
893     }
894   }
895 
896   bt_property_t adapter_prop = {};
897   /* Send the adapter_properties_cb with bonded consolidated device */
898   {
899     /* BONDED_DEVICES */
900     auto devices_list = std::make_unique<RawAddress[]>(consolidated_devices.size());
901     adapter_prop.type = BT_PROPERTY_ADAPTER_BONDED_DEVICES;
902     adapter_prop.len = consolidated_devices.size() * sizeof(RawAddress);
903     adapter_prop.val = devices_list.get();
904     for (uint16_t i = 0; i < consolidated_devices.size(); i++) {
905       devices_list[i] = std::get<0>(consolidated_devices[i]);
906     }
907     btif_adapter_properties_evt(BT_STATUS_SUCCESS, /* num_props */ 1, &adapter_prop);
908   }
909 
910   for (const auto& device : consolidated_devices) {
911     if (bonded_addresses.find(std::get<1>(device)) != bonded_addresses.end()) {
912       // Invokes address consolidation for DuMo devices
913       GetInterfaceToProfiles()->events->invoke_address_consolidate_cb(std::get<0>(device),
914                                                                       std::get<1>(device));
915     } else {
916       // Associates RPA & identity address for LE-only devices
917       GetInterfaceToProfiles()->events->invoke_le_address_associate_cb(
918               std::get<0>(device), std::get<1>(device), std::get<2>(device));
919     }
920   }
921 }
922 
923 /*******************************************************************************
924  *
925  * Function         btif_storage_load_bonded_devices
926  *
927  * Description      BTIF storage API - Loads all the bonded devices from NVRAM
928  *                  and adds to the BTA.
929  *                  Additionally, this API also invokes the adaper_properties_cb
930  *                  and remote_device_properties_cb for each of the bonded
931  *                  devices.
932  *
933  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
934  *
935  ******************************************************************************/
btif_storage_load_bonded_devices(void)936 bt_status_t btif_storage_load_bonded_devices(void) {
937   btif_bonded_devices_t bonded_devices;
938   uint32_t i = 0;
939   bt_property_t adapter_props[6];
940   uint32_t num_props = 0;
941   bt_property_t remote_properties[10];
942   RawAddress addr;
943   bt_bdname_t name, alias, model_name;
944   bt_scan_mode_t mode;
945   uint32_t disc_timeout;
946   Uuid local_uuids[BT_MAX_NUM_UUIDS];
947   Uuid remote_uuids[BT_MAX_NUM_UUIDS];
948   bt_status_t status;
949 
950   remove_devices_with_sample_ltk();
951 
952   btif_in_fetch_bonded_devices(&bonded_devices, 1);
953 
954   /* Now send the adapter_properties_cb with all adapter_properties */
955   {
956     memset(adapter_props, 0, sizeof(adapter_props));
957 
958     /* address */
959     status = btif_storage_get_adapter_prop(BT_PROPERTY_BDADDR, &addr, sizeof(addr),
960                                            &adapter_props[num_props]);
961     // Add BT_PROPERTY_BDADDR property into list only when successful.
962     // Otherwise, skip this property entry.
963     if (status == BT_STATUS_SUCCESS) {
964       num_props++;
965     }
966 
967     /* BD_NAME */
968     btif_storage_get_adapter_prop(BT_PROPERTY_BDNAME, &name, sizeof(name),
969                                   &adapter_props[num_props]);
970     num_props++;
971 
972     /* DISC_TIMEOUT */
973     btif_storage_get_adapter_prop(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, &disc_timeout,
974                                   sizeof(disc_timeout), &adapter_props[num_props]);
975     num_props++;
976 
977     /* BONDED_DEVICES */
978     RawAddress* devices_list = reinterpret_cast<RawAddress*>(
979             osi_malloc(sizeof(RawAddress) * bonded_devices.num_devices));
980     adapter_props[num_props].type = BT_PROPERTY_ADAPTER_BONDED_DEVICES;
981     adapter_props[num_props].len = bonded_devices.num_devices * sizeof(RawAddress);
982     adapter_props[num_props].val = devices_list;
983     for (i = 0; i < bonded_devices.num_devices; i++) {
984       devices_list[i] = bonded_devices.devices[i];
985     }
986     num_props++;
987 
988     /* LOCAL UUIDs */
989     btif_storage_get_adapter_prop(BT_PROPERTY_UUIDS, local_uuids, sizeof(local_uuids),
990                                   &adapter_props[num_props]);
991     num_props++;
992 
993     btif_adapter_properties_evt(BT_STATUS_SUCCESS, num_props, adapter_props);
994 
995     osi_free(devices_list);
996   }
997 
998   log::verbose("Number of bonded devices found={}", bonded_devices.num_devices);
999 
1000   {
1001     for (i = 0; i < bonded_devices.num_devices; i++) {
1002       RawAddress* p_remote_addr;
1003 
1004       /*
1005        * TODO: improve handling of missing fields in NVRAM.
1006        */
1007       uint32_t cod = 0;
1008       uint32_t devtype = 0;
1009 
1010       num_props = 0;
1011       p_remote_addr = &bonded_devices.devices[i];
1012       memset(remote_properties, 0, sizeof(remote_properties));
1013       btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_BDNAME, &name, sizeof(name),
1014                                    &remote_properties[num_props]);
1015       num_props++;
1016 
1017       btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_REMOTE_FRIENDLY_NAME, &alias,
1018                                    sizeof(alias), &remote_properties[num_props]);
1019       num_props++;
1020 
1021       btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_CLASS_OF_DEVICE, &cod, sizeof(cod),
1022                                    &remote_properties[num_props]);
1023       num_props++;
1024 
1025       btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_TYPE_OF_DEVICE, &devtype,
1026                                    sizeof(devtype), &remote_properties[num_props]);
1027       num_props++;
1028 
1029       btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_UUIDS, remote_uuids,
1030                                    sizeof(remote_uuids), &remote_properties[num_props]);
1031       num_props++;
1032 
1033       // Floss needs appearance for metrics purposes
1034       uint16_t appearance = 0;
1035       if (btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_APPEARANCE, &appearance,
1036                                        sizeof(appearance),
1037                                        &remote_properties[num_props]) == BT_STATUS_SUCCESS) {
1038         num_props++;
1039       }
1040 
1041 #if TARGET_FLOSS
1042       // Floss needs VID:PID for metrics purposes
1043       bt_vendor_product_info_t vp_info;
1044       if (btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_VENDOR_PRODUCT_INFO, &vp_info,
1045                                        sizeof(vp_info),
1046                                        &remote_properties[num_props]) == BT_STATUS_SUCCESS) {
1047         num_props++;
1048       }
1049 
1050       // Floss needs address type for diagnosis API
1051       uint8_t addr_type;
1052       if (btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_REMOTE_ADDR_TYPE, &addr_type,
1053                                        sizeof(addr_type),
1054                                        &remote_properties[num_props]) == BT_STATUS_SUCCESS) {
1055         num_props++;
1056       }
1057 #endif
1058 
1059       btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_REMOTE_MODEL_NUM, &model_name,
1060                                    sizeof(model_name), &remote_properties[num_props]);
1061       num_props++;
1062 
1063       btif_remote_properties_evt(BT_STATUS_SUCCESS, p_remote_addr, num_props, remote_properties);
1064     }
1065   }
1066   return BT_STATUS_SUCCESS;
1067 }
1068 
1069 /*******************************************************************************
1070  *
1071  * Function         btif_storage_add_ble_bonding_key
1072  *
1073  * Description      BTIF storage API - Adds the newly bonded device to NVRAM
1074  *                  along with the ble-key, Key type and Pin key length
1075  *
1076  * Returns          BT_STATUS_SUCCESS if the store was successful,
1077  *                  BT_STATUS_FAIL otherwise
1078  *
1079  ******************************************************************************/
1080 
btif_storage_add_ble_bonding_key(RawAddress * remote_bd_addr,const uint8_t * key_value,uint8_t key_type,uint8_t key_length)1081 bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, const uint8_t* key_value,
1082                                              uint8_t key_type, uint8_t key_length) {
1083   for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) {
1084     auto key = BTIF_STORAGE_LE_KEYS[i];
1085     if (key.type == key_type) {
1086       bool ret = btif_config_set_bin(remote_bd_addr->ToString(), key.name, key_value, key_length);
1087 
1088       if (ret) {
1089         btif_storage_set_mode(remote_bd_addr);
1090       }
1091       return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1092     }
1093   }
1094 
1095   log::warn("Unknown LE key type: {}", key_type);
1096   return BT_STATUS_FAIL;
1097 }
1098 
1099 /*******************************************************************************
1100  *
1101  * Function         btif_storage_get_ble_bonding_key
1102  *
1103  * Description
1104  *
1105  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
1106  *                  BT_STATUS_FAIL otherwise
1107  *
1108  ******************************************************************************/
btif_storage_get_ble_bonding_key(const RawAddress & remote_bd_addr,uint8_t key_type,uint8_t * key_value,int key_length)1109 bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, uint8_t key_type,
1110                                              uint8_t* key_value, int key_length) {
1111   for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) {
1112     auto key = BTIF_STORAGE_LE_KEYS[i];
1113     if (key.type == key_type) {
1114       size_t length = key_length;
1115       bool ret = btif_config_get_bin(remote_bd_addr.ToString(), key.name, key_value, &length);
1116       return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1117     }
1118   }
1119 
1120   log::warn("Unknown LE key type: {}", key_type);
1121   return BT_STATUS_FAIL;
1122 }
1123 
1124 /*******************************************************************************
1125  *
1126  * Function         btif_storage_remove_ble_keys
1127  *
1128  * Description      BTIF storage API - Deletes the bonded device from NVRAM
1129  *
1130  * Returns          BT_STATUS_SUCCESS if the deletion was successful,
1131  *                  BT_STATUS_FAIL otherwise
1132  *
1133  ******************************************************************************/
btif_storage_remove_ble_bonding_keys(const RawAddress * remote_bd_addr)1134 bt_status_t btif_storage_remove_ble_bonding_keys(const RawAddress* remote_bd_addr) {
1135   std::string bdstr = remote_bd_addr->ToString();
1136   log::info("Removing bonding keys for bd addr:{}", *remote_bd_addr);
1137   bool ret = true;
1138   for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) {
1139     auto key_name = BTIF_STORAGE_LE_KEYS[i].name;
1140     if (btif_config_exist(bdstr, key_name)) {
1141       ret &= btif_config_remove(bdstr, key_name);
1142     }
1143   }
1144 
1145   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1146 }
1147 
1148 /*******************************************************************************
1149  *
1150  * Function         btif_storage_add_ble_local_key
1151  *
1152  * Description      BTIF storage API - Adds the ble key to NVRAM
1153  *
1154  * Returns          BT_STATUS_SUCCESS if the store was successful,
1155  *                  BT_STATUS_FAIL otherwise
1156  *
1157  ******************************************************************************/
btif_storage_add_ble_local_key(const Octet16 & key_value,uint8_t key_type)1158 bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value, uint8_t key_type) {
1159   for (size_t i = 0; i < std::size(BTIF_STORAGE_LOCAL_LE_KEYS); i++) {
1160     auto key = BTIF_STORAGE_LOCAL_LE_KEYS[i];
1161     if (key.type == key_type) {
1162       bool ret = btif_config_set_bin(BTIF_STORAGE_SECTION_ADAPTER, key.name, key_value.data(),
1163                                      key_value.size());
1164 
1165       return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1166     }
1167   }
1168   log::warn("Unknown LE key type: {}", key_type);
1169   return BT_STATUS_FAIL;
1170 }
1171 
1172 /** Stores local key of |key_type| into |key_value|
1173  * Returns BT_STATUS_SUCCESS if the fetch was successful, BT_STATUS_FAIL
1174  * otherwise
1175  */
btif_storage_get_ble_local_key(uint8_t key_type,Octet16 * key_value)1176 bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, Octet16* key_value) {
1177   for (size_t i = 0; i < std::size(BTIF_STORAGE_LOCAL_LE_KEYS); i++) {
1178     auto key = BTIF_STORAGE_LOCAL_LE_KEYS[i];
1179     if (key.type == key_type) {
1180       size_t length = key_value->size();
1181       bool ret = btif_config_get_bin(BTIF_STORAGE_SECTION_ADAPTER, key.name, key_value->data(),
1182                                      &length);
1183 
1184       return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1185     }
1186   }
1187   log::warn("Unknown LE key type: {}", key_type);
1188   return BT_STATUS_FAIL;
1189 }
1190 
btif_in_fetch_bonded_ble_device(const std::string & remote_bd_addr,int add,btif_bonded_devices_t * p_bonded_devices)1191 bt_status_t btif_in_fetch_bonded_ble_device(const std::string& remote_bd_addr, int add,
1192                                             btif_bonded_devices_t* p_bonded_devices) {
1193   int device_type;
1194   tBLE_ADDR_TYPE addr_type;
1195   bool device_added = false;
1196   bool key_found = false;
1197   RawAddress bd_addr;
1198 
1199   RawAddress::FromString(remote_bd_addr, bd_addr);
1200 
1201   if (!btif_config_get_int(remote_bd_addr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type)) {
1202     return BT_STATUS_FAIL;
1203   }
1204 
1205   if ((device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE ||
1206       btif_has_ble_keys(remote_bd_addr)) {
1207     log::verbose("Found a LE device: {}", bd_addr);
1208 
1209     if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != BT_STATUS_SUCCESS) {
1210       addr_type = BLE_ADDR_PUBLIC;
1211       btif_storage_set_remote_addr_type(&bd_addr, BLE_ADDR_PUBLIC);
1212     }
1213 
1214     for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) {
1215       auto key = BTIF_STORAGE_LE_KEYS[i];
1216       btif_read_le_key(key.type, key.size, bd_addr, addr_type, add, &device_added, &key_found);
1217     }
1218 
1219     // Fill in the bonded devices
1220     if (device_added) {
1221       if (p_bonded_devices->num_devices < BTM_SEC_MAX_DEVICE_RECORDS) {
1222         p_bonded_devices->devices[p_bonded_devices->num_devices++] = bd_addr;
1223       } else {
1224         log::warn("Exceed the max number of bonded devices");
1225       }
1226       btif_gatts_add_bonded_dev_from_nv(bd_addr);
1227     }
1228 
1229     if (key_found) {
1230       return BT_STATUS_SUCCESS;
1231     }
1232   }
1233   return BT_STATUS_DEVICE_NOT_FOUND;
1234 }
1235 
btif_storage_invoke_addr_type_update(const RawAddress & remote_bd_addr,const tBLE_ADDR_TYPE & addr_type)1236 void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr,
1237                                           const tBLE_ADDR_TYPE& addr_type) {
1238   bt_property_t prop;
1239   prop.type = BT_PROPERTY_REMOTE_ADDR_TYPE;
1240   prop.val = const_cast<tBLE_ADDR_TYPE*>(reinterpret_cast<const tBLE_ADDR_TYPE*>(&addr_type));
1241   prop.len = sizeof(tBLE_ADDR_TYPE);
1242   GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS,
1243                                                                        remote_bd_addr, 1, &prop);
1244 }
1245 
btif_storage_set_remote_addr_type(const RawAddress * remote_bd_addr,tBLE_ADDR_TYPE addr_type)1246 bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr,
1247                                               tBLE_ADDR_TYPE addr_type) {
1248   bool ret = btif_config_set_int(remote_bd_addr->ToString(), BTIF_STORAGE_KEY_ADDR_TYPE,
1249                                  static_cast<int>(addr_type));
1250 
1251 #if TARGET_FLOSS
1252   // Floss needs to get address type for diagnosis API.
1253   btif_storage_invoke_addr_type_update(*remote_bd_addr, addr_type);
1254 #endif
1255 
1256   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1257 }
1258 
btif_has_ble_keys(const std::string & bdstr)1259 bool btif_has_ble_keys(const std::string& bdstr) {
1260   return btif_config_exist(bdstr, BTIF_STORAGE_KEY_LE_KEY_PENC);
1261 }
1262 
1263 /*******************************************************************************
1264  *
1265  * Function         btif_storage_get_remote_addr_type
1266  *
1267  * Description      BTIF storage API - Fetches the remote addr type
1268  *
1269  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
1270  *                  BT_STATUS_FAIL otherwise
1271  *
1272  ******************************************************************************/
btif_storage_get_remote_addr_type(const RawAddress * remote_bd_addr,tBLE_ADDR_TYPE * addr_type)1273 bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr,
1274                                               tBLE_ADDR_TYPE* addr_type) {
1275   int val;
1276   bool ret = btif_config_get_int(remote_bd_addr->ToString(), BTIF_STORAGE_KEY_ADDR_TYPE, &val);
1277   *addr_type = static_cast<tBLE_ADDR_TYPE>(val);
1278   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1279 }
1280 
1281 /** Stores information about GATT server supported features */
btif_storage_set_gatt_sr_supp_feat(const RawAddress & addr,uint8_t feat)1282 void btif_storage_set_gatt_sr_supp_feat(const RawAddress& addr, uint8_t feat) {
1283   do_in_jni_thread(Bind(
1284           [](const RawAddress& addr, uint8_t feat) {
1285             std::string bdstr = addr.ToString();
1286             log::verbose(
1287                     "GATT server supported features for: {} features: "
1288                     "{}",
1289                     addr, feat);
1290             btif_config_set_int(bdstr, BTIF_STORAGE_KEY_GATT_SERVER_SUPPORTED, feat);
1291           },
1292           addr, feat));
1293 }
1294 
1295 /** Gets information about GATT server supported features */
btif_storage_get_sr_supp_feat(const RawAddress & bd_addr)1296 uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) {
1297   auto name = bd_addr.ToString();
1298 
1299   int value = 0;
1300   btif_config_get_int(name, BTIF_STORAGE_KEY_GATT_SERVER_SUPPORTED, &value);
1301   log::verbose("Remote device: {} GATT server supported features 0x{:02x}", bd_addr, value);
1302 
1303   return value;
1304 }
1305 
1306 /*******************************************************************************
1307  *
1308  * Function         btif_storage_is_restricted_device
1309  *
1310  * Description      BTIF storage API - checks if this device is a restricted
1311  *                  device
1312  *
1313  * Returns          true  if the device is labeled as restricted
1314  *                  false otherwise
1315  *
1316  ******************************************************************************/
btif_storage_is_restricted_device(const RawAddress * remote_bd_addr)1317 bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) {
1318   int val;
1319   return btif_config_get_int(remote_bd_addr->ToString(), BTIF_STORAGE_KEY_RESTRICTED, &val);
1320 }
1321 
1322 /*******************************************************************************
1323  *
1324  * Function         btif_storage_prune_devices
1325  *
1326  * Description      Removes restricted mode devices in non-restricted mode
1327  *
1328  * Returns          none
1329  *
1330  ******************************************************************************/
btif_storage_prune_devices()1331 void btif_storage_prune_devices() {
1332   if (GetInterfaceToProfiles()->config->isRestrictedMode()) {
1333     int user_id = btif_storage_get_user_id();
1334 
1335     // Remove the devices with different user id
1336     for (const auto& bd_addr : btif_config_get_paired_devices()) {
1337       auto name = bd_addr.ToString();
1338       int id = 0;
1339       if (btif_config_get_int(name, BTIF_STORAGE_KEY_RESTRICTED, &id)) {
1340         // Restricted device, remove if user ID is different
1341         if (id != user_id) {
1342           log::info("Removing {} since user changed from {} to {}", bd_addr, id, user_id);
1343           btif_config_remove_device(name);
1344         }
1345       }
1346     }
1347   } else {
1348     // Default user, remove all restricted devices
1349     btif_config_remove_device_with_key(BTIF_STORAGE_KEY_RESTRICTED);
1350   }
1351 }
1352 
1353 // Get the name of a device from btif for interop database matching.
btif_storage_get_stored_remote_name(const RawAddress & bd_addr,char * name)1354 bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, char* name) {
1355   bt_property_t property;
1356   property.type = BT_PROPERTY_BDNAME;
1357   property.len = BD_NAME_LEN;
1358   property.val = name;
1359 
1360   return btif_storage_get_remote_device_property(&bd_addr, &property) == BT_STATUS_SUCCESS;
1361 }
1362 
1363 // Get the Class of Device.
btif_storage_get_cod(const RawAddress & bd_addr,uint32_t * cod)1364 bool btif_storage_get_cod(const RawAddress& bd_addr, uint32_t* cod) {
1365   bt_property_t property;
1366   property.type = BT_PROPERTY_CLASS_OF_DEVICE;
1367   property.len = sizeof(*cod);
1368   property.val = cod;
1369 
1370   return btif_storage_get_remote_device_property(&bd_addr, &property) == BT_STATUS_SUCCESS;
1371 }
1372 
1373 /** Stores information about GATT Client supported features support */
btif_storage_set_gatt_cl_supp_feat(const RawAddress & bd_addr,uint8_t feat)1374 void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, uint8_t feat) {
1375   do_in_jni_thread(Bind(
1376           [](const RawAddress& bd_addr, uint8_t feat) {
1377             std::string bdstr = bd_addr.ToString();
1378             log::verbose("saving gatt client supported feat: {}", bd_addr);
1379             btif_config_set_int(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED, feat);
1380           },
1381           bd_addr, feat));
1382 }
1383 
1384 /** Get client supported features */
btif_storage_get_gatt_cl_supp_feat(const RawAddress & bd_addr)1385 uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) {
1386   auto name = bd_addr.ToString();
1387 
1388   int value = 0;
1389   btif_config_get_int(name, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED, &value);
1390   log::verbose("Remote device: {} GATT client supported features 0x{:02x}", bd_addr, value);
1391 
1392   return value;
1393 }
1394 
1395 /** Remove client supported features */
btif_storage_remove_gatt_cl_supp_feat(const RawAddress & bd_addr)1396 void btif_storage_remove_gatt_cl_supp_feat(const RawAddress& bd_addr) {
1397   do_in_jni_thread(Bind(
1398           [](const RawAddress& bd_addr) {
1399             auto bdstr = bd_addr.ToString();
1400             if (btif_config_exist(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED)) {
1401               btif_config_remove(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED);
1402             }
1403           },
1404           bd_addr));
1405 }
1406 
1407 /** Store last server database hash for remote client */
btif_storage_set_gatt_cl_db_hash(const RawAddress & bd_addr,Octet16 hash)1408 void btif_storage_set_gatt_cl_db_hash(const RawAddress& bd_addr, Octet16 hash) {
1409   do_in_jni_thread(Bind(
1410           [](const RawAddress& bd_addr, Octet16 hash) {
1411             auto bdstr = bd_addr.ToString();
1412             btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH, hash.data(),
1413                                 hash.size());
1414           },
1415           bd_addr, hash));
1416 }
1417 
1418 /** Get last server database hash for remote client */
btif_storage_get_gatt_cl_db_hash(const RawAddress & bd_addr)1419 Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) {
1420   auto bdstr = bd_addr.ToString();
1421 
1422   Octet16 hash;
1423   size_t size = hash.size();
1424   btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH, hash.data(), &size);
1425 
1426   return hash;
1427 }
1428 
1429 /** Remove las server database hash for remote client */
btif_storage_remove_gatt_cl_db_hash(const RawAddress & bd_addr)1430 void btif_storage_remove_gatt_cl_db_hash(const RawAddress& bd_addr) {
1431   do_in_jni_thread(Bind(
1432           [](const RawAddress& bd_addr) {
1433             auto bdstr = bd_addr.ToString();
1434             if (btif_config_exist(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH)) {
1435               btif_config_remove(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH);
1436             }
1437           },
1438           bd_addr));
1439 }
1440 
btif_debug_linkkey_type_dump(int fd)1441 void btif_debug_linkkey_type_dump(int fd) {
1442   dprintf(fd, "\nLink Key Types:\n");
1443   for (const auto& bd_addr : btif_config_get_paired_devices()) {
1444     auto bdstr = bd_addr.ToString();
1445     int linkkey_type;
1446     dprintf(fd, "  %s\n", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
1447 
1448     dprintf(fd, "    BR: ");
1449     if (btif_config_get_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, &linkkey_type)) {
1450       dprintf(fd, "%s", linkkey_type_text(linkkey_type).c_str());
1451     }
1452     dprintf(fd, "\n");
1453 
1454     dprintf(fd, "    LE:");
1455     for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) {
1456       const std::string& key_name = BTIF_STORAGE_LE_KEYS[i].name;
1457       if (btif_config_exist(bdstr, key_name)) {
1458         dprintf(fd, " %s", key_name.c_str());
1459       }
1460     }
1461 
1462     dprintf(fd, "\n");
1463   }
1464 }
1465