• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
33 #include "btif_storage.h"
34 
35 #include <alloca.h>
36 #include <base/logging.h>
37 #include <ctype.h>
38 #include <log/log.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 
43 #include "bt_common.h"
44 #include "bta_hd_api.h"
45 #include "bta_hearing_aid_api.h"
46 #include "bta_hh_api.h"
47 #include "btif_api.h"
48 #include "btif_config.h"
49 #include "btif_hd.h"
50 #include "btif_hh.h"
51 #include "btif_util.h"
52 #include "device/include/controller.h"
53 #include "osi/include/allocator.h"
54 #include "osi/include/compat.h"
55 #include "osi/include/config.h"
56 #include "osi/include/log.h"
57 #include "osi/include/osi.h"
58 
59 using base::Bind;
60 using bluetooth::Uuid;
61 
62 /*******************************************************************************
63  *  Constants & Macros
64  ******************************************************************************/
65 
66 // TODO(armansito): Find a better way than using a hardcoded path.
67 #define BTIF_STORAGE_PATH_BLUEDROID "/data/misc/bluedroid"
68 
69 //#define BTIF_STORAGE_PATH_ADAPTER_INFO "adapter_info"
70 //#define BTIF_STORAGE_PATH_REMOTE_DEVICES "remote_devices"
71 #define BTIF_STORAGE_PATH_REMOTE_DEVTIME "Timestamp"
72 #define BTIF_STORAGE_PATH_REMOTE_DEVCLASS "DevClass"
73 #define BTIF_STORAGE_PATH_REMOTE_DEVTYPE "DevType"
74 #define BTIF_STORAGE_PATH_REMOTE_NAME "Name"
75 #define BTIF_STORAGE_PATH_REMOTE_VER_MFCT "Manufacturer"
76 #define BTIF_STORAGE_PATH_REMOTE_VER_VER "LmpVer"
77 #define BTIF_STORAGE_PATH_REMOTE_VER_SUBVER "LmpSubVer"
78 
79 //#define BTIF_STORAGE_PATH_REMOTE_LINKKEYS "remote_linkkeys"
80 #define BTIF_STORAGE_PATH_REMOTE_ALIASE "Aliase"
81 #define BTIF_STORAGE_PATH_REMOTE_SERVICE "Service"
82 #define BTIF_STORAGE_PATH_REMOTE_HIDINFO "HidInfo"
83 #define BTIF_STORAGE_KEY_ADAPTER_NAME "Name"
84 #define BTIF_STORAGE_KEY_ADAPTER_SCANMODE "ScanMode"
85 #define BTIF_STORAGE_KEY_LOCAL_IO_CAPS "LocalIOCaps"
86 #define BTIF_STORAGE_KEY_LOCAL_IO_CAPS_BLE "LocalIOCapsBLE"
87 #define BTIF_STORAGE_KEY_ADAPTER_DISC_TIMEOUT "DiscoveryTimeout"
88 
89 /* This is a local property to add a device found */
90 #define BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP 0xFF
91 
92 // TODO: This macro should be converted to a function
93 #define BTIF_STORAGE_GET_ADAPTER_PROP(s, t, v, l, p) \
94   do {                                               \
95     (p).type = (t);                                  \
96     (p).val = (v);                                   \
97     (p).len = (l);                                   \
98     (s) = btif_storage_get_adapter_property(&(p));   \
99   } while (0)
100 
101 // TODO: This macro should be converted to a function
102 #define BTIF_STORAGE_GET_REMOTE_PROP(b, t, v, l, p)     \
103   do {                                                  \
104     (p).type = (t);                                     \
105     (p).val = (v);                                      \
106     (p).len = (l);                                      \
107     btif_storage_get_remote_device_property((b), &(p)); \
108   } while (0)
109 
110 #define STORAGE_BDADDR_STRING_SZ (18) /* 00:11:22:33:44:55 */
111 #define STORAGE_UUID_STRING_SIZE \
112   (36 + 1) /* 00001200-0000-1000-8000-00805f9b34fb; */
113 #define STORAGE_PINLEN_STRING_MAX_SIZE (2)  /* ascii pinlen max chars */
114 #define STORAGE_KEYTYPE_STRING_MAX_SIZE (1) /* ascii keytype max chars */
115 
116 #define STORAGE_KEY_TYPE_MAX (10)
117 
118 #define STORAGE_HID_ATRR_MASK_SIZE (4)
119 #define STORAGE_HID_SUB_CLASS_SIZE (2)
120 #define STORAGE_HID_APP_ID_SIZE (2)
121 #define STORAGE_HID_VENDOR_ID_SIZE (4)
122 #define STORAGE_HID_PRODUCT_ID_SIZE (4)
123 #define STORAGE_HID_VERSION_SIZE (4)
124 #define STORAGE_HID_CTRY_CODE_SIZE (2)
125 #define STORAGE_HID_DESC_LEN_SIZE (4)
126 #define STORAGE_HID_DESC_MAX_SIZE (2 * 512)
127 
128 /* <18 char bd addr> <space> LIST< <36 char uuid> <;> > <keytype (dec)> <pinlen>
129  */
130 #define BTIF_REMOTE_SERVICES_ENTRY_SIZE_MAX      \
131   (STORAGE_BDADDR_STRING_SZ + 1 +                \
132    STORAGE_UUID_STRING_SIZE * BT_MAX_NUM_UUIDS + \
133    STORAGE_PINLEN_STRING_MAX_SIZE + STORAGE_KEYTYPE_STRING_MAX_SIZE)
134 
135 #define STORAGE_REMOTE_LINKKEYS_ENTRY_SIZE (LINK_KEY_LEN * 2 + 1 + 2 + 1 + 2)
136 
137 /* <18 char bd addr> <space>LIST <attr_mask> <space> > <sub_class> <space>
138    <app_id> <space>
139                                 <vendor_id> <space> > <product_id> <space>
140    <version> <space>
141                                 <ctry_code> <space> > <desc_len> <space>
142    <desc_list> <space> */
143 #define BTIF_HID_INFO_ENTRY_SIZE_MAX                                  \
144   (STORAGE_BDADDR_STRING_SZ + 1 + STORAGE_HID_ATRR_MASK_SIZE + 1 +    \
145    STORAGE_HID_SUB_CLASS_SIZE + 1 + STORAGE_HID_APP_ID_SIZE + 1 +     \
146    STORAGE_HID_VENDOR_ID_SIZE + 1 + STORAGE_HID_PRODUCT_ID_SIZE + 1 + \
147    STORAGE_HID_VERSION_SIZE + 1 + STORAGE_HID_CTRY_CODE_SIZE + 1 +    \
148    STORAGE_HID_DESC_LEN_SIZE + 1 + STORAGE_HID_DESC_MAX_SIZE + 1)
149 
150 /* currently remote services is the potentially largest entry */
151 #define BTIF_STORAGE_MAX_LINE_SZ BTIF_REMOTE_SERVICES_ENTRY_SIZE_MAX
152 
153 /* check against unv max entry size at compile time */
154 #if (BTIF_STORAGE_ENTRY_MAX_SIZE > UNV_MAXLINE_LENGTH)
155 #error "btif storage entry size exceeds unv max line size"
156 #endif
157 
158 /*******************************************************************************
159  *  Local type definitions
160  ******************************************************************************/
161 typedef struct {
162   uint32_t num_devices;
163   RawAddress devices[BTM_SEC_MAX_DEVICE_RECORDS];
164 } btif_bonded_devices_t;
165 
166 /*******************************************************************************
167  *  External functions
168  ******************************************************************************/
169 
170 extern void btif_gatts_add_bonded_dev_from_nv(const RawAddress& bda);
171 
172 /*******************************************************************************
173  *  Internal Functions
174  ******************************************************************************/
175 
176 static bt_status_t btif_in_fetch_bonded_ble_device(
177     const std::string& remote_bd_addr, int add,
178     btif_bonded_devices_t* p_bonded_devices);
179 static bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr);
180 
181 static bool btif_has_ble_keys(const std::string& bdstr);
182 
183 /*******************************************************************************
184  *  Static functions
185  ******************************************************************************/
186 
prop2cfg(const RawAddress * remote_bd_addr,bt_property_t * prop)187 static int prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) {
188   std::string bdstr;
189   if (remote_bd_addr) {
190     bdstr = remote_bd_addr->ToString();
191   }
192 
193   BTIF_TRACE_DEBUG("in, bd addr:%s, prop type:%d, len:%d", bdstr.c_str(),
194                    prop->type, prop->len);
195   char value[1024];
196   if (prop->len <= 0 || prop->len > (int)sizeof(value) - 1) {
197     BTIF_TRACE_ERROR("property type:%d, len:%d is invalid", prop->type,
198                      prop->len);
199     return false;
200   }
201   switch (prop->type) {
202     case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
203       btif_config_set_int(bdstr, BTIF_STORAGE_PATH_REMOTE_DEVTIME,
204                           (int)time(NULL));
205       break;
206     case BT_PROPERTY_BDNAME: {
207       int name_length = prop->len > BTM_MAX_LOC_BD_NAME_LEN
208                             ? BTM_MAX_LOC_BD_NAME_LEN
209                             : prop->len;
210       strncpy(value, (char*)prop->val, name_length);
211       value[name_length] = '\0';
212       if (remote_bd_addr) {
213         btif_config_set_str(bdstr, BTIF_STORAGE_PATH_REMOTE_NAME, value);
214       } else {
215         btif_config_set_str("Adapter", BTIF_STORAGE_KEY_ADAPTER_NAME, value);
216         btif_config_flush();
217       }
218       break;
219     }
220     case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
221       strncpy(value, (char*)prop->val, prop->len);
222       value[prop->len] = '\0';
223       btif_config_set_str(bdstr, BTIF_STORAGE_PATH_REMOTE_ALIASE, value);
224       break;
225     case BT_PROPERTY_ADAPTER_SCAN_MODE:
226       btif_config_set_int("Adapter", BTIF_STORAGE_KEY_ADAPTER_SCANMODE,
227                           *(int*)prop->val);
228       break;
229     case BT_PROPERTY_LOCAL_IO_CAPS:
230       btif_config_set_int("Adapter", BTIF_STORAGE_KEY_LOCAL_IO_CAPS,
231                           *(int*)prop->val);
232       break;
233     case BT_PROPERTY_LOCAL_IO_CAPS_BLE:
234       btif_config_set_int("Adapter", BTIF_STORAGE_KEY_LOCAL_IO_CAPS_BLE,
235                           *(int*)prop->val);
236       break;
237     case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
238       btif_config_set_int("Adapter", BTIF_STORAGE_KEY_ADAPTER_DISC_TIMEOUT,
239                           *(int*)prop->val);
240       break;
241     case BT_PROPERTY_CLASS_OF_DEVICE:
242       btif_config_set_int(bdstr, BTIF_STORAGE_PATH_REMOTE_DEVCLASS,
243                           *(int*)prop->val);
244       break;
245     case BT_PROPERTY_TYPE_OF_DEVICE:
246       btif_config_set_int(bdstr, BTIF_STORAGE_PATH_REMOTE_DEVTYPE,
247                           *(int*)prop->val);
248       break;
249     case BT_PROPERTY_UUIDS: {
250       std::string val;
251       size_t cnt = (prop->len) / sizeof(Uuid);
252       for (size_t i = 0; i < cnt; i++) {
253         val += (reinterpret_cast<Uuid*>(prop->val) + i)->ToString() + " ";
254       }
255       btif_config_set_str(bdstr, BTIF_STORAGE_PATH_REMOTE_SERVICE, val);
256       break;
257     }
258     case BT_PROPERTY_REMOTE_VERSION_INFO: {
259       bt_remote_version_t* info = (bt_remote_version_t*)prop->val;
260 
261       if (!info) return false;
262 
263       btif_config_set_int(bdstr, BTIF_STORAGE_PATH_REMOTE_VER_MFCT,
264                           info->manufacturer);
265       btif_config_set_int(bdstr, BTIF_STORAGE_PATH_REMOTE_VER_VER,
266                           info->version);
267       btif_config_set_int(bdstr, BTIF_STORAGE_PATH_REMOTE_VER_SUBVER,
268                           info->sub_ver);
269     } break;
270 
271     default:
272       BTIF_TRACE_ERROR("Unknown prop type:%d", prop->type);
273       return false;
274   }
275 
276   /* No need to look for bonded device with address of NULL */
277   if (remote_bd_addr &&
278       btif_in_fetch_bonded_device(bdstr) == BT_STATUS_SUCCESS) {
279     /* save changes if the device was bonded */
280     btif_config_flush();
281   }
282 
283   return true;
284 }
285 
cfg2prop(const RawAddress * remote_bd_addr,bt_property_t * prop)286 static int cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) {
287   std::string bdstr;
288   if (remote_bd_addr) {
289     bdstr = remote_bd_addr->ToString();
290   }
291   BTIF_TRACE_DEBUG("in, bd addr:%s, prop type:%d, len:%d", bdstr.c_str(),
292                    prop->type, prop->len);
293   if (prop->len <= 0) {
294     BTIF_TRACE_ERROR("property type:%d, len:%d is invalid", prop->type,
295                      prop->len);
296     return false;
297   }
298   int ret = false;
299   switch (prop->type) {
300     case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
301       if (prop->len >= (int)sizeof(int))
302         ret = btif_config_get_int(bdstr, BTIF_STORAGE_PATH_REMOTE_DEVTIME,
303                                   (int*)prop->val);
304       break;
305     case BT_PROPERTY_BDNAME: {
306       int len = prop->len;
307       if (remote_bd_addr)
308         ret = btif_config_get_str(bdstr, BTIF_STORAGE_PATH_REMOTE_NAME,
309                                   (char*)prop->val, &len);
310       else
311         ret = btif_config_get_str("Adapter", BTIF_STORAGE_KEY_ADAPTER_NAME,
312                                   (char*)prop->val, &len);
313       if (ret && len && len <= prop->len)
314         prop->len = len - 1;
315       else {
316         prop->len = 0;
317         ret = false;
318       }
319       break;
320     }
321     case BT_PROPERTY_REMOTE_FRIENDLY_NAME: {
322       int len = prop->len;
323       ret = btif_config_get_str(bdstr, BTIF_STORAGE_PATH_REMOTE_ALIASE,
324                                 (char*)prop->val, &len);
325       if (ret && len && len <= prop->len)
326         prop->len = len - 1;
327       else {
328         prop->len = 0;
329         ret = false;
330       }
331       break;
332     }
333     case BT_PROPERTY_ADAPTER_SCAN_MODE:
334       if (prop->len >= (int)sizeof(int))
335         ret = btif_config_get_int("Adapter", BTIF_STORAGE_KEY_ADAPTER_SCANMODE,
336                                   (int*)prop->val);
337       break;
338 
339     case BT_PROPERTY_LOCAL_IO_CAPS:
340       if (prop->len >= (int)sizeof(int))
341         ret = btif_config_get_int("Adapter", BTIF_STORAGE_KEY_LOCAL_IO_CAPS,
342                                   (int*)prop->val);
343       break;
344     case BT_PROPERTY_LOCAL_IO_CAPS_BLE:
345       if (prop->len >= (int)sizeof(int))
346         ret = btif_config_get_int("Adapter", BTIF_STORAGE_KEY_LOCAL_IO_CAPS_BLE,
347                                   (int*)prop->val);
348       break;
349 
350     case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
351       if (prop->len >= (int)sizeof(int))
352         ret = btif_config_get_int(
353             "Adapter", BTIF_STORAGE_KEY_ADAPTER_DISC_TIMEOUT, (int*)prop->val);
354       break;
355     case BT_PROPERTY_CLASS_OF_DEVICE:
356       if (prop->len >= (int)sizeof(int))
357         ret = btif_config_get_int(bdstr, BTIF_STORAGE_PATH_REMOTE_DEVCLASS,
358                                   (int*)prop->val);
359       break;
360     case BT_PROPERTY_TYPE_OF_DEVICE:
361       if (prop->len >= (int)sizeof(int))
362         ret = btif_config_get_int(bdstr, BTIF_STORAGE_PATH_REMOTE_DEVTYPE,
363                                   (int*)prop->val);
364       break;
365     case BT_PROPERTY_UUIDS: {
366       char value[1280];
367       int size = sizeof(value);
368       if (btif_config_get_str(bdstr, BTIF_STORAGE_PATH_REMOTE_SERVICE, value,
369                               &size)) {
370         Uuid* p_uuid = reinterpret_cast<Uuid*>(prop->val);
371         size_t num_uuids =
372             btif_split_uuids_string(value, p_uuid, BT_MAX_NUM_UUIDS);
373         prop->len = num_uuids * sizeof(Uuid);
374         ret = true;
375       } else {
376         prop->val = NULL;
377         prop->len = 0;
378       }
379     } break;
380 
381     case BT_PROPERTY_REMOTE_VERSION_INFO: {
382       bt_remote_version_t* info = (bt_remote_version_t*)prop->val;
383 
384       if (prop->len >= (int)sizeof(bt_remote_version_t)) {
385         ret = btif_config_get_int(bdstr, BTIF_STORAGE_PATH_REMOTE_VER_MFCT,
386                                   &info->manufacturer);
387 
388         if (ret)
389           ret = btif_config_get_int(bdstr, BTIF_STORAGE_PATH_REMOTE_VER_VER,
390                                     &info->version);
391 
392         if (ret)
393           ret = btif_config_get_int(bdstr, BTIF_STORAGE_PATH_REMOTE_VER_SUBVER,
394                                     &info->sub_ver);
395       }
396     } break;
397 
398     default:
399       BTIF_TRACE_ERROR("Unknow prop type:%d", prop->type);
400       return false;
401   }
402   return ret;
403 }
404 
405 /*******************************************************************************
406  *
407  * Function         btif_in_fetch_bonded_devices
408  *
409  * Description      Internal helper function to fetch the bonded devices
410  *                  from NVRAM
411  *
412  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
413  *
414  ******************************************************************************/
btif_in_fetch_bonded_device(const std::string & bdstr)415 static bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr) {
416   bool bt_linkkey_file_found = false;
417 
418   LinkKey link_key;
419   size_t size = link_key.size();
420   if (btif_config_get_bin(bdstr, "LinkKey", link_key.data(), &size)) {
421     int linkkey_type;
422     if (btif_config_get_int(bdstr, "LinkKeyType", &linkkey_type)) {
423       bt_linkkey_file_found = true;
424     } else {
425       bt_linkkey_file_found = false;
426     }
427   }
428   if ((btif_in_fetch_bonded_ble_device(bdstr, false, NULL) !=
429        BT_STATUS_SUCCESS) &&
430       (!bt_linkkey_file_found)) {
431     BTIF_TRACE_DEBUG("Remote device:%s, no link key or ble key found",
432                      bdstr.c_str());
433     return BT_STATUS_FAIL;
434   }
435   return BT_STATUS_SUCCESS;
436 }
437 
438 /*******************************************************************************
439  *
440  * Function         btif_in_fetch_bonded_devices
441  *
442  * Description      Internal helper function to fetch the bonded devices
443  *                  from NVRAM
444  *
445  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
446  *
447  ******************************************************************************/
btif_in_fetch_bonded_devices(btif_bonded_devices_t * p_bonded_devices,int add)448 static bt_status_t btif_in_fetch_bonded_devices(
449     btif_bonded_devices_t* p_bonded_devices, int add) {
450   memset(p_bonded_devices, 0, sizeof(btif_bonded_devices_t));
451 
452   bool bt_linkkey_file_found = false;
453   int device_type;
454 
455   // TODO: this code is not thread safe, it can corrupt config content.
456   // b/67595284
457   for (const section_t& section : btif_config_sections()) {
458     const std::string& name = section.name;
459     if (!RawAddress::IsValidAddress(name)) continue;
460 
461     BTIF_TRACE_DEBUG("Remote device:%s", name.c_str());
462     LinkKey link_key;
463     size_t size = sizeof(link_key);
464     if (btif_config_get_bin(name, "LinkKey", link_key.data(), &size)) {
465       int linkkey_type;
466       if (btif_config_get_int(name, "LinkKeyType", &linkkey_type)) {
467         RawAddress bd_addr;
468         RawAddress::FromString(name, bd_addr);
469         if (add) {
470           DEV_CLASS dev_class = {0, 0, 0};
471           int cod;
472           int pin_length = 0;
473           if (btif_config_get_int(name, "DevClass", &cod))
474             uint2devclass((uint32_t)cod, dev_class);
475           btif_config_get_int(name, "PinLength", &pin_length);
476           BTA_DmAddDevice(bd_addr, dev_class, link_key, 0, 0,
477                           (uint8_t)linkkey_type, 0, pin_length);
478 
479           if (btif_config_get_int(name, "DevType", &device_type) &&
480               (device_type == BT_DEVICE_TYPE_DUMO)) {
481             btif_gatts_add_bonded_dev_from_nv(bd_addr);
482           }
483         }
484         bt_linkkey_file_found = true;
485         p_bonded_devices->devices[p_bonded_devices->num_devices++] = bd_addr;
486       } else {
487         bt_linkkey_file_found = false;
488       }
489     }
490     if (!btif_in_fetch_bonded_ble_device(name, add, p_bonded_devices) && !bt_linkkey_file_found) {
491       BTIF_TRACE_DEBUG("Remote device:%s, no link key or ble key found",
492                        name.c_str());
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 uint8_t 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,
499                              RawAddress bd_addr, const uint8_t addr_type,
500                              const bool add_key, bool* device_added,
501                              bool* key_found) {
502   CHECK(device_added);
503   CHECK(key_found);
504 
505   tBTA_LE_KEY_VALUE key;
506   memset(&key, 0, sizeof(key));
507 
508   if (btif_storage_get_ble_bonding_key(&bd_addr, key_type, (uint8_t*)&key,
509                                        key_len) == BT_STATUS_SUCCESS) {
510     if (add_key) {
511       if (!*device_added) {
512         BTA_DmAddBleDevice(bd_addr, addr_type, BT_DEVICE_TYPE_BLE);
513         *device_added = true;
514       }
515 
516       BTIF_TRACE_DEBUG("%s() Adding key type %d for %s", __func__, key_type,
517                        bd_addr.ToString().c_str());
518       BTA_DmAddBleKey(bd_addr, &key, key_type);
519     }
520 
521     *key_found = true;
522   }
523 }
524 
525 /*******************************************************************************
526  * Functions
527  *
528  * Functions are synchronous and can be called by both from internal modules
529  * such as BTIF_DM and by external entiries from HAL via BTIF_context_switch.
530  * For OUT parameters, the caller is expected to provide the memory.
531  * Caller is expected to provide a valid pointer to 'property->value' based on
532  * the property->type.
533  ******************************************************************************/
534 
535 /*******************************************************************************
536  *
537  * Function         btif_split_uuids_string
538  *
539  * Description      Internal helper function to split the string of UUIDs
540  *                  read from the NVRAM to an array
541  *
542  * Returns          Number of UUIDs parsed from the supplied string
543  *
544  ******************************************************************************/
btif_split_uuids_string(const char * str,bluetooth::Uuid * p_uuid,size_t max_uuids)545 size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid,
546                                size_t max_uuids) {
547   CHECK(str);
548   CHECK(p_uuid);
549 
550   size_t num_uuids = 0;
551   while (str && num_uuids < max_uuids) {
552     bool is_valid;
553     bluetooth::Uuid tmp =
554         Uuid::FromString(std::string(str, Uuid::kString128BitLen), &is_valid);
555     if (!is_valid) break;
556 
557     *p_uuid = tmp;
558     p_uuid++;
559 
560     num_uuids++;
561     str = strchr(str, ' ');
562     if (str) str++;
563   }
564 
565   return num_uuids;
566 }
567 
568 /**
569  * Helper function for fetching a local Input/Output capability property. If not
570  * set, it returns the default value.
571  */
btif_storage_get_io_cap_property(bt_property_type_t type,uint8_t default_value)572 static uint8_t btif_storage_get_io_cap_property(bt_property_type_t type,
573                                                 uint8_t default_value) {
574   char buf[sizeof(int)];
575 
576   bt_property_t property;
577   property.type = type;
578   property.val = (void*)buf;
579   property.len = sizeof(int);
580 
581   bt_status_t ret = btif_storage_get_adapter_property(&property);
582 
583   return (ret == BT_STATUS_SUCCESS) ? (uint8_t)(*(int*)property.val)
584                                     : default_value;
585 }
586 
587 /*******************************************************************************
588  *
589  * Function         btif_storage_get_io_caps
590  *
591  * Description      BTIF storage API - Fetches the local Input/Output
592  *                  capabilities of the device.
593  *
594  * Returns          Returns local IO Capability of device. If not stored,
595  *                  returns BTM_LOCAL_IO_CAPS.
596  *
597  ******************************************************************************/
btif_storage_get_local_io_caps()598 uint8_t btif_storage_get_local_io_caps() {
599   return btif_storage_get_io_cap_property(BT_PROPERTY_LOCAL_IO_CAPS,
600                                           BTM_LOCAL_IO_CAPS);
601 }
602 
603 /*******************************************************************************
604  *
605  * Function         btif_storage_get_io_caps_ble
606  *
607  * Description      BTIF storage API - Fetches the local Input/Output
608  *                  capabilities of the BLE device.
609  *
610  * Returns          Returns local IO Capability of BLE device. If not stored,
611  *                  returns BTM_LOCAL_IO_CAPS_BLE.
612  *
613  ******************************************************************************/
btif_storage_get_local_io_caps_ble()614 uint8_t btif_storage_get_local_io_caps_ble() {
615   return btif_storage_get_io_cap_property(BT_PROPERTY_LOCAL_IO_CAPS_BLE,
616                                           BTM_LOCAL_IO_CAPS_BLE);
617 }
618 
619 /*******************************************************************************
620  *
621  * Function         btif_storage_get_adapter_property
622  *
623  * Description      BTIF storage API - Fetches the adapter property->type
624  *                  from NVRAM and fills property->val.
625  *                  Caller should provide memory for property->val and
626  *                  set the property->val
627  *
628  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
629  *                  BT_STATUS_FAIL otherwise
630  *
631  ******************************************************************************/
btif_storage_get_adapter_property(bt_property_t * property)632 bt_status_t btif_storage_get_adapter_property(bt_property_t* property) {
633   /* Special handling for adapter address and BONDED_DEVICES */
634   if (property->type == BT_PROPERTY_BDADDR) {
635     RawAddress* bd_addr = (RawAddress*)property->val;
636     /* Fetch the local BD ADDR */
637     const controller_t* controller = controller_get_interface();
638     if (!controller->get_is_ready()) {
639       LOG_ERROR(LOG_TAG,
640                 "%s: Controller not ready! Unable to return Bluetooth Address",
641                 __func__);
642       *bd_addr = RawAddress::kEmpty;
643       return BT_STATUS_FAIL;
644     } else {
645       LOG_ERROR(LOG_TAG, "%s: Controller ready!", __func__);
646       *bd_addr = *controller->get_address();
647     }
648     property->len = RawAddress::kLength;
649     return BT_STATUS_SUCCESS;
650   } else if (property->type == BT_PROPERTY_ADAPTER_BONDED_DEVICES) {
651     btif_bonded_devices_t bonded_devices;
652 
653     btif_in_fetch_bonded_devices(&bonded_devices, 0);
654 
655     BTIF_TRACE_DEBUG(
656         "%s: Number of bonded devices: %d "
657         "Property:BT_PROPERTY_ADAPTER_BONDED_DEVICES",
658         __func__, bonded_devices.num_devices);
659 
660     if (bonded_devices.num_devices > 0) {
661       property->len = bonded_devices.num_devices * RawAddress::kLength;
662       memcpy(property->val, bonded_devices.devices, property->len);
663     }
664 
665     /* if there are no bonded_devices, then length shall be 0 */
666     return BT_STATUS_SUCCESS;
667   } else if (property->type == BT_PROPERTY_UUIDS) {
668     /* publish list of local supported services */
669     Uuid* p_uuid = reinterpret_cast<Uuid*>(property->val);
670     uint32_t num_uuids = 0;
671     uint32_t i;
672 
673     tBTA_SERVICE_MASK service_mask = btif_get_enabled_services_mask();
674     LOG_INFO(LOG_TAG, "%s service_mask:0x%x", __func__, service_mask);
675     for (i = 0; i < BTA_MAX_SERVICE_ID; i++) {
676       /* This should eventually become a function when more services are enabled
677        */
678       if (service_mask & (tBTA_SERVICE_MASK)(1 << i)) {
679         switch (i) {
680           case BTA_HFP_SERVICE_ID: {
681             *(p_uuid + num_uuids) =
682                 Uuid::From16Bit(UUID_SERVCLASS_AG_HANDSFREE);
683             num_uuids++;
684           }
685             FALLTHROUGH_INTENDED; /* FALLTHROUGH */
686           /* intentional fall through: Send both BFP & HSP UUIDs if HFP is
687            * enabled */
688           case BTA_HSP_SERVICE_ID: {
689             *(p_uuid + num_uuids) =
690                 Uuid::From16Bit(UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY);
691             num_uuids++;
692           } break;
693           case BTA_A2DP_SOURCE_SERVICE_ID: {
694             *(p_uuid + num_uuids) =
695                 Uuid::From16Bit(UUID_SERVCLASS_AUDIO_SOURCE);
696             num_uuids++;
697           } break;
698           case BTA_A2DP_SINK_SERVICE_ID: {
699             *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_AUDIO_SINK);
700             num_uuids++;
701           } break;
702           case BTA_HFP_HS_SERVICE_ID: {
703             *(p_uuid + num_uuids) =
704                 Uuid::From16Bit(UUID_SERVCLASS_HF_HANDSFREE);
705             num_uuids++;
706           } break;
707         }
708       }
709     }
710     property->len = (num_uuids) * sizeof(Uuid);
711     return BT_STATUS_SUCCESS;
712   }
713 
714   /* fall through for other properties */
715   if (!cfg2prop(NULL, property)) {
716     return btif_dm_get_adapter_property(property);
717   }
718   return BT_STATUS_SUCCESS;
719 }
720 
721 /*******************************************************************************
722  *
723  * Function         btif_storage_set_adapter_property
724  *
725  * Description      BTIF storage API - Stores the adapter property
726  *                  to NVRAM
727  *
728  * Returns          BT_STATUS_SUCCESS if the store was successful,
729  *                  BT_STATUS_FAIL otherwise
730  *
731  ******************************************************************************/
btif_storage_set_adapter_property(bt_property_t * property)732 bt_status_t btif_storage_set_adapter_property(bt_property_t* property) {
733   return prop2cfg(NULL, property) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
734 }
735 
736 /*******************************************************************************
737  *
738  * Function         btif_storage_get_remote_device_property
739  *
740  * Description      BTIF storage API - Fetches the remote device property->type
741  *                  from NVRAM and fills property->val.
742  *                  Caller should provide memory for property->val and
743  *                  set the property->val
744  *
745  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
746  *                  BT_STATUS_FAIL otherwise
747  *
748  ******************************************************************************/
btif_storage_get_remote_device_property(const RawAddress * remote_bd_addr,bt_property_t * property)749 bt_status_t btif_storage_get_remote_device_property(
750     const RawAddress* remote_bd_addr, bt_property_t* property) {
751   return cfg2prop(remote_bd_addr, property) ? BT_STATUS_SUCCESS
752                                             : BT_STATUS_FAIL;
753 }
754 /*******************************************************************************
755  *
756  * Function         btif_storage_set_remote_device_property
757  *
758  * Description      BTIF storage API - Stores the remote device property
759  *                  to NVRAM
760  *
761  * Returns          BT_STATUS_SUCCESS if the store was successful,
762  *                  BT_STATUS_FAIL otherwise
763  *
764  ******************************************************************************/
btif_storage_set_remote_device_property(const RawAddress * remote_bd_addr,bt_property_t * property)765 bt_status_t btif_storage_set_remote_device_property(
766     const RawAddress* remote_bd_addr, bt_property_t* property) {
767   return prop2cfg(remote_bd_addr, property) ? BT_STATUS_SUCCESS
768                                             : BT_STATUS_FAIL;
769 }
770 
771 /*******************************************************************************
772  *
773  * Function         btif_storage_add_remote_device
774  *
775  * Description      BTIF storage API - Adds a newly discovered device to NVRAM
776  *                  along with the timestamp. Also, stores the various
777  *                  properties - RSSI, BDADDR, NAME (if found in EIR)
778  *
779  * Returns          BT_STATUS_SUCCESS if the store was successful,
780  *                  BT_STATUS_FAIL otherwise
781  *
782  ******************************************************************************/
btif_storage_add_remote_device(const RawAddress * remote_bd_addr,uint32_t num_properties,bt_property_t * properties)783 bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr,
784                                            uint32_t num_properties,
785                                            bt_property_t* properties) {
786   uint32_t i = 0;
787   /* TODO: If writing a property, fails do we go back undo the earlier
788    * written properties? */
789   for (i = 0; i < num_properties; i++) {
790     /* Ignore the RSSI as this is not stored in DB */
791     if (properties[i].type == BT_PROPERTY_REMOTE_RSSI) continue;
792 
793     /* address for remote device needs special handling as we also store
794      * timestamp */
795     if (properties[i].type == BT_PROPERTY_BDADDR) {
796       bt_property_t addr_prop;
797       memcpy(&addr_prop, &properties[i], sizeof(bt_property_t));
798       addr_prop.type = (bt_property_type_t)BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP;
799       btif_storage_set_remote_device_property(remote_bd_addr, &addr_prop);
800     } else {
801       btif_storage_set_remote_device_property(remote_bd_addr, &properties[i]);
802     }
803   }
804   return BT_STATUS_SUCCESS;
805 }
806 
807 /*******************************************************************************
808  *
809  * Function         btif_storage_add_bonded_device
810  *
811  * Description      BTIF storage API - Adds the newly bonded device to NVRAM
812  *                  along with the link-key, Key type and Pin key length
813  *
814  * Returns          BT_STATUS_SUCCESS if the store was successful,
815  *                  BT_STATUS_FAIL otherwise
816  *
817  ******************************************************************************/
818 
btif_storage_add_bonded_device(RawAddress * remote_bd_addr,LinkKey link_key,uint8_t key_type,uint8_t pin_length)819 bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr,
820                                            LinkKey link_key, uint8_t key_type,
821                                            uint8_t pin_length) {
822   std::string bdstr = remote_bd_addr->ToString();
823   int ret = btif_config_set_int(bdstr, "LinkKeyType", (int)key_type);
824   ret &= btif_config_set_int(bdstr, "PinLength", (int)pin_length);
825   ret &=
826       btif_config_set_bin(bdstr, "LinkKey", link_key.data(), link_key.size());
827 
828   if (is_restricted_mode()) {
829     BTIF_TRACE_WARNING("%s: '%s' pairing will be removed if unrestricted",
830                        __func__, bdstr.c_str());
831     btif_config_set_int(bdstr, "Restricted", 1);
832   }
833 
834   /* write bonded info immediately */
835   btif_config_flush();
836   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
837 }
838 
839 /*******************************************************************************
840  *
841  * Function         btif_storage_remove_bonded_device
842  *
843  * Description      BTIF storage API - Deletes the bonded device from NVRAM
844  *
845  * Returns          BT_STATUS_SUCCESS if the deletion was successful,
846  *                  BT_STATUS_FAIL otherwise
847  *
848  ******************************************************************************/
btif_storage_remove_bonded_device(const RawAddress * remote_bd_addr)849 bt_status_t btif_storage_remove_bonded_device(
850     const RawAddress* remote_bd_addr) {
851   std::string bdstr = remote_bd_addr->ToString();
852   BTIF_TRACE_DEBUG("in bd addr:%s", bdstr.c_str());
853 
854   btif_storage_remove_ble_bonding_keys(remote_bd_addr);
855 
856   int ret = 1;
857   if (btif_config_exist(bdstr, "LinkKeyType"))
858     ret &= btif_config_remove(bdstr, "LinkKeyType");
859   if (btif_config_exist(bdstr, "PinLength"))
860     ret &= btif_config_remove(bdstr, "PinLength");
861   if (btif_config_exist(bdstr, "LinkKey"))
862     ret &= btif_config_remove(bdstr, "LinkKey");
863   if (btif_config_exist(bdstr, BTIF_STORAGE_PATH_REMOTE_ALIASE)) {
864     ret &= btif_config_remove(bdstr, BTIF_STORAGE_PATH_REMOTE_ALIASE);
865   }
866   /* write bonded info immediately */
867   btif_config_flush();
868   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
869 }
870 
871 /* Some devices hardcode sample LTK value from spec, instead of generating one.
872  * Treat such devices as insecure, and remove such bonds when bluetooth
873  * restarts. Removing them after disconnection is handled separately.
874  *
875  * We still allow such devices to bond in order to give the user a chance to
876  * update firmware.
877  */
remove_devices_with_sample_ltk()878 static void remove_devices_with_sample_ltk() {
879   std::vector<RawAddress> bad_ltk;
880   for (const section_t& section : btif_config_sections()) {
881     const std::string& name = section.name;
882     if (!RawAddress::IsValidAddress(name)) {
883       continue;
884     }
885 
886     RawAddress bd_addr;
887     RawAddress::FromString(name, bd_addr);
888 
889     tBTA_LE_KEY_VALUE key;
890     memset(&key, 0, sizeof(key));
891 
892     if (btif_storage_get_ble_bonding_key(&bd_addr, BTIF_DM_LE_KEY_PENC, (uint8_t*)&key, sizeof(tBTM_LE_PENC_KEYS)) ==
893         BT_STATUS_SUCCESS) {
894       if (is_sample_ltk(key.penc_key.ltk)) {
895         bad_ltk.push_back(bd_addr);
896       }
897     }
898   }
899 
900   for (RawAddress address : bad_ltk) {
901     android_errorWriteLog(0x534e4554, "128437297");
902     LOG(ERROR) << __func__ << ": removing bond to device using test TLK: " << address;
903 
904     btif_storage_remove_bonded_device(&address);
905   }
906 }
907 
908 /*******************************************************************************
909  *
910  * Function         btif_storage_load_bonded_devices
911  *
912  * Description      BTIF storage API - Loads all the bonded devices from NVRAM
913  *                  and adds to the BTA.
914  *                  Additionally, this API also invokes the adaper_properties_cb
915  *                  and remote_device_properties_cb for each of the bonded
916  *                  devices.
917  *
918  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
919  *
920  ******************************************************************************/
btif_storage_load_bonded_devices(void)921 bt_status_t btif_storage_load_bonded_devices(void) {
922   btif_bonded_devices_t bonded_devices;
923   uint32_t i = 0;
924   bt_property_t adapter_props[6];
925   uint32_t num_props = 0;
926   bt_property_t remote_properties[8];
927   RawAddress addr;
928   bt_bdname_t name, alias;
929   bt_scan_mode_t mode;
930   uint32_t disc_timeout;
931   Uuid local_uuids[BT_MAX_NUM_UUIDS];
932   Uuid remote_uuids[BT_MAX_NUM_UUIDS];
933   bt_status_t status;
934 
935   remove_devices_with_sample_ltk();
936 
937   btif_in_fetch_bonded_devices(&bonded_devices, 1);
938 
939   /* Now send the adapter_properties_cb with all adapter_properties */
940   {
941     memset(adapter_props, 0, sizeof(adapter_props));
942 
943     /* address */
944     BTIF_STORAGE_GET_ADAPTER_PROP(status, BT_PROPERTY_BDADDR, &addr,
945                                   sizeof(addr), adapter_props[num_props]);
946     // Add BT_PROPERTY_BDADDR property into list only when successful.
947     // Otherwise, skip this property entry.
948     if (status == BT_STATUS_SUCCESS) {
949       num_props++;
950     }
951 
952     /* BD_NAME */
953     BTIF_STORAGE_GET_ADAPTER_PROP(status, BT_PROPERTY_BDNAME, &name,
954                                   sizeof(name), adapter_props[num_props]);
955     num_props++;
956 
957     /* SCAN_MODE */
958     /* TODO: At the time of BT on, always report the scan mode as 0 irrespective
959      of the scan_mode during the previous enable cycle.
960      This needs to be re-visited as part of the app/stack enable sequence
961      synchronization */
962     mode = BT_SCAN_MODE_NONE;
963     adapter_props[num_props].type = BT_PROPERTY_ADAPTER_SCAN_MODE;
964     adapter_props[num_props].len = sizeof(mode);
965     adapter_props[num_props].val = &mode;
966     num_props++;
967 
968     /* DISC_TIMEOUT */
969     BTIF_STORAGE_GET_ADAPTER_PROP(status, BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT,
970                                   &disc_timeout, sizeof(disc_timeout),
971                                   adapter_props[num_props]);
972     num_props++;
973 
974     /* BONDED_DEVICES */
975     RawAddress* devices_list = (RawAddress*)osi_malloc(
976         sizeof(RawAddress) * bonded_devices.num_devices);
977     adapter_props[num_props].type = BT_PROPERTY_ADAPTER_BONDED_DEVICES;
978     adapter_props[num_props].len =
979         bonded_devices.num_devices * sizeof(RawAddress);
980     adapter_props[num_props].val = devices_list;
981     for (i = 0; i < bonded_devices.num_devices; i++) {
982       devices_list[i] = bonded_devices.devices[i];
983     }
984     num_props++;
985 
986     /* LOCAL UUIDs */
987     BTIF_STORAGE_GET_ADAPTER_PROP(status, BT_PROPERTY_UUIDS, local_uuids,
988                                   sizeof(local_uuids),
989                                   adapter_props[num_props]);
990     num_props++;
991 
992     btif_adapter_properties_evt(BT_STATUS_SUCCESS, num_props, adapter_props);
993 
994     osi_free(devices_list);
995   }
996 
997   BTIF_TRACE_EVENT("%s: %d bonded devices found", __func__,
998                    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,
1014                                    sizeof(name), remote_properties[num_props]);
1015       num_props++;
1016 
1017       BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr,
1018                                    BT_PROPERTY_REMOTE_FRIENDLY_NAME, &alias,
1019                                    sizeof(alias), remote_properties[num_props]);
1020       num_props++;
1021 
1022       BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_CLASS_OF_DEVICE,
1023                                    &cod, sizeof(cod),
1024                                    remote_properties[num_props]);
1025       num_props++;
1026 
1027       BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_TYPE_OF_DEVICE,
1028                                    &devtype, sizeof(devtype),
1029                                    remote_properties[num_props]);
1030       num_props++;
1031 
1032       BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_UUIDS,
1033                                    remote_uuids, sizeof(remote_uuids),
1034                                    remote_properties[num_props]);
1035       num_props++;
1036 
1037       btif_remote_properties_evt(BT_STATUS_SUCCESS, p_remote_addr, num_props,
1038                                  remote_properties);
1039     }
1040   }
1041   return BT_STATUS_SUCCESS;
1042 }
1043 
1044 /*******************************************************************************
1045  *
1046  * Function         btif_storage_add_ble_bonding_key
1047  *
1048  * Description      BTIF storage API - Adds the newly bonded device to NVRAM
1049  *                  along with the ble-key, Key type and Pin key length
1050  *
1051  * Returns          BT_STATUS_SUCCESS if the store was successful,
1052  *                  BT_STATUS_FAIL otherwise
1053  *
1054  ******************************************************************************/
1055 
btif_storage_add_ble_bonding_key(RawAddress * remote_bd_addr,const uint8_t * key,uint8_t key_type,uint8_t key_length)1056 bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr,
1057                                              const uint8_t* key,
1058                                              uint8_t key_type,
1059                                              uint8_t key_length) {
1060   const char* name;
1061   switch (key_type) {
1062     case BTIF_DM_LE_KEY_PENC:
1063       name = "LE_KEY_PENC";
1064       break;
1065     case BTIF_DM_LE_KEY_PID:
1066       name = "LE_KEY_PID";
1067       break;
1068     case BTIF_DM_LE_KEY_PCSRK:
1069       name = "LE_KEY_PCSRK";
1070       break;
1071     case BTIF_DM_LE_KEY_LENC:
1072       name = "LE_KEY_LENC";
1073       break;
1074     case BTIF_DM_LE_KEY_LCSRK:
1075       name = "LE_KEY_LCSRK";
1076       break;
1077     case BTIF_DM_LE_KEY_LID:
1078       name = "LE_KEY_LID";
1079       break;
1080     default:
1081       return BT_STATUS_FAIL;
1082   }
1083   int ret =
1084       btif_config_set_bin(remote_bd_addr->ToString(), name, key, key_length);
1085   btif_config_save();
1086   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1087 }
1088 
1089 /*******************************************************************************
1090  *
1091  * Function         btif_storage_get_ble_bonding_key
1092  *
1093  * Description
1094  *
1095  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
1096  *                  BT_STATUS_FAIL otherwise
1097  *
1098  ******************************************************************************/
btif_storage_get_ble_bonding_key(RawAddress * remote_bd_addr,uint8_t key_type,uint8_t * key_value,int key_length)1099 bt_status_t btif_storage_get_ble_bonding_key(RawAddress* remote_bd_addr,
1100                                              uint8_t key_type,
1101                                              uint8_t* key_value,
1102                                              int key_length) {
1103   const char* name;
1104   switch (key_type) {
1105     case BTIF_DM_LE_KEY_PENC:
1106       name = "LE_KEY_PENC";
1107       break;
1108     case BTIF_DM_LE_KEY_PID:
1109       name = "LE_KEY_PID";
1110       break;
1111     case BTIF_DM_LE_KEY_PCSRK:
1112       name = "LE_KEY_PCSRK";
1113       break;
1114     case BTIF_DM_LE_KEY_LENC:
1115       name = "LE_KEY_LENC";
1116       break;
1117     case BTIF_DM_LE_KEY_LCSRK:
1118       name = "LE_KEY_LCSRK";
1119       break;
1120     case BTIF_DM_LE_KEY_LID:
1121       name = "LE_KEY_LID";
1122     default:
1123       return BT_STATUS_FAIL;
1124   }
1125   size_t length = key_length;
1126   int ret =
1127       btif_config_get_bin(remote_bd_addr->ToString(), name, key_value, &length);
1128   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1129 }
1130 
1131 /*******************************************************************************
1132  *
1133  * Function         btif_storage_remove_ble_keys
1134  *
1135  * Description      BTIF storage API - Deletes the bonded device from NVRAM
1136  *
1137  * Returns          BT_STATUS_SUCCESS if the deletion was successful,
1138  *                  BT_STATUS_FAIL otherwise
1139  *
1140  ******************************************************************************/
btif_storage_remove_ble_bonding_keys(const RawAddress * remote_bd_addr)1141 bt_status_t btif_storage_remove_ble_bonding_keys(
1142     const RawAddress* remote_bd_addr) {
1143   std::string bdstr = remote_bd_addr->ToString();
1144   BTIF_TRACE_DEBUG(" %s in bd addr:%s", __func__, bdstr.c_str());
1145   int ret = 1;
1146   if (btif_config_exist(bdstr, "LE_KEY_PENC"))
1147     ret &= btif_config_remove(bdstr, "LE_KEY_PENC");
1148   if (btif_config_exist(bdstr, "LE_KEY_PID"))
1149     ret &= btif_config_remove(bdstr, "LE_KEY_PID");
1150   if (btif_config_exist(bdstr, "LE_KEY_PCSRK"))
1151     ret &= btif_config_remove(bdstr, "LE_KEY_PCSRK");
1152   if (btif_config_exist(bdstr, "LE_KEY_LENC"))
1153     ret &= btif_config_remove(bdstr, "LE_KEY_LENC");
1154   if (btif_config_exist(bdstr, "LE_KEY_LCSRK"))
1155     ret &= btif_config_remove(bdstr, "LE_KEY_LCSRK");
1156   btif_config_save();
1157   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1158 }
1159 
1160 /*******************************************************************************
1161  *
1162  * Function         btif_storage_add_ble_local_key
1163  *
1164  * Description      BTIF storage API - Adds the ble key to NVRAM
1165  *
1166  * Returns          BT_STATUS_SUCCESS if the store was successful,
1167  *                  BT_STATUS_FAIL otherwise
1168  *
1169  ******************************************************************************/
btif_storage_add_ble_local_key(const Octet16 & key,uint8_t key_type)1170 bt_status_t btif_storage_add_ble_local_key(const Octet16& key,
1171                                            uint8_t key_type) {
1172   const char* name;
1173   switch (key_type) {
1174     case BTIF_DM_LE_LOCAL_KEY_IR:
1175       name = "LE_LOCAL_KEY_IR";
1176       break;
1177     case BTIF_DM_LE_LOCAL_KEY_IRK:
1178       name = "LE_LOCAL_KEY_IRK";
1179       break;
1180     case BTIF_DM_LE_LOCAL_KEY_DHK:
1181       name = "LE_LOCAL_KEY_DHK";
1182       break;
1183     case BTIF_DM_LE_LOCAL_KEY_ER:
1184       name = "LE_LOCAL_KEY_ER";
1185       break;
1186     default:
1187       return BT_STATUS_FAIL;
1188   }
1189   int ret = btif_config_set_bin("Adapter", name, key.data(), key.size());
1190   btif_config_save();
1191   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1192 }
1193 
1194 /** Stores local key of |key_type| into |key_value|
1195  * Returns BT_STATUS_SUCCESS if the fetch was successful, BT_STATUS_FAIL
1196  * otherwise
1197  */
btif_storage_get_ble_local_key(uint8_t key_type,Octet16 * key_value)1198 bt_status_t btif_storage_get_ble_local_key(uint8_t key_type,
1199                                            Octet16* key_value) {
1200   const char* name;
1201   switch (key_type) {
1202     case BTIF_DM_LE_LOCAL_KEY_IR:
1203       name = "LE_LOCAL_KEY_IR";
1204       break;
1205     case BTIF_DM_LE_LOCAL_KEY_IRK:
1206       name = "LE_LOCAL_KEY_IRK";
1207       break;
1208     case BTIF_DM_LE_LOCAL_KEY_DHK:
1209       name = "LE_LOCAL_KEY_DHK";
1210       break;
1211     case BTIF_DM_LE_LOCAL_KEY_ER:
1212       name = "LE_LOCAL_KEY_ER";
1213       break;
1214     default:
1215       return BT_STATUS_FAIL;
1216   }
1217   size_t length = key_value->size();
1218   int ret = btif_config_get_bin("Adapter", name, key_value->data(), &length);
1219   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1220 }
1221 
1222 /*******************************************************************************
1223  *
1224  * Function         btif_storage_remove_ble_local_keys
1225  *
1226  * Description      BTIF storage API - Deletes the bonded device from NVRAM
1227  *
1228  * Returns          BT_STATUS_SUCCESS if the deletion was successful,
1229  *                  BT_STATUS_FAIL otherwise
1230  *
1231  ******************************************************************************/
btif_storage_remove_ble_local_keys(void)1232 bt_status_t btif_storage_remove_ble_local_keys(void) {
1233   int ret = 1;
1234   if (btif_config_exist("Adapter", "LE_LOCAL_KEY_IR"))
1235     ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_IR");
1236   if (btif_config_exist("Adapter", "LE_LOCAL_KEY_IRK"))
1237     ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_IRK");
1238   if (btif_config_exist("Adapter", "LE_LOCAL_KEY_DHK"))
1239     ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_DHK");
1240   if (btif_config_exist("Adapter", "LE_LOCAL_KEY_ER"))
1241     ret &= btif_config_remove("Adapter", "LE_LOCAL_KEY_ER");
1242   btif_config_save();
1243   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1244 }
1245 
btif_in_fetch_bonded_ble_device(const std::string & remote_bd_addr,int add,btif_bonded_devices_t * p_bonded_devices)1246 static bt_status_t btif_in_fetch_bonded_ble_device(
1247     const std::string& remote_bd_addr, int add,
1248     btif_bonded_devices_t* p_bonded_devices) {
1249   int device_type;
1250   int addr_type;
1251   bool device_added = false;
1252   bool key_found = false;
1253 
1254   if (!btif_config_get_int(remote_bd_addr, "DevType", &device_type))
1255     return BT_STATUS_FAIL;
1256 
1257   if ((device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE ||
1258       btif_has_ble_keys(remote_bd_addr)) {
1259     BTIF_TRACE_DEBUG("%s Found a LE device: %s", __func__,
1260                      remote_bd_addr.c_str());
1261 
1262     RawAddress bd_addr;
1263     RawAddress::FromString(remote_bd_addr, bd_addr);
1264 
1265     if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) !=
1266         BT_STATUS_SUCCESS) {
1267       addr_type = BLE_ADDR_PUBLIC;
1268       btif_storage_set_remote_addr_type(&bd_addr, BLE_ADDR_PUBLIC);
1269     }
1270 
1271     btif_read_le_key(BTIF_DM_LE_KEY_PENC, sizeof(tBTM_LE_PENC_KEYS), bd_addr,
1272                      addr_type, add, &device_added, &key_found);
1273 
1274     btif_read_le_key(BTIF_DM_LE_KEY_PID, sizeof(tBTM_LE_PID_KEYS), bd_addr,
1275                      addr_type, add, &device_added, &key_found);
1276 
1277     btif_read_le_key(BTIF_DM_LE_KEY_LID, sizeof(tBTM_LE_PID_KEYS), bd_addr,
1278                      addr_type, add, &device_added, &key_found);
1279 
1280     btif_read_le_key(BTIF_DM_LE_KEY_PCSRK, sizeof(tBTM_LE_PCSRK_KEYS), bd_addr,
1281                      addr_type, add, &device_added, &key_found);
1282 
1283     btif_read_le_key(BTIF_DM_LE_KEY_LENC, sizeof(tBTM_LE_LENC_KEYS), bd_addr,
1284                      addr_type, add, &device_added, &key_found);
1285 
1286     btif_read_le_key(BTIF_DM_LE_KEY_LCSRK, sizeof(tBTM_LE_LCSRK_KEYS), bd_addr,
1287                      addr_type, add, &device_added, &key_found);
1288 
1289     // Fill in the bonded devices
1290     if (device_added) {
1291       p_bonded_devices->devices[p_bonded_devices->num_devices++] = bd_addr;
1292       btif_gatts_add_bonded_dev_from_nv(bd_addr);
1293     }
1294 
1295     if (key_found) return BT_STATUS_SUCCESS;
1296   }
1297   return BT_STATUS_FAIL;
1298 }
1299 
btif_storage_set_remote_addr_type(const RawAddress * remote_bd_addr,uint8_t addr_type)1300 bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr,
1301                                               uint8_t addr_type) {
1302   int ret = btif_config_set_int(remote_bd_addr->ToString(), "AddrType",
1303                                 (int)addr_type);
1304   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1305 }
1306 
btif_has_ble_keys(const std::string & bdstr)1307 bool btif_has_ble_keys(const std::string& bdstr) {
1308   return btif_config_exist(bdstr, "LE_KEY_PENC");
1309 }
1310 
1311 /*******************************************************************************
1312  *
1313  * Function         btif_storage_get_remote_addr_type
1314  *
1315  * Description      BTIF storage API - Fetches the remote addr type
1316  *
1317  * Returns          BT_STATUS_SUCCESS if the fetch was successful,
1318  *                  BT_STATUS_FAIL otherwise
1319  *
1320  ******************************************************************************/
btif_storage_get_remote_addr_type(const RawAddress * remote_bd_addr,int * addr_type)1321 bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr,
1322                                               int* addr_type) {
1323   int ret =
1324       btif_config_get_int(remote_bd_addr->ToString(), "AddrType", addr_type);
1325   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
1326 }
1327 /*******************************************************************************
1328  *
1329  * Function         btif_storage_add_hid_device_info
1330  *
1331  * Description      BTIF storage API - Adds the hid information of bonded hid
1332  *                  devices-to NVRAM
1333  *
1334  * Returns          BT_STATUS_SUCCESS if the store was successful,
1335  *                  BT_STATUS_FAIL otherwise
1336  *
1337  ******************************************************************************/
1338 
btif_storage_add_hid_device_info(RawAddress * remote_bd_addr,uint16_t attr_mask,uint8_t sub_class,uint8_t app_id,uint16_t vendor_id,uint16_t product_id,uint16_t version,uint8_t ctry_code,uint16_t ssr_max_latency,uint16_t ssr_min_tout,uint16_t dl_len,uint8_t * dsc_list)1339 bt_status_t btif_storage_add_hid_device_info(
1340     RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class,
1341     uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version,
1342     uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout,
1343     uint16_t dl_len, uint8_t* dsc_list) {
1344   BTIF_TRACE_DEBUG("btif_storage_add_hid_device_info:");
1345   std::string bdstr = remote_bd_addr->ToString();
1346   btif_config_set_int(bdstr, "HidAttrMask", attr_mask);
1347   btif_config_set_int(bdstr, "HidSubClass", sub_class);
1348   btif_config_set_int(bdstr, "HidAppId", app_id);
1349   btif_config_set_int(bdstr, "HidVendorId", vendor_id);
1350   btif_config_set_int(bdstr, "HidProductId", product_id);
1351   btif_config_set_int(bdstr, "HidVersion", version);
1352   btif_config_set_int(bdstr, "HidCountryCode", ctry_code);
1353   btif_config_set_int(bdstr, "HidSSRMaxLatency", ssr_max_latency);
1354   btif_config_set_int(bdstr, "HidSSRMinTimeout", ssr_min_tout);
1355   if (dl_len > 0) btif_config_set_bin(bdstr, "HidDescriptor", dsc_list, dl_len);
1356   btif_config_save();
1357   return BT_STATUS_SUCCESS;
1358 }
1359 
1360 /*******************************************************************************
1361  *
1362  * Function         btif_storage_load_bonded_hid_info
1363  *
1364  * Description      BTIF storage API - Loads hid info for all the bonded devices
1365  *                  from NVRAM and adds those devices  to the BTA_HH.
1366  *
1367  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
1368  *
1369  ******************************************************************************/
btif_storage_load_bonded_hid_info(void)1370 bt_status_t btif_storage_load_bonded_hid_info(void) {
1371   // TODO: this code is not thread safe, it can corrupt config content.
1372   // b/67595284
1373   for (const section_t& section : btif_config_sections()) {
1374     const std::string& name = section.name;
1375     if (!RawAddress::IsValidAddress(name)) continue;
1376 
1377     BTIF_TRACE_DEBUG("Remote device:%s", name.c_str());
1378 
1379     int value;
1380     if (!btif_config_get_int(name, "HidAttrMask", &value)) continue;
1381     uint16_t attr_mask = (uint16_t)value;
1382 
1383     if (btif_in_fetch_bonded_device(name) != BT_STATUS_SUCCESS) {
1384       RawAddress bd_addr;
1385       RawAddress::FromString(name, bd_addr);
1386       btif_storage_remove_hid_info(&bd_addr);
1387       continue;
1388     }
1389 
1390     tBTA_HH_DEV_DSCP_INFO dscp_info;
1391     memset(&dscp_info, 0, sizeof(dscp_info));
1392 
1393     btif_config_get_int(name, "HidSubClass", &value);
1394     uint8_t sub_class = (uint8_t)value;
1395 
1396     btif_config_get_int(name, "HidAppId", &value);
1397     uint8_t app_id = (uint8_t)value;
1398 
1399     btif_config_get_int(name, "HidVendorId", &value);
1400     dscp_info.vendor_id = (uint16_t)value;
1401 
1402     btif_config_get_int(name, "HidProductId", &value);
1403     dscp_info.product_id = (uint16_t)value;
1404 
1405     btif_config_get_int(name, "HidVersion", &value);
1406     dscp_info.version = (uint8_t)value;
1407 
1408     btif_config_get_int(name, "HidCountryCode", &value);
1409     dscp_info.ctry_code = (uint8_t)value;
1410 
1411     value = 0;
1412     btif_config_get_int(name, "HidSSRMaxLatency", &value);
1413     dscp_info.ssr_max_latency = (uint16_t)value;
1414 
1415     value = 0;
1416     btif_config_get_int(name, "HidSSRMinTimeout", &value);
1417     dscp_info.ssr_min_tout = (uint16_t)value;
1418 
1419     size_t len = btif_config_get_bin_length(name, "HidDescriptor");
1420     if (len > 0) {
1421       dscp_info.descriptor.dl_len = (uint16_t)len;
1422       dscp_info.descriptor.dsc_list = (uint8_t*)alloca(len);
1423       btif_config_get_bin(name, "HidDescriptor",
1424                           (uint8_t*)dscp_info.descriptor.dsc_list, &len);
1425     }
1426 
1427     RawAddress bd_addr;
1428     RawAddress::FromString(name, bd_addr);
1429     // add extracted information to BTA HH
1430     if (btif_hh_add_added_dev(bd_addr, attr_mask)) {
1431       BTA_HhAddDev(bd_addr, attr_mask, sub_class, app_id, dscp_info);
1432     }
1433   }
1434 
1435   return BT_STATUS_SUCCESS;
1436 }
1437 
1438 /*******************************************************************************
1439  *
1440  * Function         btif_storage_remove_hid_info
1441  *
1442  * Description      BTIF storage API - Deletes the bonded hid device info from
1443  *                  NVRAM
1444  *
1445  * Returns          BT_STATUS_SUCCESS if the deletion was successful,
1446  *                  BT_STATUS_FAIL otherwise
1447  *
1448  ******************************************************************************/
btif_storage_remove_hid_info(RawAddress * remote_bd_addr)1449 bt_status_t btif_storage_remove_hid_info(RawAddress* remote_bd_addr) {
1450   std::string bdstr = remote_bd_addr->ToString();
1451 
1452   btif_config_remove(bdstr, "HidAttrMask");
1453   btif_config_remove(bdstr, "HidSubClass");
1454   btif_config_remove(bdstr, "HidAppId");
1455   btif_config_remove(bdstr, "HidVendorId");
1456   btif_config_remove(bdstr, "HidProductId");
1457   btif_config_remove(bdstr, "HidVersion");
1458   btif_config_remove(bdstr, "HidCountryCode");
1459   btif_config_remove(bdstr, "HidSSRMaxLatency");
1460   btif_config_remove(bdstr, "HidSSRMinTimeout");
1461   btif_config_remove(bdstr, "HidDescriptor");
1462   btif_config_save();
1463   return BT_STATUS_SUCCESS;
1464 }
1465 
1466 constexpr char HEARING_AID_READ_PSM_HANDLE[] = "HearingAidReadPsmHandle";
1467 constexpr char HEARING_AID_CAPABILITIES[] = "HearingAidCapabilities";
1468 constexpr char HEARING_AID_CODECS[] = "HearingAidCodecs";
1469 constexpr char HEARING_AID_AUDIO_CONTROL_POINT[] =
1470     "HearingAidAudioControlPoint";
1471 constexpr char HEARING_AID_VOLUME_HANDLE[] = "HearingAidVolumeHandle";
1472 constexpr char HEARING_AID_AUDIO_STATUS_HANDLE[] =
1473     "HearingAidAudioStatusHandle";
1474 constexpr char HEARING_AID_AUDIO_STATUS_CCC_HANDLE[] =
1475     "HearingAidAudioStatusCccHandle";
1476 constexpr char HEARING_AID_SERVICE_CHANGED_CCC_HANDLE[] =
1477     "HearingAidServiceChangedCccHandle";
1478 constexpr char HEARING_AID_SYNC_ID[] = "HearingAidSyncId";
1479 constexpr char HEARING_AID_RENDER_DELAY[] = "HearingAidRenderDelay";
1480 constexpr char HEARING_AID_PREPARATION_DELAY[] = "HearingAidPreparationDelay";
1481 constexpr char HEARING_AID_IS_WHITE_LISTED[] = "HearingAidIsWhiteListed";
1482 
btif_storage_add_hearing_aid(const HearingDevice & dev_info)1483 void btif_storage_add_hearing_aid(const HearingDevice& dev_info) {
1484   do_in_jni_thread(
1485       FROM_HERE,
1486       Bind(
1487           [](const HearingDevice& dev_info) {
1488             std::string bdstr = dev_info.address.ToString();
1489             VLOG(2) << "saving hearing aid device: " << bdstr;
1490             btif_config_set_int(bdstr, HEARING_AID_SERVICE_CHANGED_CCC_HANDLE,
1491                                 dev_info.service_changed_ccc_handle);
1492             btif_config_set_int(bdstr, HEARING_AID_READ_PSM_HANDLE,
1493                                 dev_info.read_psm_handle);
1494             btif_config_set_int(bdstr, HEARING_AID_CAPABILITIES,
1495                                 dev_info.capabilities);
1496             btif_config_set_int(bdstr, HEARING_AID_CODECS, dev_info.codecs);
1497             btif_config_set_int(bdstr, HEARING_AID_AUDIO_CONTROL_POINT,
1498                                 dev_info.audio_control_point_handle);
1499             btif_config_set_int(bdstr, HEARING_AID_VOLUME_HANDLE,
1500                                 dev_info.volume_handle);
1501             btif_config_set_int(bdstr, HEARING_AID_AUDIO_STATUS_HANDLE,
1502                                 dev_info.audio_status_handle);
1503             btif_config_set_int(bdstr, HEARING_AID_AUDIO_STATUS_CCC_HANDLE,
1504                                 dev_info.audio_status_ccc_handle);
1505             btif_config_set_uint64(bdstr, HEARING_AID_SYNC_ID,
1506                                    dev_info.hi_sync_id);
1507             btif_config_set_int(bdstr, HEARING_AID_RENDER_DELAY,
1508                                 dev_info.render_delay);
1509             btif_config_set_int(bdstr, HEARING_AID_PREPARATION_DELAY,
1510                                 dev_info.preparation_delay);
1511             btif_config_set_int(bdstr, HEARING_AID_IS_WHITE_LISTED, true);
1512             btif_config_save();
1513           },
1514           dev_info));
1515 }
1516 
1517 /** Loads information about bonded hearing aid devices */
btif_storage_load_bonded_hearing_aids()1518 void btif_storage_load_bonded_hearing_aids() {
1519   // TODO: this code is not thread safe, it can corrupt config content.
1520   // b/67595284
1521   for (const section_t& section : btif_config_sections()) {
1522     const std::string& name = section.name;
1523     if (!RawAddress::IsValidAddress(name)) continue;
1524 
1525     int size = STORAGE_UUID_STRING_SIZE * HEARINGAID_MAX_NUM_UUIDS;
1526     char uuid_str[size];
1527     bool isHearingaidDevice = false;
1528     if (btif_config_get_str(name, BTIF_STORAGE_PATH_REMOTE_SERVICE, uuid_str,
1529                             &size)) {
1530       Uuid p_uuid[HEARINGAID_MAX_NUM_UUIDS];
1531       size_t num_uuids =
1532           btif_split_uuids_string(uuid_str, p_uuid, HEARINGAID_MAX_NUM_UUIDS);
1533       for (size_t i = 0; i < num_uuids; i++) {
1534         if (p_uuid[i] == Uuid::FromString("FDF0")) {
1535           isHearingaidDevice = true;
1536           break;
1537         }
1538       }
1539     }
1540     if (!isHearingaidDevice) {
1541       continue;
1542     }
1543 
1544     BTIF_TRACE_DEBUG("Remote device:%s", name.c_str());
1545 
1546     if (btif_in_fetch_bonded_device(name) != BT_STATUS_SUCCESS) {
1547       RawAddress bd_addr;
1548       RawAddress::FromString(name, bd_addr);
1549       btif_storage_remove_hearing_aid(bd_addr);
1550       continue;
1551     }
1552 
1553     int value;
1554     uint8_t capabilities = 0;
1555     if (btif_config_get_int(name, HEARING_AID_CAPABILITIES, &value))
1556       capabilities = value;
1557 
1558     uint16_t codecs = 0;
1559     if (btif_config_get_int(name, HEARING_AID_CODECS, &value)) codecs = value;
1560 
1561     uint16_t audio_control_point_handle = 0;
1562     if (btif_config_get_int(name, HEARING_AID_AUDIO_CONTROL_POINT, &value))
1563       audio_control_point_handle = value;
1564 
1565     uint16_t audio_status_handle = 0;
1566     if (btif_config_get_int(name, HEARING_AID_AUDIO_STATUS_HANDLE, &value))
1567       audio_status_handle = value;
1568 
1569     uint16_t audio_status_ccc_handle = 0;
1570     if (btif_config_get_int(name, HEARING_AID_AUDIO_STATUS_CCC_HANDLE, &value))
1571       audio_status_ccc_handle = value;
1572 
1573     uint16_t service_changed_ccc_handle = 0;
1574     if (btif_config_get_int(name, HEARING_AID_SERVICE_CHANGED_CCC_HANDLE,
1575                             &value))
1576       service_changed_ccc_handle = value;
1577 
1578     uint16_t volume_handle = 0;
1579     if (btif_config_get_int(name, HEARING_AID_VOLUME_HANDLE, &value))
1580       volume_handle = value;
1581 
1582     uint16_t read_psm_handle = 0;
1583     if (btif_config_get_int(name, HEARING_AID_READ_PSM_HANDLE, &value))
1584       read_psm_handle = value;
1585 
1586     uint64_t lvalue;
1587     uint64_t hi_sync_id = 0;
1588     if (btif_config_get_uint64(name, HEARING_AID_SYNC_ID, &lvalue))
1589       hi_sync_id = lvalue;
1590 
1591     uint16_t render_delay = 0;
1592     if (btif_config_get_int(name, HEARING_AID_RENDER_DELAY, &value))
1593       render_delay = value;
1594 
1595     uint16_t preparation_delay = 0;
1596     if (btif_config_get_int(name, HEARING_AID_PREPARATION_DELAY, &value))
1597       preparation_delay = value;
1598 
1599     uint16_t is_white_listed = 0;
1600     if (btif_config_get_int(name, HEARING_AID_IS_WHITE_LISTED, &value))
1601       is_white_listed = value;
1602 
1603     RawAddress bd_addr;
1604     RawAddress::FromString(name, bd_addr);
1605 
1606     // add extracted information to BTA Hearing Aid
1607     do_in_main_thread(
1608         FROM_HERE,
1609         Bind(&HearingAid::AddFromStorage,
1610              HearingDevice(bd_addr, capabilities, codecs,
1611                            audio_control_point_handle, audio_status_handle,
1612                            audio_status_ccc_handle, service_changed_ccc_handle,
1613                            volume_handle, read_psm_handle, hi_sync_id,
1614                            render_delay, preparation_delay),
1615              is_white_listed));
1616   }
1617 }
1618 
1619 /** Deletes the bonded hearing aid device info from NVRAM */
btif_storage_remove_hearing_aid(const RawAddress & address)1620 void btif_storage_remove_hearing_aid(const RawAddress& address) {
1621   std::string addrstr = address.ToString();
1622   btif_config_remove(addrstr, HEARING_AID_READ_PSM_HANDLE);
1623   btif_config_remove(addrstr, HEARING_AID_CAPABILITIES);
1624   btif_config_remove(addrstr, HEARING_AID_CODECS);
1625   btif_config_remove(addrstr, HEARING_AID_AUDIO_CONTROL_POINT);
1626   btif_config_remove(addrstr, HEARING_AID_VOLUME_HANDLE);
1627   btif_config_remove(addrstr, HEARING_AID_AUDIO_STATUS_HANDLE);
1628   btif_config_remove(addrstr, HEARING_AID_AUDIO_STATUS_CCC_HANDLE);
1629   btif_config_remove(addrstr, HEARING_AID_SERVICE_CHANGED_CCC_HANDLE);
1630   btif_config_remove(addrstr, HEARING_AID_SYNC_ID);
1631   btif_config_remove(addrstr, HEARING_AID_RENDER_DELAY);
1632   btif_config_remove(addrstr, HEARING_AID_PREPARATION_DELAY);
1633   btif_config_remove(addrstr, HEARING_AID_IS_WHITE_LISTED);
1634   btif_config_save();
1635 }
1636 
1637 /** Set/Unset the hearing aid device HEARING_AID_IS_WHITE_LISTED flag. */
btif_storage_set_hearing_aid_white_list(const RawAddress & address,bool add_to_whitelist)1638 void btif_storage_set_hearing_aid_white_list(const RawAddress& address,
1639                                              bool add_to_whitelist) {
1640   std::string addrstr = address.ToString();
1641 
1642   btif_config_set_int(addrstr, HEARING_AID_IS_WHITE_LISTED, add_to_whitelist);
1643   btif_config_save();
1644 }
1645 
1646 /** Get the hearing aid device properties. */
btif_storage_get_hearing_aid_prop(const RawAddress & address,uint8_t * capabilities,uint64_t * hi_sync_id,uint16_t * render_delay,uint16_t * preparation_delay,uint16_t * codecs)1647 bool btif_storage_get_hearing_aid_prop(
1648     const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id,
1649     uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) {
1650   std::string addrstr = address.ToString();
1651 
1652   int value;
1653   if (btif_config_get_int(addrstr, HEARING_AID_CAPABILITIES, &value)) {
1654     *capabilities = value;
1655   } else {
1656     return false;
1657   }
1658 
1659   if (btif_config_get_int(addrstr, HEARING_AID_CODECS, &value)) {
1660     *codecs = value;
1661   } else {
1662     return false;
1663   }
1664 
1665   if (btif_config_get_int(addrstr, HEARING_AID_RENDER_DELAY, &value)) {
1666     *render_delay = value;
1667   } else {
1668     return false;
1669   }
1670 
1671   if (btif_config_get_int(addrstr, HEARING_AID_PREPARATION_DELAY, &value)) {
1672     *preparation_delay = value;
1673   } else {
1674     return false;
1675   }
1676 
1677   uint64_t lvalue;
1678   if (btif_config_get_uint64(addrstr, HEARING_AID_SYNC_ID, &lvalue)) {
1679     *hi_sync_id = lvalue;
1680   } else {
1681     return false;
1682   }
1683 
1684   return true;
1685 }
1686 
1687 /*******************************************************************************
1688  *
1689  * Function         btif_storage_is_restricted_device
1690  *
1691  * Description      BTIF storage API - checks if this device is a restricted
1692  *                  device
1693  *
1694  * Returns          true  if the device is labeled as restricted
1695  *                  false otherwise
1696  *
1697  ******************************************************************************/
btif_storage_is_restricted_device(const RawAddress * remote_bd_addr)1698 bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) {
1699   return btif_config_exist(remote_bd_addr->ToString(), "Restricted");
1700 }
1701 
btif_storage_get_num_bonded_devices(void)1702 int btif_storage_get_num_bonded_devices(void) {
1703   btif_bonded_devices_t bonded_devices;
1704   btif_in_fetch_bonded_devices(&bonded_devices, 0);
1705   return bonded_devices.num_devices;
1706 }
1707 
1708 /*******************************************************************************
1709  * Function         btif_storage_load_hidd
1710  *
1711  * Description      Loads hidd bonded device and "plugs" it into hidd
1712  *
1713  * Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
1714  *
1715  ******************************************************************************/
btif_storage_load_hidd(void)1716 bt_status_t btif_storage_load_hidd(void) {
1717   // TODO: this code is not thread safe, it can corrupt config content.
1718   // b/67595284
1719   for (const section_t& section : btif_config_sections()) {
1720     const std::string& name = section.name;
1721     if (!RawAddress::IsValidAddress(name)) continue;
1722 
1723     BTIF_TRACE_DEBUG("Remote device:%s", name.c_str());
1724     int value;
1725     if (btif_in_fetch_bonded_device(name) == BT_STATUS_SUCCESS) {
1726       if (btif_config_get_int(name, "HidDeviceCabled", &value)) {
1727         RawAddress bd_addr;
1728         RawAddress::FromString(name, bd_addr);
1729         BTA_HdAddDevice(bd_addr);
1730         break;
1731       }
1732     }
1733   }
1734 
1735   return BT_STATUS_SUCCESS;
1736 }
1737 
1738 /*******************************************************************************
1739  *
1740  * Function         btif_storage_set_hidd
1741  *
1742  * Description      Stores currently used HIDD device info in nvram and remove
1743  *                  the "HidDeviceCabled" flag from unused devices
1744  *
1745  * Returns          BT_STATUS_SUCCESS
1746  *
1747  ******************************************************************************/
btif_storage_set_hidd(RawAddress * remote_bd_addr)1748 bt_status_t btif_storage_set_hidd(RawAddress* remote_bd_addr) {
1749   std::string remote_device_address_string = remote_bd_addr->ToString();
1750   for (const section_t& section : btif_config_sections()) {
1751     if (!RawAddress::IsValidAddress(section.name)) continue;
1752     if (section.name == remote_device_address_string) continue;
1753     if (btif_in_fetch_bonded_device(section.name) == BT_STATUS_SUCCESS) {
1754       btif_config_remove(section.name, "HidDeviceCabled");
1755     }
1756   }
1757 
1758   btif_config_set_int(remote_device_address_string, "HidDeviceCabled", 1);
1759   btif_config_save();
1760   return BT_STATUS_SUCCESS;
1761 }
1762 
1763 /*******************************************************************************
1764  *
1765  * Function         btif_storage_remove_hidd
1766  *
1767  * Description      Removes hidd bonded device info from nvram
1768  *
1769  * Returns          BT_STATUS_SUCCESS
1770  *
1771  ******************************************************************************/
btif_storage_remove_hidd(RawAddress * remote_bd_addr)1772 bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) {
1773   btif_config_remove(remote_bd_addr->ToString(), "HidDeviceCabled");
1774   btif_config_save();
1775 
1776   return BT_STATUS_SUCCESS;
1777 }
1778 
1779 // Get the name of a device from btif for interop database matching.
btif_storage_get_stored_remote_name(const RawAddress & bd_addr,char * name)1780 bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr,
1781                                          char* name) {
1782   bt_property_t property;
1783   property.type = BT_PROPERTY_BDNAME;
1784   property.len = BTM_MAX_REM_BD_NAME_LEN;
1785   property.val = name;
1786 
1787   return (btif_storage_get_remote_device_property(&bd_addr, &property) ==
1788           BT_STATUS_SUCCESS);
1789 }
1790