summaryrefslogtreecommitdiffstats
path: root/btif/src/btif_storage.c
blob: 4d80914b1e00799d40c4511b0e9f9cbe169b78fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
/************************************************************************************
 *
 *  Copyright (C) 2009-2012 Broadcom Corporation
 *
 *  This program is the proprietary software of Broadcom Corporation and/or its
 *  licensors, and may only be used, duplicated, modified or distributed
 *  pursuant to the terms and conditions of a separate, written license
 *  agreement executed between you and Broadcom (an "Authorized License").
 *  Except as set forth in an Authorized License, Broadcom grants no license
 *  (express or implied), right to use, or waiver of any kind with respect to
 *  the Software, and Broadcom expressly reserves all rights in and to the
 *  Software and all intellectual property rights therein.
 *  IF YOU HAVE NO AUTHORIZED LICENSE, THEN YOU HAVE NO RIGHT TO USE THIS
 *  SOFTWARE IN ANY WAY, AND SHOULD IMMEDIATELY NOTIFY BROADCOM AND DISCONTINUE
 *  ALL USE OF THE SOFTWARE.
 *
 *  Except as expressly set forth in the Authorized License,
 *
 *  1.     This program, including its structure, sequence and organization,
 *         constitutes the valuable trade secrets of Broadcom, and you shall
 *         use all reasonable efforts to protect the confidentiality thereof,
 *         and to use this information only in connection with your use of
 *         Broadcom integrated circuit products.
 *
 *  2.     TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SOFTWARE IS PROVIDED
 *         "AS IS" AND WITH ALL FAULTS AND BROADCOM MAKES NO PROMISES,
 *         REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS, IMPLIED, STATUTORY,
 *         OR OTHERWISE, WITH RESPECT TO THE SOFTWARE.  BROADCOM SPECIFICALLY
 *         DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY,
 *         NONINFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, LACK OF VIRUSES,
 *         ACCURACY OR COMPLETENESS, QUIET ENJOYMENT, QUIET POSSESSION OR
 *         CORRESPONDENCE TO DESCRIPTION. YOU ASSUME THE ENTIRE RISK ARISING OUT
 *         OF USE OR PERFORMANCE OF THE SOFTWARE.
 *
 *  3.     TO THE MAXIMUM EXTENT PERMITTED BY LAW, IN NO EVENT SHALL BROADCOM OR
 *         ITS LICENSORS BE LIABLE FOR
 *         (i)   CONSEQUENTIAL, INCIDENTAL, SPECIAL, INDIRECT, OR EXEMPLARY
 *               DAMAGES WHATSOEVER ARISING OUT OF OR IN ANY WAY RELATING TO
 *               YOUR USE OF OR INABILITY TO USE THE SOFTWARE EVEN IF BROADCOM
 *               HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES; OR
 *         (ii)  ANY AMOUNT IN EXCESS OF THE AMOUNT ACTUALLY PAID FOR THE
 *               SOFTWARE ITSELF OR U.S. $1, WHICHEVER IS GREATER. THESE
 *               LIMITATIONS SHALL APPLY NOTWITHSTANDING ANY FAILURE OF
 *               ESSENTIAL PURPOSE OF ANY LIMITED REMEDY.
 *
 ************************************************************************************/

/************************************************************************************
 *
 *  Filename:      btif_storage.c
 *
 *  Description:   Stores the local BT adapter and remote device properties in
 *                 NVRAM storage, typically as text files in the
 *                 mobile's filesystem
 *
 *
 *  Data storage directory structure
 *
 * data
 * `-- misc
 *   `-- bluedroid
 *       `-- LOCAL
 *           |-- adapter_info            - Local adapter config
 *           |-- remote_devices          - Remote devices and Timestamp
 *           |-- remote_devclass         - Remote devices' COD
 *           |-- remote_devtype          - Remote devices' type
 *           |-- remote_names            - Remote devices' names
 *           |-- remote_aliases          - Remote devices' Friendly names
 *           `-- remote_services         - Remote devices' services
 *
 *
 * adapter_info - Key/Value
 *     name <space> <Name of Local Bluetooth device>
 *     scan_mode <space> <Scan Mode>
 *     discovery_timeout <space> <Discovery Timeout in seconds>
 *
 * remote_devices - Key/Value
 *     <remote device bd_addr> <space> <Timestamp>
 *
 * remote_devclass - Key/Value
 *    <remote device bd_addr> <space> <Device class>
 *
 * remote_devtype - Key/Value
 *    <remote_device bd_addr><space> <Device Type>
 *
 * remote_names - Key/Value
 *    <remote_device bd_addr> <space> <Bluetooth device Name as reported by the controller>
 *
 * remote_linkkeys - Key/Value
 *     <remote device bd_addr > <space> <LinkKey> <space> <KeyType> <space> <PinLength>
 *
 * remote_aliases - Key/Value
 *     <remote device bd_addr> <space> <Friendy Name>
 *
 * remote_services - Key/Value
 *     <remote_device bd_addr> <space> <List of UUIDs separated by semicolons>
 *
 ***********************************************************************************/
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>


#include <hardware/bluetooth.h>

#define LOG_TAG "BTIF_STORAGE"

#include "btif_api.h"

#include "btif_util.h"
#include "unv.h"
#include "bd.h"
#include "gki.h"
#include "bta_hh_api.h"
#include "btif_hh.h"


/************************************************************************************
**  Constants & Macros
************************************************************************************/

#define BTIF_STORAGE_PATH_BLUEDROID "/data/misc/bluedroid"

#define BTIF_STORAGE_PATH_ADAPTER_INFO "adapter_info"
#define BTIF_STORAGE_PATH_REMOTE_DEVICES "remote_devices"
#define BTIF_STORAGE_PATH_REMOTE_DEVCLASSES "remote_devclasses"
#define BTIF_STORAGE_PATH_REMOTE_DEVTYPES "remote_devtypes"
#define BTIF_STORAGE_PATH_REMOTE_NAMES "remote_names"
#define BTIF_STORAGE_PATH_REMOTE_LINKKEYS "remote_linkkeys"
#define BTIF_STORAGE_PATH_REMOTE_ALIASES "remote_aliases"
#define BTIF_STORAGE_PATH_REMOTE_SERVICES "remote_services"
#define BTIF_STORAGE_PATH_REMOTE_HIDINFO "hid_info"
#define BTIF_STORAGE_PATH_DYNAMIC_AUTOPAIR_BLACKLIST ""
#define BTIF_STORAGE_KEY_ADAPTER_NAME "name"
#define BTIF_STORAGE_KEY_ADAPTER_SCANMODE "scan_mode"
#define BTIF_STORAGE_KEY_ADAPTER_DISC_TIMEOUT "discovery_timeout"


#define BTIF_AUTO_PAIR_CONF_FILE  "/etc/bluetooth/auto_pair_devlist.conf"
#define BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST "auto_pair_blacklist"
#define BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_ADDR "AddressBlacklist"
#define BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_EXACTNAME "ExactNameBlacklist"
#define BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_PARTIALNAME "PartialNameBlacklist"
#define BTIF_STORAGE_KEY_AUTOPAIR_FIXPIN_KBLIST "FixedPinZerosKeyboardBlacklist"
#define BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR "DynamicAddressBlacklist"

#define BTIF_AUTO_PAIR_CONF_VALUE_SEPARATOR ","
#define BTIF_AUTO_PAIR_CONF_SPACE ' '
#define BTIF_AUTO_PAIR_CONF_COMMENT '#'
#define BTIF_AUTO_PAIR_CONF_KEY_VAL_DELIMETER "="


/* This is a local property to add a device found */
#define BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP 0xFF

#define BTIF_STORAGE_GET_ADAPTER_PROP(t,v,l,p) \
      {p.type=t;p.val=v;p.len=l; btif_storage_get_adapter_property(&p);}

#define BTIF_STORAGE_GET_REMOTE_PROP(b,t,v,l,p) \
      {p.type=t;p.val=v;p.len=l;btif_storage_get_remote_device_property(b,&p);}

#define STORAGE_BDADDR_STRING_SZ           (18)      /* 00:11:22:33:44:55 */
#define STORAGE_UUID_STRING_SIZE           (36+1)    /* 00001200-0000-1000-8000-00805f9b34fb; */
#define STORAGE_PINLEN_STRING_MAX_SIZE     (2)       /* ascii pinlen max chars */
#define STORAGE_KEYTYPE_STRING_MAX_SIZE    (1)       /* ascii keytype max chars */

#define STORAGE_KEY_TYPE_MAX               (10)

#define STORAGE_HID_ATRR_MASK_SIZE           (4)
#define STORAGE_HID_SUB_CLASS_SIZE           (2)
#define STORAGE_HID_APP_ID_SIZE              (2)
#define STORAGE_HID_VENDOR_ID_SIZE           (4)
#define STORAGE_HID_PRODUCT_ID_SIZE          (4)
#define STORAGE_HID_VERSION_SIZE             (4)
#define STORAGE_HID_CTRY_CODE_SIZE           (2)
#define STORAGE_HID_DESC_LEN_SIZE            (4)
#define STORAGE_HID_DESC_MAX_SIZE            (2*512)

/* <18 char bd addr> <space> LIST< <36 char uuid> <;> > <keytype (dec)> <pinlen> */
#define BTIF_REMOTE_SERVICES_ENTRY_SIZE_MAX (STORAGE_BDADDR_STRING_SZ + 1 +\
                                             STORAGE_UUID_STRING_SIZE*BT_MAX_NUM_UUIDS + \
                                             STORAGE_PINLEN_STRING_MAX_SIZE +\
                                             STORAGE_KEYTYPE_STRING_MAX_SIZE)

#define STORAGE_REMOTE_LINKKEYS_ENTRY_SIZE (LINK_KEY_LEN*2 + 1 + 2 + 1 + 2)

/* <18 char bd addr> <space>LIST <attr_mask> <space> > <sub_class> <space> <app_id> <space>
                                <vendor_id> <space> > <product_id> <space> <version> <space>
                                <ctry_code> <space> > <desc_len> <space> <desc_list> <space> */
#define BTIF_HID_INFO_ENTRY_SIZE_MAX    (STORAGE_BDADDR_STRING_SZ + 1 +\
                                         STORAGE_HID_ATRR_MASK_SIZE + 1 +\
                                         STORAGE_HID_SUB_CLASS_SIZE + 1 +\
                                         STORAGE_HID_APP_ID_SIZE+ 1 +\
                                         STORAGE_HID_VENDOR_ID_SIZE+ 1 +\
                                         STORAGE_HID_PRODUCT_ID_SIZE+ 1 +\
                                         STORAGE_HID_VERSION_SIZE+ 1 +\
                                         STORAGE_HID_CTRY_CODE_SIZE+ 1 +\
                                         STORAGE_HID_DESC_LEN_SIZE+ 1 +\
                                         STORAGE_HID_DESC_MAX_SIZE+ 1 )


/* currently remote services is the potentially largest entry */
#define BTIF_STORAGE_MAX_LINE_SZ BTIF_REMOTE_SERVICES_ENTRY_SIZE_MAX


/* check against unv max entry size at compile time */
#if (BTIF_STORAGE_ENTRY_MAX_SIZE > UNV_MAXLINE_LENGTH)
    #error "btif storage entry size exceeds unv max line size"
#endif



#define BTIF_STORAGE_HL_APP_CB "hl_app_cb"
#define BTIF_STORAGE_HL_APP_DATA "hl_app_data_"
#define BTIF_STORAGE_HL_APP_MDL_DATA "hl_app_mdl_data_"
/************************************************************************************
**  Local type definitions
************************************************************************************/
typedef struct
{
    uint32_t num_devices;
    bt_bdaddr_t devices[BTM_SEC_MAX_DEVICE_RECORDS];
} btif_bonded_devices_t;

/************************************************************************************
**  Extern variables
************************************************************************************/
extern UINT16 bta_service_id_to_uuid_lkup_tbl [BTA_MAX_SERVICE_ID];
extern bt_bdaddr_t btif_local_bd_addr;
/************************************************************************************
**  Static variables
************************************************************************************/

/************************************************************************************
**  Static functions
************************************************************************************/
/*******************************************************************************
**
** Function         btif_in_make_filename
**
** Description      Internal helper function to create NVRAM file path
**                  from address and filename
**
** Returns          NVRAM file path if successfull, NULL otherwise
**
*******************************************************************************/
static char* btif_in_make_filename(bt_bdaddr_t *bd_addr, char *fname)
{
    static char path[256];
    bdstr_t bdstr;

    if (fname == NULL)return NULL;
    if (bd_addr)
    {
        sprintf(path, "%s/%s/%s", BTIF_STORAGE_PATH_BLUEDROID,
                bd2str(bd_addr, &bdstr), fname);
    }
    else
    {
        /* local adapter */
        sprintf(path, "%s/LOCAL/%s", BTIF_STORAGE_PATH_BLUEDROID, fname);
    }

    return(char*)path;
}

/*******************************************************************************
**
** Function         btif_in_adapter_key_from_type
**
** Description      Internal helper function to map a property type
**                  to the NVRAM filename key
**
** Returns          NVRAM filename key if successfull, 'NO_KEY' otherwise
**
*******************************************************************************/
static const char *btif_in_get_adapter_key_from_type(bt_property_type_t type)
{
    switch (type)
    {
        case BT_PROPERTY_BDNAME:
            return BTIF_STORAGE_KEY_ADAPTER_NAME;
        case BT_PROPERTY_ADAPTER_SCAN_MODE:
            return BTIF_STORAGE_KEY_ADAPTER_SCANMODE;
        case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
            return BTIF_STORAGE_KEY_ADAPTER_DISC_TIMEOUT;
        default:
            /* return valid string to avoid passing NULL to NV RAM driver */
            return "NO_KEY";
    }
}

/*******************************************************************************
**
** Function         btif_in_split_uuids_string_to_list
**
** Description      Internal helper function to split the string of UUIDs
**                  read from the NVRAM to an array
**
** Returns          None
**
*******************************************************************************/
static void btif_in_split_uuids_string_to_list(char *str, bt_uuid_t *p_uuid,
                                               uint32_t *p_num_uuid)
{
    char buf[64];
    char *p_start = str;
    char *p_needle;
    uint32_t num = 0;
    do
    {
        p_needle = strchr(p_start, ';');
        if (p_needle < p_start) break;
        memset(buf, 0, sizeof(buf));
        strncpy(buf, p_start, (p_needle-p_start));
        string_to_uuid(buf, p_uuid + num);
        num++;
        p_start = ++p_needle;

    } while (*p_start != 0);
    *p_num_uuid = num;
}

/*******************************************************************************
**
** Function         btif_in_str_to_property
**
** Description      Internal helper function to convert the string read from
**                  NVRAM into a property->val. Also sets the property->len.
**                  Assumption is that property->val has enough memory to
**                  store the string fetched from NVRAM
**
** Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
**
*******************************************************************************/
static bt_status_t btif_in_str_to_property(char *value, bt_property_t *property)
{
    bt_status_t status = BT_STATUS_SUCCESS;
    property->len = 0;

    /* if Value is NULL, then just set the property->len to 0 and return.
       This is possible if the entry does not exist  */
    if (value == NULL)
    {
        status = BT_STATUS_FAIL;
    }
    switch (property->type)
    {
        case BT_PROPERTY_BDNAME:
        case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
            {
                *((char*)property->val) = 0;
                if (value)
                {
                    property->len = strlen(value);
                    strcpy((char*)property->val, value);
                }
            } break;
        case BT_PROPERTY_ADAPTER_SCAN_MODE:
        case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
            {
                *((uint32_t *)property->val) = 0;
                if (value)
                {
                    uint32_t ival;
                    property->len = sizeof(uint32_t);
                    ival = atoi(value);
                    memcpy((uint32_t*)property->val, &ival, sizeof(uint32_t));
                }
            } break;
        case BT_PROPERTY_CLASS_OF_DEVICE:
        case BT_PROPERTY_TYPE_OF_DEVICE:
            {
                *((uint32_t *)property->val) = 0;
                if (value)
                {
                    uint32_t ival;
                    property->len = sizeof(uint32_t);
                    ival = strtol(value, NULL, 16);
                    memcpy((uint32_t*)property->val, &ival, sizeof(uint32_t));
                }
            } break;
        case BT_PROPERTY_UUIDS:
            {
                if (value)
                {
                    bt_uuid_t *p_uuid = (bt_uuid_t*)property->val;
                    uint32_t num_uuids = 0;
                    btif_in_split_uuids_string_to_list(value, p_uuid, &num_uuids);
                    property->len = num_uuids * sizeof(bt_uuid_t);
                }
            } break;
        default:
            {
                break;
            }
    }
    return status;
}

/*******************************************************************************
**
** Function         btif_in_property_to_str
**
** Description      Internal helper function to convert the property->val
**                  to a string that can be written to the NVRAM
**
** Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
**
*******************************************************************************/
static bt_status_t btif_in_property_to_str(bt_property_t *property, char *value)
{
    switch (property->type)
    {
        case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
            {
                sprintf(value, "%d", (int)time(NULL));
            }break;
        case BT_PROPERTY_BDNAME:
        case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
            {
                strncpy(value, (char*)property->val, property->len);
                value[property->len]='\0';
            }break;
        case BT_PROPERTY_ADAPTER_SCAN_MODE:
        case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
            {
                sprintf(value, "%d", *((uint32_t*)property->val));
            }break;
        case BT_PROPERTY_CLASS_OF_DEVICE:
        case BT_PROPERTY_TYPE_OF_DEVICE:
            {
                sprintf(value, "0x%x", *((uint32_t*)property->val));
            }break;
        case BT_PROPERTY_UUIDS:
            {
                uint32_t i;
                char buf[64];
                value[0] = 0;
                for (i=0; i < (property->len)/sizeof(bt_uuid_t); i++)
                {
                    bt_uuid_t *p_uuid = (bt_uuid_t*)property->val + i;
                    memset(buf, 0, sizeof(buf));
                    uuid_to_string(p_uuid, buf);
                    strcat(value, buf);
                    strcat(value, ";");
                }
                value[strlen(value)] = 0;
            }break;
        default:
            {
                return BT_STATUS_FAIL;
            }
    }
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_in_get_remote_device_path_from_property
**
** Description      Internal helper function to map a property type
**                  to the NVRAM filename key
**
** Returns          NVRAM filename key if successfull, NULL otherwise
**
*******************************************************************************/
static char* btif_in_get_remote_device_path_from_property(bt_property_type_t type)
{
    switch (type)
    {
        case BT_PROPERTY_BDADDR:
        case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
            return BTIF_STORAGE_PATH_REMOTE_DEVICES;
        case BT_PROPERTY_BDNAME:
            return BTIF_STORAGE_PATH_REMOTE_NAMES;
        case BT_PROPERTY_CLASS_OF_DEVICE:
            return BTIF_STORAGE_PATH_REMOTE_DEVCLASSES;
        case BT_PROPERTY_TYPE_OF_DEVICE:
            return BTIF_STORAGE_PATH_REMOTE_DEVTYPES;
        case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
            return BTIF_STORAGE_PATH_REMOTE_ALIASES;
        case BT_PROPERTY_UUIDS:
            return BTIF_STORAGE_PATH_REMOTE_SERVICES;
        default:
            return NULL;
    }
}

/*******************************************************************************
**
** Function         btif_in_load_device_iter_cb
**
** Description      Internal iterator callback from UNV when loading the
**                  link-keys
**
** Returns
**
*******************************************************************************/

int btif_in_load_device_iter_cb(char *key, char *value, void *userdata)
{
    btif_bonded_devices_t *p_bonded_devices = (btif_bonded_devices_t *)userdata;
    DEV_CLASS dev_class = {0, 0, 0};
    bt_bdaddr_t bd_addr;
    LINK_KEY link_key;
    uint8_t key_type;
    uint8_t pin_length;
    int offset = 0;
    int8_t temp[3];
    uint32_t i;

    memset(temp, 0, sizeof(temp));

    BTIF_TRACE_DEBUG3("%s %s %s", __FUNCTION__, key, value);

    /* convert 32 char linkkey (fixed size) */
    for (i = 0; i < LINK_KEY_LEN; i++)
    {
        memcpy(temp, value + (i * 2), 2);
        link_key[i] = (uint8_t) strtol((const char *)temp, NULL, 16);
        offset+=2;
    }

    /* skip space */
    offset++;

    /* convert decimal keytype (max 2 ascii chars) */
    memset(temp, 0, sizeof(temp));
    memcpy(temp, value + offset, 2);
    key_type = (uint8_t)strtoul((const char *)temp, NULL, 10);

    /* value + space */
    offset+=2;

    /* convert decimal pinlen (max 2 ascii chars) */
    memset(temp, 0, sizeof(temp));
    memcpy(temp, value + offset, 2);
    pin_length = (uint8_t)strtoul((const char *)temp, NULL, 10);

    /* convert bd address (keystring) */
    str2bd(key, &bd_addr);

    /* add extracted information to BTA security manager */
    BTA_DmAddDevice(bd_addr.address, dev_class, link_key, 0, 0, key_type, 0);

    /* Fill in the bonded devices */
    memcpy(&p_bonded_devices->devices[p_bonded_devices->num_devices++], &bd_addr, sizeof(bt_bdaddr_t));

    return 0;
}


int btif_in_get_device_iter_cb(char *key, char *value, void *userdata)
{
    btif_bonded_devices_t *p_bonded_devices = (btif_bonded_devices_t *)userdata;
    DEV_CLASS dev_class = {0, 0, 0};
    bt_bdaddr_t bd_addr;
    LINK_KEY link_key;
    uint8_t key_type;
    uint8_t pin_length;
    int offset = 0;
    int8_t temp[3];
    uint32_t i;

    memset(temp, 0, sizeof(temp));

    BTIF_TRACE_DEBUG3("%s %s %s", __FUNCTION__, key, value);

    /* convert 32 char linkkey (fixed size) */
    for (i = 0; i < LINK_KEY_LEN; i++)
    {
        memcpy(temp, value + (i * 2), 2);
        link_key[i] = (uint8_t) strtol((const char *)temp, NULL, 16);
        offset+=2;
    }

    /* skip space */
    offset++;

    /* convert decimal keytype (max 2 ascii chars) */
    memset(temp, 0, sizeof(temp));
    memcpy(temp, value + offset, 2);
    key_type = (uint8_t)strtoul((const char *)temp, NULL, 10);

    /* value + space */
    offset+=2;

    /* convert decimal pinlen (max 2 ascii chars) */
    memset(temp, 0, sizeof(temp));
    memcpy(temp, value + offset, 2);
    pin_length = (uint8_t)strtoul((const char *)temp, NULL, 10);

    /* convert bd address (keystring) */
    str2bd(key, &bd_addr);


     /* Fill in the bonded devices */
    memcpy(&p_bonded_devices->devices[p_bonded_devices->num_devices++], &bd_addr, sizeof(bt_bdaddr_t));

    return 0;
}

/*******************************************************************************
**
** Function         btif_in_fetch_bonded_devices
**
** Description      Internal helper function to fetch the bonded devices
**                  from NVRAM
**
** Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
**
*******************************************************************************/
static bt_status_t btif_in_fetch_and_load_bonded_devices(btif_bonded_devices_t *p_bonded_devices)
{
    char *fname;
    int ret;

    memset(p_bonded_devices, 0, sizeof(btif_bonded_devices_t));

    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_REMOTE_LINKKEYS);

    if (fname == NULL)
        return BT_STATUS_FAIL;

    ret = unv_read_key_iter(fname, btif_in_load_device_iter_cb, p_bonded_devices);

    if (ret < 0)
        return BT_STATUS_FAIL;

    return BT_STATUS_SUCCESS;
}

static bt_status_t btif_in_fetch_bonded_devices(btif_bonded_devices_t *p_bonded_devices)
{
    char *fname;
    int ret;

    memset(p_bonded_devices, 0, sizeof(btif_bonded_devices_t));

    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_REMOTE_LINKKEYS);

    if (fname == NULL)
        return BT_STATUS_FAIL;

    ret = unv_read_key_iter(fname, btif_in_get_device_iter_cb, p_bonded_devices);

    if (ret < 0)
        return BT_STATUS_FAIL;

    return BT_STATUS_SUCCESS;
}

static int hex_str_to_int(const char* str, int size)
{
    int  n = 0;
    char c = *str++;
    while (size-- != 0)
    {
        n <<= 4;
        if (c >= '0' && c <= '9') {
            n |= c - '0';
        }
        else if (c >= 'a' && c <= 'z') {
            n |= c - 'a' + 10;
        }
        else // (c >= 'A' && c <= 'Z')
        {
            n |= c - 'A' + 10;
        }

        c = *str++;
    }
    return n;
}

/*******************************************************************************
**
** Function         btif_in_load_hid_info_iter_cb
**
** Description      Internal iterator callback from UNV when loading the
**                  hid device info
**
** Returns
**
*******************************************************************************/

int btif_in_load_hid_info_iter_cb(char *key, char *value, void *userdata)
{
    btif_bonded_devices_t *p_bonded_devices = (btif_bonded_devices_t *)userdata;
    bt_bdaddr_t bd_addr;
    tBTA_HH_DEV_DSCP_INFO dscp_info;
    uint32_t i;
    uint16_t attr_mask,a;
    uint8_t  sub_class;
    uint8_t  app_id;
    BD_ADDR* bda;
    char     *p;


    BTIF_TRACE_DEBUG3("%s - %s - %s", __FUNCTION__, key, value);

    p = value;
    attr_mask = (uint16_t) hex_str_to_int(p, 4);
    p +=5;
    sub_class = (uint8_t) hex_str_to_int(p, 2);
    p +=3;
    app_id = (uint8_t) hex_str_to_int(p, 2);
    p +=3;
    dscp_info.vendor_id = (uint16_t) hex_str_to_int(p, 4);
    p += 5;
    dscp_info.product_id = (uint16_t) hex_str_to_int(p, 4);
    p += 5;
    dscp_info.version = (uint8_t) hex_str_to_int(p, 4);
    p += 5;
    dscp_info.ctry_code = (uint8_t) hex_str_to_int(p, 2);
    p += 3;
    dscp_info.descriptor.dl_len = (uint16_t) hex_str_to_int(p, 4);
    p += 5;

    dscp_info.descriptor.dsc_list = (UINT8 *) GKI_getbuf(dscp_info.descriptor.dl_len);
    if (dscp_info.descriptor.dsc_list == NULL)
    {
        ALOGE("%s: Failed to allocate DSCP for CB", __FUNCTION__);
        return BT_STATUS_FAIL;
    }
    for (i = 0; i < dscp_info.descriptor.dl_len; i++)
    {
        dscp_info.descriptor.dsc_list[i] = (uint8_t) hex_str_to_int(p, 2);
        p += 2;
    }

    /* convert bd address (keystring) */
    str2bd(key, &bd_addr);
    bda = (BD_ADDR*) &bd_addr;

    // add extracted information to BTA HH
    if (btif_hh_add_added_dev(bd_addr,attr_mask))
    {
        BTIF_TRACE_DEBUG0("btif_in_load_hid_info_iter_cb: adding device");
        BTA_HhAddDev(bd_addr.address, attr_mask, sub_class,
                     app_id, dscp_info);
    }

    GKI_freebuf(dscp_info.descriptor.dsc_list);
    return 0;
}

/************************************************************************************
**  Externs
************************************************************************************/

/************************************************************************************
**  Functions
************************************************************************************/

/** functions are synchronous.
 * functions can be called by both internal modules such as BTIF_DM and by external entiries from HAL via BTIF_context_switch
 * For OUT parameters,  caller is expected to provide the memory.
 * Caller is expected to provide a valid pointer to 'property->value' based on the property->type
 */
/*******************************************************************************
**
** Function         btif_storage_get_adapter_property
**
** Description      BTIF storage API - Fetches the adapter property->type
**                  from NVRAM and fills property->val.
**                  Caller should provide memory for property->val and
**                  set the property->val
**
** Returns          BT_STATUS_SUCCESS if the fetch was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_get_adapter_property(bt_property_t *property)
{
    bt_status_t status;
    char *fname;
    char *value;
    int ret;
    char linebuf[BTIF_STORAGE_MAX_LINE_SZ];

    /* initialize property->len */
    property->len = 0;

    /* Special handling for adapter BD_ADDR and BONDED_DEVICES */
    if (property->type == BT_PROPERTY_BDADDR)
    {
        BD_ADDR addr;
        bt_bdaddr_t *bd_addr = (bt_bdaddr_t*)property->val;
        /* This has been cached in btif. Just fetch it from there */
        memcpy(bd_addr, &btif_local_bd_addr, sizeof(bt_bdaddr_t));
        property->len = sizeof(bt_bdaddr_t);
        return BT_STATUS_SUCCESS;
    }
    else if (property->type == BT_PROPERTY_ADAPTER_BONDED_DEVICES)
    {
        btif_bonded_devices_t bonded_devices;

        btif_in_fetch_bonded_devices(&bonded_devices);

        BTIF_TRACE_DEBUG2("%s: Number of bonded devices: %d Property:BT_PROPERTY_ADAPTER_BONDED_DEVICES", __FUNCTION__, bonded_devices.num_devices);

        if (bonded_devices.num_devices > 0)
        {
            property->len = bonded_devices.num_devices * sizeof(bt_bdaddr_t);
            memcpy(property->val, bonded_devices.devices, property->len);
        }

        /* if there are no bonded_devices, then length shall be 0 */
        return BT_STATUS_SUCCESS;
    }
    else if (property->type == BT_PROPERTY_UUIDS)
    {
        /* publish list of local supported services */
        bt_uuid_t *p_uuid = (bt_uuid_t*)property->val;
        uint32_t num_uuids = 0;
        uint32_t i;

        tBTA_SERVICE_MASK service_mask = btif_get_enabled_services_mask();
        BTIF_TRACE_ERROR2("%s service_mask:0x%x", __FUNCTION__, service_mask);
        for (i=0; i < BTA_MAX_SERVICE_ID; i++)
        {
            /* This should eventually become a function when more services are enabled */
            if (service_mask
                &(tBTA_SERVICE_MASK)(1 << i))
            {
                switch (i)
                {
                    case BTA_HFP_SERVICE_ID:
                        {
                            uuid16_to_uuid128(UUID_SERVCLASS_AG_HANDSFREE,
                                              p_uuid+num_uuids);
                            num_uuids++;
                            uuid16_to_uuid128(UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY,
                                              p_uuid+num_uuids);
                            num_uuids++;
                        }break;
                    case BTA_A2DP_SERVICE_ID:
                        {
                            uuid16_to_uuid128(UUID_SERVCLASS_AUDIO_SOURCE,
                                              p_uuid+num_uuids);
                            num_uuids++;
                        }break;
                }
            }
        }
        property->len = (num_uuids)*sizeof(bt_uuid_t);
        return BT_STATUS_SUCCESS;
    }

    /* fall through for other properties */

    /* create filepath */
    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_ADAPTER_INFO);

    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }

    ret = unv_create_file(fname);

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    value = unv_read_key( fname,
                          btif_in_get_adapter_key_from_type(property->type),
                          linebuf, UNV_MAXLINE_LENGTH);

    if (value == NULL)
    {
        /* properties not yet existing, request default values from bta */
        return btif_dm_get_adapter_property(property);
    }
    else
    {
        /* convert to property_t data structure */
        status = btif_in_str_to_property(value, property);
    }

    return status;
}

/*******************************************************************************
**
** Function         btif_storage_set_adapter_property
**
** Description      BTIF storage API - Stores the adapter property
**                  to NVRAM
**
** Returns          BT_STATUS_SUCCESS if the store was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_set_adapter_property(bt_property_t *property)
{
    char *fname;
    char value[1200];
    int ret;

    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_ADAPTER_INFO);
    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }
    ret = unv_create_file(fname);
    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    if (btif_in_property_to_str(property, value) != BT_STATUS_SUCCESS)
    {
        return BT_STATUS_FAIL;
    }
    ret = unv_write_key(fname, btif_in_get_adapter_key_from_type(property->type), value);
    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_get_remote_device_property
**
** Description      BTIF storage API - Fetches the remote device property->type
**                  from NVRAM and fills property->val.
**                  Caller should provide memory for property->val and
**                  set the property->val
**
** Returns          BT_STATUS_SUCCESS if the fetch was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_get_remote_device_property(bt_bdaddr_t *remote_bd_addr,
                                                    bt_property_t *property)
{
    char linebuf[BTIF_STORAGE_MAX_LINE_SZ];
    char *fname;
    char *value;
    int ret;
    bdstr_t bdstr;

    fname = btif_in_make_filename(NULL,
                                  btif_in_get_remote_device_path_from_property(property->type));

    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }


    ret = unv_create_file(fname);
    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    value = unv_read_key(fname, bd2str(remote_bd_addr, &bdstr), linebuf, BTIF_STORAGE_MAX_LINE_SZ);

    return btif_in_str_to_property(value, property);
}

/*******************************************************************************
**
** Function         btif_storage_set_remote_device_property
**
** Description      BTIF storage API - Stores the remote device property
**                  to NVRAM
**
** Returns          BT_STATUS_SUCCESS if the store was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_set_remote_device_property(bt_bdaddr_t *remote_bd_addr,
                                                    bt_property_t *property)
{
    char value[1200];
    char *fname;
    bdstr_t bdstr;
    int ret;

    fname = btif_in_make_filename(NULL,
                                  btif_in_get_remote_device_path_from_property(property->type));


    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }


    ret = unv_create_file(fname);
    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }
    memset(value, 0, sizeof(value));

    if (btif_in_property_to_str(property, value) != BT_STATUS_SUCCESS)
    {
        return BT_STATUS_FAIL;
    }

    ret = unv_write_key(fname, bd2str(remote_bd_addr, &bdstr), value);
    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_add_remote_device
**
** Description      BTIF storage API - Adds a newly discovered device to NVRAM
**                  along with the timestamp. Also, stores the various
**                  properties - RSSI, BDADDR, NAME (if found in EIR)
**
** Returns          BT_STATUS_SUCCESS if the store was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_add_remote_device(bt_bdaddr_t *remote_bdaddr,
                                           uint32_t num_properties,
                                           bt_property_t *properties)
{
    uint32_t i = 0;
    /* TODO: If writing a property, fails do we go back undo the earlier
     * written properties? */
    for (i=0; i < num_properties; i++)
    {
        /* Ignore the RSSI as this is not stored in DB */
        if (properties[i].type == BT_PROPERTY_REMOTE_RSSI)
            continue;

        /* BD_ADDR for remote device needs special handling as we also store timestamp */
        if (properties[i].type == BT_PROPERTY_BDADDR)
        {
            bt_property_t addr_prop;
            memcpy(&addr_prop, &properties[i], sizeof(bt_property_t));
            addr_prop.type = BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP;
            btif_storage_set_remote_device_property(remote_bdaddr,
                                                    &addr_prop);
        }
        else
        {
            btif_storage_set_remote_device_property(remote_bdaddr,
                                                    &properties[i]);
        }
    }
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_add_bonded_device
**
** Description      BTIF storage API - Adds the newly bonded device to NVRAM
**                  along with the link-key, Key type and Pin key length
**
** Returns          BT_STATUS_SUCCESS if the store was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/

bt_status_t btif_storage_add_bonded_device(bt_bdaddr_t *remote_bd_addr,
                                           LINK_KEY link_key,
                                           uint8_t key_type,
                                           uint8_t pin_length)
{
    char value[STORAGE_REMOTE_LINKKEYS_ENTRY_SIZE];
    uint32_t i = 0;
    char *fname;
    bdstr_t bdstr;
    int ret;

    fname = btif_in_make_filename(NULL,
                                  BTIF_STORAGE_PATH_REMOTE_LINKKEYS);
    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }
    ret = unv_create_file(fname);

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    /* check ascii representations doesn't exceed max size */

    if (key_type > STORAGE_KEY_TYPE_MAX)
        return BT_STATUS_FAIL;

    if (pin_length > PIN_CODE_LEN)
        return BT_STATUS_FAIL;

    memset(value, 0, sizeof(value));

    for (i = 0; i < LINK_KEY_LEN; i++)
        sprintf(value + (i * 2), "%2.2X", link_key[i]);

    sprintf(value + (LINK_KEY_LEN*2), " %d %d", key_type, pin_length);

    ret = unv_write_key(fname, bd2str(remote_bd_addr, &bdstr), value);

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_remove_bonded_device
**
** Description      BTIF storage API - Deletes the bonded device from NVRAM
**
** Returns          BT_STATUS_SUCCESS if the deletion was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_remove_bonded_device(bt_bdaddr_t *remote_bd_addr)
{
    char *fname;
    int ret;
    bdstr_t bdstr;

    fname = btif_in_make_filename(NULL,
                                  BTIF_STORAGE_PATH_REMOTE_LINKKEYS);
    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }
    ret = unv_create_file(fname);

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    ret = unv_remove_key(fname, bd2str(remote_bd_addr, &bdstr));

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_load_bonded_devices
**
** Description      BTIF storage API - Loads all the bonded devices from NVRAM
**                  and adds to the BTA.
**                  Additionally, this API also invokes the adaper_properties_cb
**                  and remote_device_properties_cb for each of the bonded devices.
**
** Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_load_bonded_devices(void)
{
    char *fname;
    btif_bonded_devices_t bonded_devices;
    uint32_t i = 0;
    bt_property_t adapter_props[6];
    uint32_t num_props = 0;
    bt_property_t remote_properties[8];
    bt_bdaddr_t addr;
    bt_bdname_t name, alias;
    bt_scan_mode_t mode;
    uint32_t disc_timeout;
    bt_bdaddr_t *devices_list;
    bt_uuid_t local_uuids[BT_MAX_NUM_UUIDS];
    bt_uuid_t remote_uuids[BT_MAX_NUM_UUIDS];
    uint32_t cod, devtype;

    btif_in_fetch_and_load_bonded_devices(&bonded_devices);

    /* Now send the adapter_properties_cb with all adapter_properties */
    {
        memset(adapter_props, 0, sizeof(adapter_props));

        /* BD_ADDR */
        BTIF_STORAGE_GET_ADAPTER_PROP(BT_PROPERTY_BDADDR, &addr, sizeof(addr),
                                      adapter_props[num_props]);
        num_props++;

        /* BD_NAME */
        BTIF_STORAGE_GET_ADAPTER_PROP(BT_PROPERTY_BDNAME, &name, sizeof(name),
                                      adapter_props[num_props]);
        num_props++;

        /* SCAN_MODE */
        /* TODO: At the time of BT on, always report the scan mode as 0 irrespective
         of the scan_mode during the previous enable cycle.
         This needs to be re-visited as part of the app/stack enable sequence
         synchronization */
        mode = BT_SCAN_MODE_NONE;
        adapter_props[num_props].type = BT_PROPERTY_ADAPTER_SCAN_MODE;
        adapter_props[num_props].len = sizeof(mode);
        adapter_props[num_props].val = &mode;
        num_props++;

        /* DISC_TIMEOUT */
        BTIF_STORAGE_GET_ADAPTER_PROP(BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT,
                                      &disc_timeout, sizeof(disc_timeout),
                                      adapter_props[num_props]);
        num_props++;

        /* BONDED_DEVICES */
        devices_list = (bt_bdaddr_t*)malloc(sizeof(bt_bdaddr_t)*bonded_devices.num_devices);
        adapter_props[num_props].type = BT_PROPERTY_ADAPTER_BONDED_DEVICES;
        adapter_props[num_props].len = bonded_devices.num_devices * sizeof(bt_bdaddr_t);
        adapter_props[num_props].val = devices_list;
        for (i=0; i < bonded_devices.num_devices; i++)
        {
            memcpy(devices_list + i, &bonded_devices.devices[i], sizeof(bt_bdaddr_t));
        }
        num_props++;

        /* LOCAL UUIDs */
        BTIF_STORAGE_GET_ADAPTER_PROP(BT_PROPERTY_UUIDS,
                                      local_uuids, sizeof(local_uuids),
                                      adapter_props[num_props]);
        num_props++;

        btif_adapter_properties_evt(BT_STATUS_SUCCESS, num_props, adapter_props);

        free(devices_list);
    }

    BTIF_TRACE_EVENT2("%s: %d bonded devices found", __FUNCTION__, bonded_devices.num_devices);

    {
        for (i = 0; i < bonded_devices.num_devices; i++)
        {
            bt_bdaddr_t *p_remote_addr;

            num_props = 0;
            p_remote_addr = &bonded_devices.devices[i];
            memset(remote_properties, 0, sizeof(remote_properties));
            BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_BDNAME,
                                         &name, sizeof(name),
                                         remote_properties[num_props]);
            num_props++;

            BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_REMOTE_FRIENDLY_NAME,
                                         &alias, sizeof(alias),
                                         remote_properties[num_props]);
            num_props++;

            BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_CLASS_OF_DEVICE,
                                         &cod, sizeof(cod),
                                         remote_properties[num_props]);
            num_props++;

            BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_TYPE_OF_DEVICE,
                                         &devtype, sizeof(devtype),
                                         remote_properties[num_props]);
            num_props++;

            BTIF_STORAGE_GET_REMOTE_PROP(p_remote_addr, BT_PROPERTY_UUIDS,
                                         remote_uuids, sizeof(remote_uuids),
                                         remote_properties[num_props]);
            num_props++;

            btif_remote_properties_evt(BT_STATUS_SUCCESS, p_remote_addr,
                                       num_props, remote_properties);
        }
    }
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_add_hid_device_info
**
** Description      BTIF storage API - Adds the hid information of bonded hid devices-to NVRAM
**
** Returns          BT_STATUS_SUCCESS if the store was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/

bt_status_t btif_storage_add_hid_device_info(bt_bdaddr_t *remote_bd_addr,
                                                    UINT16 attr_mask, UINT8 sub_class,
                                                    UINT8 app_id, UINT16 vendor_id,
                                                    UINT16 product_id, UINT16 version,
                                                    UINT8 ctry_code, UINT16 dl_len, UINT8 *dsc_list)
{
    char  *hid_info;
    uint32_t i = 0;
    char *fname;
    bdstr_t bdstr;
    int ret;

    char*    p;
    size_t   size;

    fname = btif_in_make_filename(NULL,
                                  BTIF_STORAGE_PATH_REMOTE_HIDINFO);
    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }
    ret = unv_create_file(fname);

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }
    BTIF_TRACE_DEBUG1("%s",__FUNCTION__);

/* value = <attr_mask> <space> > <sub_class> <space> <app_id> <space>
                                <vendor_id> <space> > <product_id> <space> <version> <space>
                                <ctry_code> <space> > <desc_len> <space> <desc_list> <space> */
    size = (STORAGE_BDADDR_STRING_SZ + 1 + STORAGE_HID_ATRR_MASK_SIZE + 1 +
            STORAGE_HID_SUB_CLASS_SIZE + 1 + STORAGE_HID_APP_ID_SIZE+ 1 +
            STORAGE_HID_VENDOR_ID_SIZE+ 1 + STORAGE_HID_PRODUCT_ID_SIZE+ 1 +
            STORAGE_HID_VERSION_SIZE+ 1 + STORAGE_HID_CTRY_CODE_SIZE+ 1 +
            STORAGE_HID_DESC_LEN_SIZE+ 1 + (dl_len *2)+1);

    hid_info = (char *) malloc(size);
    if (hid_info == NULL) {
        BTIF_TRACE_ERROR2("%s: Oops, failed to allocate %d byte buffer for HID info string",
              __FUNCTION__, size);
        return BT_STATUS_FAIL;
    }

    //Convert the entries to hex and copy it to hid_info
    sprintf(hid_info, "%04X %02X %02X %04X %04X %04X %02X %04X ",
            attr_mask,sub_class,app_id,vendor_id,product_id,version,ctry_code,dl_len);

    i = 0;
    p = &hid_info[strlen(hid_info)];
    while ((i + 16) <= dl_len) {
        sprintf(p, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                dsc_list[i],    dsc_list[i+1],  dsc_list[i+2],  dsc_list[i+3],
                dsc_list[i+4],  dsc_list[i+5],  dsc_list[i+6],  dsc_list[i+7],
                dsc_list[i+8],  dsc_list[i+9],  dsc_list[i+10], dsc_list[i+11],
                dsc_list[i+12], dsc_list[i+13], dsc_list[i+14], dsc_list[i+15]);
        p += 32;
        i += 16;
    }
    if ((i + 8) <= dl_len) {
        sprintf(p, "%02X%02X%02X%02X%02X%02X%02X%02X",
                dsc_list[i],   dsc_list[i+1], dsc_list[i+2], dsc_list[i+3],
                dsc_list[i+4], dsc_list[i+5], dsc_list[i+6], dsc_list[i+7]);
        p += 16;
        i += 8;
    }
    if ((i + 4) <= dl_len) {
        sprintf(p, "%02X%02X%02X%02X",
                dsc_list[i], dsc_list[i+1], dsc_list[i+2], dsc_list[i+3]);
        p += 8;
        i += 4;
    }
    if ((i + 3) == dl_len) {
        sprintf(p, "%02X%02X%02X", dsc_list[i], dsc_list[i+1], dsc_list[i+2]);
        p += 6;
    }
    else if ((i + 2) == dl_len) {
        sprintf(p, "%02X%02X", dsc_list[i], dsc_list[i+1]);
        p += 4;
    }
    else if ((i + 1) == dl_len) {
        sprintf(p, "%02X", dsc_list[i]);
        p += 2;
    }
    *p = '\0';

    ret = unv_write_key(fname, bd2str(remote_bd_addr, &bdstr), hid_info);
    free(hid_info);
    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_load_bonded_hid_info
**
** Description      BTIF storage API - Loads hid info for all the bonded devices from NVRAM
**                  and adds those devices  to the BTA_HH.
**
** Returns          BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_load_bonded_hid_info(void)
{
    char *fname;
    int ret;
    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_REMOTE_HIDINFO);

    if (fname == NULL)
        return BT_STATUS_FAIL;

    ret = unv_read_key_iter(fname, btif_in_load_hid_info_iter_cb, NULL);

    if (ret < 0)
        return BT_STATUS_FAIL;

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_remove_hid_info
**
** Description      BTIF storage API - Deletes the bonded hid device info from NVRAM
**
** Returns          BT_STATUS_SUCCESS if the deletion was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_remove_hid_info(bt_bdaddr_t *remote_bd_addr)
{
    char *fname;
    int ret;
    bdstr_t bdstr;

    fname = btif_in_make_filename(NULL,
                                  BTIF_STORAGE_PATH_REMOTE_HIDINFO);
    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }
    ret = unv_create_file(fname);

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    ret = unv_remove_key(fname, bd2str(remote_bd_addr, &bdstr));

    if (ret < 0)
    {
        return BT_STATUS_FAIL;
    }

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_read_hl_apps_cb
**
** Description      BTIF storage API - Read HL application control block from NVRAM
**
** Returns          BT_STATUS_SUCCESS if the operation was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_read_hl_apps_cb(char *value, int value_size)
{
    char  fname[256],  tmp[3];
    bt_status_t bt_status = BT_STATUS_SUCCESS;
    int   status=FALSE, i, buf_size;
    char *p_buf;

    BTIF_TRACE_DEBUG1("%s ", __FUNCTION__);
    sprintf(fname, "%s/LOCAL/%s", BTIF_STORAGE_PATH_BLUEDROID, BTIF_STORAGE_HL_APP_CB);
    buf_size = value_size*2;
    p_buf = malloc(buf_size);
    BTIF_TRACE_DEBUG2("value_size=%d buf_size=%d", value_size, buf_size);
    if (p_buf)
    {
        if ((status = unv_read_hl_apps_cb(fname, p_buf, buf_size))!=0)
        {
            bt_status = BT_STATUS_FAIL;
        }
        else
        {
            for (i = 0; i < value_size; i++)
            {
                memcpy(tmp, p_buf + (i * 2), 2);
                value[i] = (uint8_t) strtol(tmp, NULL, 16);
            }
        }

        free(p_buf);
    }
    else
    {
        bt_status = BT_STATUS_FAIL;
    }

    BTIF_TRACE_DEBUG4("%s read file:(%s) read status=%d bt_status=%d", __FUNCTION__,  fname, status, bt_status);
    return bt_status;
}

/*******************************************************************************
**
** Function         btif_storage_write_hl_apps_cb
**
** Description      BTIF storage API - Write HL application control block to NVRAM
**
** Returns          BT_STATUS_SUCCESS if the operation was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_write_hl_apps_cb(char *value, int value_size)
{
    char  fname[256];
    bt_status_t bt_status = BT_STATUS_SUCCESS;
    int   status=FALSE, i, buf_size;
    char *p_buf;

    BTIF_TRACE_DEBUG1("%s ", __FUNCTION__);
    sprintf(fname, "%s/LOCAL/%s", BTIF_STORAGE_PATH_BLUEDROID, BTIF_STORAGE_HL_APP_CB);
    buf_size = value_size * 2;
    p_buf = malloc(buf_size);
    BTIF_TRACE_DEBUG2("value_size=%d buf_size=%d", value_size, buf_size);
    if (p_buf)
    {
        for (i = 0; i < value_size; i++)
            sprintf(p_buf + (i * 2), "%2.2X", value[i]);

        if ((status = unv_write_hl_apps_cb(fname, p_buf, buf_size))!=0)
            bt_status = BT_STATUS_FAIL;

        free(p_buf);
    }
    else
    {
        bt_status = BT_STATUS_FAIL;
    }
    BTIF_TRACE_DEBUG4("%s write file:(%s) write status=%d bt_status=%d", __FUNCTION__,  fname, status, bt_status);
    return bt_status;
}

bt_status_t btif_storage_read_hl_data(char *fname, char *value, int value_size)
{
    char            tmp[3];
    bt_status_t     bt_status = BT_STATUS_SUCCESS;
    int             i, buf_size;
    char            *p_buf;

    buf_size = value_size*2;
    p_buf = malloc(buf_size);
    BTIF_TRACE_DEBUG3("%s value_size=%d buf_size=%d", __FUNCTION__, value_size, buf_size);
    if (p_buf)
    {
        if (unv_read_hl_data(fname, p_buf, buf_size) != 0)
        {
            bt_status = BT_STATUS_FAIL;
        }
        else
        {
            for (i = 0; i < value_size; i++)
            {
                memcpy(tmp, p_buf + (i * 2), 2);
                value[i] = (uint8_t) strtol(tmp, NULL, 16);
            }
        }
        free(p_buf);
    }
    else
    {
        bt_status = BT_STATUS_FAIL;
    }
    BTIF_TRACE_DEBUG1("bt_status=%d",   bt_status);
    return bt_status;
}

bt_status_t btif_storage_write_hl_data(char *fname, char *value, int value_size)
{
    bt_status_t bt_status = BT_STATUS_SUCCESS;
    int         i, buf_size;
    char        *p_buf;

    buf_size = value_size * 2;
    p_buf = malloc(buf_size);
    BTIF_TRACE_DEBUG3("%s value_size=%d buf_size=%d", __FUNCTION__, value_size, buf_size);
    if (p_buf)
    {
        for (i = 0; i < value_size; i++)
            sprintf(p_buf + (i * 2), "%2.2X", value[i]);

        if ( unv_write_hl_data(fname, p_buf, buf_size)!= 0)
            bt_status = BT_STATUS_FAIL;

        free(p_buf);
    }
    else
    {
        bt_status = BT_STATUS_FAIL;
    }
    BTIF_TRACE_DEBUG1("bt_status=%d",   bt_status);

    return bt_status;
}

/*******************************************************************************
**
** Function         btif_storage_read_hl_apps_cb
**
** Description      BTIF storage API - Read HL application configuration from NVRAM
**
** Returns          BT_STATUS_SUCCESS if the operation was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_read_hl_app_data(UINT8 app_idx, char *value, int value_size)
{
    char  fname[256];
    bt_status_t bt_status = BT_STATUS_SUCCESS;

    BTIF_TRACE_DEBUG1("%s ", __FUNCTION__);
    sprintf(fname, "%s/LOCAL/%s%d", BTIF_STORAGE_PATH_BLUEDROID, BTIF_STORAGE_HL_APP_DATA, app_idx);
    bt_status = btif_storage_read_hl_data(fname,  value, value_size);
    BTIF_TRACE_DEBUG3("%s read file:(%s) bt_status=%d", __FUNCTION__, fname,   bt_status);

    return bt_status;
}

/*******************************************************************************
**
** Function         btif_storage_read_hl_mdl_data
**
** Description      BTIF storage API - Read HL application MDL configuration from NVRAM
**
** Returns          BT_STATUS_SUCCESS if the operation was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_write_hl_app_data(UINT8 app_idx, char *value, int value_size)
{
    char  fname[256];
    bt_status_t bt_status = BT_STATUS_SUCCESS;


    BTIF_TRACE_DEBUG1("%s ", __FUNCTION__);
    sprintf(fname, "%s/LOCAL/%s%d", BTIF_STORAGE_PATH_BLUEDROID, BTIF_STORAGE_HL_APP_DATA, app_idx);
    bt_status = btif_storage_write_hl_data(fname,  value, value_size);
    BTIF_TRACE_DEBUG3("%s write file:(%s) bt_status=%d", __FUNCTION__, fname,   bt_status);

    return bt_status;
}

/*******************************************************************************
**
** Function         btif_storage_read_hl_mdl_data
**
** Description      BTIF storage API - Read HL application MDL configuration from NVRAM
**
** Returns          BT_STATUS_SUCCESS if the operation was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_read_hl_mdl_data(UINT8 app_idx, char *value, int value_size)
{
    char  fname[256],  tmp[3];
    bt_status_t bt_status = BT_STATUS_SUCCESS;
    int   status, i, buf_size;
    char *p_buf;

    BTIF_TRACE_DEBUG1("%s ", __FUNCTION__);
    sprintf(fname, "%s/LOCAL/%s%d", BTIF_STORAGE_PATH_BLUEDROID, BTIF_STORAGE_HL_APP_MDL_DATA, app_idx);
    bt_status = btif_storage_read_hl_data(fname,  value, value_size);
    BTIF_TRACE_DEBUG3("%s read file:(%s) bt_status=%d", __FUNCTION__, fname,   bt_status);

    return bt_status;
}

/*******************************************************************************
**
** Function         btif_storage_write_hl_mdl_data
**
** Description      BTIF storage API - Write HL application MDL configuration from NVRAM
**
** Returns          BT_STATUS_SUCCESS if the operation was successful,
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_write_hl_mdl_data(UINT8 app_idx, char *value, int value_size)
{
    char  fname[256];
    bt_status_t bt_status = BT_STATUS_SUCCESS;
    int   status, i, buf_size;
    char *p_buf;

    BTIF_TRACE_DEBUG1("%s ", __FUNCTION__);
    sprintf(fname, "%s/LOCAL/%s%d", BTIF_STORAGE_PATH_BLUEDROID, BTIF_STORAGE_HL_APP_MDL_DATA, app_idx);
    bt_status = btif_storage_write_hl_data(fname,  value, value_size);
    BTIF_TRACE_DEBUG3("%s write file:(%s) bt_status=%d", __FUNCTION__, fname,   bt_status);

    return bt_status;
}

/*******************************************************************************
**
** Function         btif_storage_load_autopair_device_list
**
** Description      BTIF storage API - Populates auto pair device list
**
** Returns          BT_STATUS_SUCCESS if the auto pair blacklist is successfully populated
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/

bt_status_t btif_storage_load_autopair_device_list()
{
    char *fname, *key_name, *key_value;
    int ret , i=0;
    char linebuf[BTIF_STORAGE_MAX_LINE_SZ];
    char *line;
    FILE *fp;

    /* check if the auto pair device list is already present in the  NV memory */
    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST);

    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }

    key_value = unv_read_key(fname,BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_ADDR,linebuf, BTIF_STORAGE_MAX_LINE_SZ);

    if (key_value  ==  NULL)
    {
        /* first time loading of auto pair blacklist configuration  */
        ret = unv_create_file(fname);

        if (ret < 0)
        {
            ALOGE("%s: Failed to create dynamic auto pair blacklist", __FUNCTION__);
            return BT_STATUS_FAIL;
        }
        fp = fopen (BTIF_AUTO_PAIR_CONF_FILE, "r");

        if (fp == NULL)
        {
            ALOGE("%s: Failed to open auto pair blacklist conf file at %s", __FUNCTION__,BTIF_AUTO_PAIR_CONF_FILE );
            return BT_STATUS_FAIL;
        }

        /* read through auto_pairing.conf file and create the key value pairs specific to  auto pair blacklist devices */
        while (fgets(linebuf, BTIF_STORAGE_MAX_LINE_SZ, fp) != NULL)
        {
            /* trip  leading white spaces */
            while (linebuf[i] == BTIF_AUTO_PAIR_CONF_SPACE)
                i++;

            /* skip  commented lines */
            if (linebuf[i] == BTIF_AUTO_PAIR_CONF_COMMENT)
                continue;

            line = (char*)&(linebuf[i]);

            if (line == NULL)
                continue;

            key_name = strtok(line, BTIF_AUTO_PAIR_CONF_KEY_VAL_DELIMETER);

            if (key_name == NULL)
                continue;
            else if((strcmp(key_name, BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_ADDR) == 0) ||
                    (strcmp(key_name, BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_EXACTNAME) ==0) ||
                    (strcmp(key_name, BTIF_STORAGE_KEY_AUTOPAIR_FIXPIN_KBLIST) ==0 ) ||
                    (strcmp(key_name, BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_PARTIALNAME) == 0) ||
                    (strcmp(key_name, BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR) == 0))
            {
                key_value = strtok(NULL, BTIF_AUTO_PAIR_CONF_KEY_VAL_DELIMETER);
                unv_write_key (fname, key_name, key_value);
            }
        }
        fclose(fp);
    }
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_storage_is_device_autopair_blacklisted
**
** Description      BTIF storage API  Checks if the given device is blacklisted for auto pairing
**
** Returns          TRUE if the device is found in the auto pair blacklist
**                  FALSE otherwise
**
*******************************************************************************/
BOOLEAN  btif_storage_is_device_autopair_blacklisted(bt_bdaddr_t *remote_dev_addr)
{
    char *fname;
    char *value, *token;
    int ret;
    bdstr_t bdstr;
    char bd_addr_lap[9];
    char *dev_name_str;
    uint8_t i = 0;
    char linebuf[BTIF_STORAGE_MAX_LINE_SZ];

    bd2str(remote_dev_addr, &bdstr);

    /* create a string with  Lower Address Part from BD Address */
      snprintf(bd_addr_lap, 9,  "%s",  (char*)bdstr);

     for ( i =0; i <strlen(bd_addr_lap) ;i++)
     {
         bd_addr_lap[i] = toupper(bd_addr_lap[i]);
     }
    /* create filepath */
    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST);

    /* check if this device address LAP is same as one of the auto pair blackliseted LAP */
    value = unv_read_key( fname,
                          BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_ADDR,
                          linebuf, BTIF_STORAGE_MAX_LINE_SZ);
    if (value != NULL)
    {
        if (strstr(value,bd_addr_lap) != NULL)
        return TRUE;
    }

    dev_name_str = BTM_SecReadDevName((remote_dev_addr->address));

    if (dev_name_str != NULL)
    {
        value = unv_read_key( fname,
                              BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_EXACTNAME,
                              linebuf, BTIF_STORAGE_MAX_LINE_SZ);
        if (value != NULL)
        {
            if (strstr(value,dev_name_str) != NULL)
                return TRUE;
        }

        value = unv_read_key( fname,
                              BTIF_STORAGE_KEY_AUTOPAIR_BLACKLIST_PARTIALNAME,
                              linebuf, BTIF_STORAGE_MAX_LINE_SZ);
        if (value != NULL)
        {
            token = strtok(value, BTIF_AUTO_PAIR_CONF_VALUE_SEPARATOR);
            while (token != NULL)
            {
                if (strstr(dev_name_str, token) != NULL)
                    return TRUE;

                token = strtok(NULL, BTIF_AUTO_PAIR_CONF_VALUE_SEPARATOR);
            }
        }
    }

    value = unv_read_key( fname,
                          BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR,
                          linebuf, BTIF_STORAGE_MAX_LINE_SZ);
    if (value != NULL)
    {
        if (strstr(value,bdstr) != NULL)
            return TRUE;
    }
   return FALSE;
}

/*******************************************************************************
**
** Function         btif_storage_add_device_to_autopair_blacklist
**
** Description      BTIF storage API - Add a remote device to the auto pairing blacklist
**
** Returns          BT_STATUS_SUCCESS if the device is successfully added to the auto pair blacklist
**                  BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_storage_add_device_to_autopair_blacklist(bt_bdaddr_t *remote_dev_addr)
{
    char *fname;
    char *value;
    int ret;
    bdstr_t bdstr;
    char linebuf[BTIF_STORAGE_MAX_LINE_SZ+20];
    char input_value [20];

    bd2str(remote_dev_addr, &bdstr);
    strncpy(input_value, (char*)bdstr, 20);
    strncat (input_value,BTIF_AUTO_PAIR_CONF_VALUE_SEPARATOR, 20);

    /* create filepath */
    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST);

    if (fname == NULL)
    {
        return BT_STATUS_FAIL;
    }

    value = unv_read_key( fname,
                          BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR,
                          linebuf, BTIF_STORAGE_MAX_LINE_SZ);
    if (value != NULL)
    {
        /* Append this address to the dynamic List of BD address  */
        strncat (linebuf, input_value, BTIF_STORAGE_MAX_LINE_SZ);
    }
    else
    {
        strncpy( linebuf,input_value, BTIF_STORAGE_MAX_LINE_SZ);
    }

    /* Write back the key value */
    ret = unv_write_key (fname, BTIF_STORAGE_KEY_AUTOPAIR_DYNAMIC_BLACKLIST_ADDR,( const char *)linebuf);

    return (ret == 0 ? BT_STATUS_SUCCESS:BT_STATUS_FAIL);
}

/*******************************************************************************
**
** Function         btif_storage_is_fixed_pin_zeros_keyboard
**
** Description      BTIF storage API - checks if this device has fixed PIN key device list
**
** Returns          TRUE   if the device is found in the fixed pin keyboard device list
**                  FALSE otherwise
**
*******************************************************************************/
BOOLEAN btif_storage_is_fixed_pin_zeros_keyboard(bt_bdaddr_t *remote_dev_addr)
{
    char *fname;
    char *value;
    int ret;
    bdstr_t bdstr;
    char bd_addr_lap[9];
    char *dev_name_str;
    uint8_t i = 0;
    char linebuf[BTIF_STORAGE_MAX_LINE_SZ];

    bd2str(remote_dev_addr, &bdstr);
    snprintf(bd_addr_lap, 9, "%s",  (char*)bdstr);

    for ( i =0; i <strlen(bd_addr_lap) ;i++)
    {
        bd_addr_lap[i] = toupper(bd_addr_lap[i]);
    }

    /* create filepath */
    fname = btif_in_make_filename(NULL, BTIF_STORAGE_PATH_AUTOPAIR_BLACKLIST);

    value = unv_read_key( fname,
                          BTIF_STORAGE_KEY_AUTOPAIR_FIXPIN_KBLIST,
                          linebuf, BTIF_STORAGE_MAX_LINE_SZ);

    if (value != NULL)
    {
        if (strstr(bd_addr_lap, value) != NULL)
            return TRUE;
    }
    return FALSE;
}