Blob: node.c

Blob id: 7f20e97ea2308a4b8a31ad1cfaa64f37c7fc6939

Size: 60.1 KB

   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
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
// SPDX-License-Identifier: LGPL-2.1-or-later
/*
 *
 *  BlueZ - Bluetooth protocol stack for Linux
 *
 *  Copyright (C) 2017-2020  Intel Corporation. All rights reserved.
 *
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#define _GNU_SOURCE
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

#include <ell/ell.h>

#include "mesh/mesh-defs.h"
#include "mesh/mesh.h"
#include "mesh/net.h"
#include "mesh/net-keys.h"
#include "mesh/appkey.h"
#include "mesh/mesh-config.h"
#include "mesh/provision.h"
#include "mesh/prov.h"
#include "mesh/keyring.h"
#include "mesh/model.h"
#include "mesh/cfgmod.h"
#include "mesh/remprv.h"
#include "mesh/prv-beacon.h"
#include "mesh/util.h"
#include "mesh/error.h"
#include "mesh/dbus.h"
#include "mesh/agent.h"
#include "mesh/manager.h"
#include "mesh/rpl.h"
#include "mesh/node.h"

#define MESH_NODE_PATH_PREFIX "/node"

/* Default values for a new locally created node */
#define DEFAULT_NEW_UNICAST 0x0001
#define DEFAULT_IV_INDEX 0x0000

/* Default element location: unknown */
#define DEFAULT_LOCATION 0x0000

enum request_type {
	REQUEST_TYPE_JOIN,
	REQUEST_TYPE_ATTACH,
	REQUEST_TYPE_CREATE,
	REQUEST_TYPE_IMPORT,
};

struct node_element {
	char *path;
	struct l_queue *models;
	uint16_t location;
	uint8_t idx;
};

struct node_composition {
	uint16_t cid;
	uint16_t pid;
	uint16_t vid;
	uint16_t crpl;
};

struct mesh_node {
	struct mesh_net *net;
	struct l_queue *elements;
	struct l_queue *pages;
	char *app_path;
	char *owner;
	char *obj_path;
	struct mesh_agent *agent;
	struct mesh_config *cfg;
	char *storage_dir;
	uint32_t disc_watch;
	uint32_t seq_number;
	bool busy;
	bool provisioner;
	uint16_t primary;
	struct node_composition comp;
	struct {
		uint16_t interval;
		uint8_t cnt;
		uint8_t mode;
	} relay;
	uint8_t uuid[16];
	uint8_t dev_key[16];
	uint8_t token[8];
	uint8_t num_ele;
	uint8_t ttl;
	uint8_t lpn;
	uint8_t proxy;
	uint8_t friend;
	uint8_t beacon;
	uint8_t mpb;
	uint8_t mpb_period;
};

struct node_import {
	uint8_t dev_key[16];
	uint8_t net_key[16];
	uint16_t net_idx;
	struct {
		bool ivu;
		bool kr;
	} flags;
	uint32_t iv_index;
	uint16_t unicast;
};

struct managed_obj_request {
	struct mesh_node *node;
	union {
		node_ready_func_t ready_cb;
		node_join_ready_func_t join_ready_cb;
	};
	struct l_dbus_message *pending_msg;
	enum request_type type;
	union {
		struct mesh_node *attach;
		struct node_import *import;
	};
};

struct send_options {
	bool segmented;
	uint16_t vendor_id;
};

static struct l_queue *nodes;

static bool match_device_uuid(const void *a, const void *b)
{
	const struct mesh_node *node = a;
	const uint8_t *uuid = b;

	return (memcmp(node->uuid, uuid, 16) == 0);
}

static bool match_token(const void *a, const void *b)
{
	const struct mesh_node *node = a;
	const uint64_t *token = b;
	const uint64_t tmp = l_get_be64(node->token);

	return *token == tmp;
}

static bool match_element_idx(const void *a, const void *b)
{
	const struct node_element *element = a;
	uint32_t index = L_PTR_TO_UINT(b);

	return (element->idx == index);
}

static int compare_element_idx(const void *a, const void *b, void *user_data)
{
	uint32_t a_idx = ((const struct node_element *)a)->idx;
	uint32_t b_idx = ((const struct node_element *)b)->idx;

	if (a_idx < b_idx)
		return -1;

	if (a_idx > b_idx)
		return 1;

	return 0;
}

static bool match_element_path(const void *a, const void *b)
{
	const struct node_element *element = a;
	const char *path = b;

	if (!element->path)
		return false;

	return (!strcmp(element->path, path));
}

struct mesh_node *node_find_by_uuid(uint8_t uuid[16])
{
	return l_queue_find(nodes, match_device_uuid, uuid);
}

struct mesh_node *node_find_by_token(uint64_t token)
{
	return l_queue_find(nodes, match_token, (void *) &token);
}

uint8_t *node_uuid_get(struct mesh_node *node)
{
	if (!node)
		return NULL;
	return node->uuid;
}

static void set_defaults(struct mesh_node *node)
{
	node->lpn = MESH_MODE_UNSUPPORTED;
	node->proxy = MESH_MODE_UNSUPPORTED;
	node->mpb = MESH_MODE_DISABLED;
	node->mpb_period = NET_MPB_REFRESH_DEFAULT;
	node->friend = (mesh_friendship_supported()) ? MESH_MODE_DISABLED :
							MESH_MODE_UNSUPPORTED;
	node->beacon = (mesh_beacon_enabled()) ? MESH_MODE_ENABLED :
							MESH_MODE_DISABLED;
	node->relay.mode = (mesh_relay_supported()) ? MESH_MODE_DISABLED :
							MESH_MODE_UNSUPPORTED;
	node->ttl = TTL_MASK;
	node->seq_number = DEFAULT_SEQUENCE_NUMBER;
}

static struct mesh_node *node_new(const uint8_t uuid[16])
{
	struct mesh_node *node;

	node = l_new(struct mesh_node, 1);
	node->net = mesh_net_new(node);
	node->elements = l_queue_new();
	node->pages = l_queue_new();
	memcpy(node->uuid, uuid, sizeof(node->uuid));
	set_defaults(node);

	return node;
}

static void free_element_path(void *a, void *b)
{
	struct node_element *element = a;

	l_free(element->path);
	element->path = NULL;
}

static void element_free(void *data)
{
	struct node_element *element = data;

	l_queue_destroy(element->models, mesh_model_free);
	l_free(element->path);
	l_free(element);
}

static void free_node_dbus_resources(struct mesh_node *node)
{
	if (!node)
		return;

	if (node->disc_watch) {
		l_dbus_remove_watch(dbus_get_bus(), node->disc_watch);
		node->disc_watch = 0;
	}

	l_queue_foreach(node->elements, free_element_path, NULL);
	l_free(node->owner);
	node->owner = NULL;
	l_free(node->app_path);
	node->app_path = NULL;

	if (node->obj_path) {
		l_dbus_object_remove_interface(dbus_get_bus(), node->obj_path,
							MESH_NODE_INTERFACE);

		l_dbus_object_remove_interface(dbus_get_bus(), node->obj_path,
						MESH_MANAGEMENT_INTERFACE);

		l_dbus_object_remove_interface(dbus_get_bus(), node->obj_path,
						L_DBUS_INTERFACE_PROPERTIES);

		l_free(node->obj_path);
		node->obj_path = NULL;
	}
}

static void free_node_resources(void *data)
{
	struct mesh_node *node = data;

	/* Unregister io callbacks */
	mesh_net_detach(node->net);


	/* In case of a provisioner, stop active scanning */
	if (node->provisioner)
		manager_scan_cancel(node);

	/* Free dynamic resources */
	free_node_dbus_resources(node);
	l_queue_destroy(node->elements, element_free);
	l_queue_destroy(node->pages, l_free);
	mesh_agent_remove(node->agent);
	mesh_config_release(node->cfg);
	mesh_net_free(node->net);
	l_free(node->storage_dir);
	l_free(node);
}

/*
 * This function is called to free resources and remove the
 * configuration files for the specified node.
 */
void node_remove(struct mesh_node *node)
{
	if (!node)
		return;

	l_queue_remove(nodes, node);

	mesh_config_destroy_nvm(node->cfg);

	free_node_resources(node);
}

static bool add_element_from_storage(struct mesh_node *node,
					struct mesh_config_element *db_ele)
{
	struct node_element *ele;

	ele = l_new(struct node_element, 1);
	if (!ele)
		return false;

	ele->idx = db_ele->index;
	ele->location = db_ele->location;
	ele->models = l_queue_new();
	l_queue_push_tail(node->elements, ele);

	if (!mesh_model_add_from_storage(node, ele->idx, ele->models,
							db_ele->models))
		return false;

	return true;
}

static bool add_elements_from_storage(struct mesh_node *node,
					struct mesh_config_node *db_node)
{
	const struct l_queue_entry *entry;
	struct node_element *ele;

	entry = l_queue_get_entries(db_node->elements);

	for (; entry; entry = entry->next)
		if (!add_element_from_storage(node, entry->data))
			return false;

	ele = l_queue_find(node->elements, match_element_idx,
						L_UINT_TO_PTR(PRIMARY_ELE_IDX));
	if (!ele)
		return false;

	/* Add configuration server model on the primary element */
	mesh_model_add(node, ele->models, CONFIG_SRV_MODEL, NULL);

	/* Add remote provisioning models on the primary element */
	mesh_model_add(node, ele->models, REM_PROV_SRV_MODEL, NULL);

	if (node->provisioner)
		mesh_model_add(node, ele->models, REM_PROV_CLI_MODEL, NULL);

	return true;
}

static void set_net_key(void *a, void *b)
{
	struct mesh_config_netkey *netkey = a;
	struct mesh_node *node = b;

	mesh_net_set_key(node->net, netkey->idx, netkey->key, netkey->new_key,
								netkey->phase);
}

static void set_appkey(void *a, void *b)
{
	struct mesh_config_appkey *appkey = a;
	struct mesh_node *node = b;

	appkey_key_init(node->net, appkey->net_idx, appkey->app_idx,
						appkey->key, appkey->new_key);
}

static bool init_storage_dir(struct mesh_node *node)
{
	char uuid[33];
	char dir_name[PATH_MAX];

	if (node->storage_dir)
		return true;

	if (!hex2str(node->uuid, 16, uuid, sizeof(uuid)))
		return false;

	snprintf(dir_name, PATH_MAX, "%s/%s", mesh_get_storage_dir(), uuid);

	if (strlen(dir_name) >= PATH_MAX)
		return false;

	create_dir(dir_name);

	node->storage_dir = l_strdup(dir_name);

	/* Initialize directory for storing RPL info */
	return rpl_init(node->storage_dir);
}

static void init_net_settings(struct mesh_node *node)
{
	struct mesh_net *net = node->net;

	mesh_net_set_proxy_mode(net, node->proxy == MESH_MODE_ENABLED);

	mesh_net_set_friend_mode(net, node->friend == MESH_MODE_ENABLED);

	mesh_net_set_relay_mode(net, node->relay.mode == MESH_MODE_ENABLED,
					node->relay.cnt, node->relay.interval);

	mesh_net_set_snb_mode(net, node->beacon == MESH_MODE_ENABLED);
	mesh_net_set_mpb_mode(net, node->mpb == MESH_MODE_ENABLED,
							node->mpb_period, true);
}

static bool init_from_storage(struct mesh_config_node *db_node,
			const uint8_t uuid[16], struct mesh_config *cfg,
			void *user_data)
{
	unsigned int num_ele;

	struct mesh_node *node = node_new(uuid);

	if (!nodes)
		nodes = l_queue_new();

	l_queue_push_tail(nodes, node);

	node->comp.cid = db_node->cid;
	node->comp.pid = db_node->pid;
	node->comp.vid = db_node->vid;
	node->comp.crpl = db_node->crpl;
	node->lpn = db_node->modes.lpn;

	node->proxy = db_node->modes.proxy;
	node->friend = db_node->modes.friend;
	node->relay.mode = db_node->modes.relay.state;
	node->relay.cnt = db_node->modes.relay.cnt;
	node->relay.interval = db_node->modes.relay.interval;
	node->beacon = db_node->modes.beacon;
	node->mpb = db_node->modes.mpb;
	node->mpb_period = db_node->modes.mpb_period;

	l_debug("relay %2.2x, proxy %2.2x, lpn %2.2x, friend %2.2x",
			node->relay.mode, node->proxy, node->lpn, node->friend);
	node->ttl = db_node->ttl;
	node->seq_number = db_node->seq_number;

	memcpy(node->dev_key, db_node->dev_key, 16);
	memcpy(node->token, db_node->token, 8);

	num_ele = l_queue_length(db_node->elements);
	if (num_ele > MAX_ELE_COUNT)
		goto fail;

	node->num_ele = num_ele;

	if (num_ele != 0 && !add_elements_from_storage(node, db_node))
		goto fail;

	node->primary = db_node->unicast;

	if (!db_node->netkeys)
		goto fail;

	if (!IS_UNASSIGNED(node->primary) &&
		!mesh_net_register_unicast(node->net, node->primary, num_ele))
		goto fail;

	mesh_net_set_iv_index(node->net, db_node->iv_index, db_node->iv_update);

	/* Initialize directory for storing keyring and RPL info */
	if (!init_storage_dir(node) || !mesh_net_load_rpl(node->net))
		goto fail;

	if (db_node->net_transmit)
		mesh_net_transmit_params_set(node->net,
					db_node->net_transmit->count,
					db_node->net_transmit->interval);

	l_queue_foreach(db_node->netkeys, set_net_key, node);

	l_queue_foreach(db_node->appkeys, set_appkey, node);

	while (l_queue_length(db_node->pages)) {
		struct mesh_config_comp_page *page;

		/* Move the composition pages to the node struct */
		page = l_queue_pop_head(db_node->pages);
		l_queue_push_tail(node->pages, page);
	}

	mesh_net_set_seq_num(node->net, node->seq_number);
	mesh_net_set_default_ttl(node->net, node->ttl);

	init_net_settings(node);

	/* Initialize configuration server model */
	cfgmod_server_init(node, PRIMARY_ELE_IDX);

	/* Initialize remote provisioning models */
	remote_prov_server_init(node, PRIMARY_ELE_IDX);
	remote_prov_client_init(node, PRIMARY_ELE_IDX);

	/* Initialize Private Beacon server model */
	prv_beacon_server_init(node, PRIMARY_ELE_IDX);

	node->cfg = cfg;

	return true;
fail:
	node_remove(node);
	return false;
}

static void cleanup_node(void *data)
{
	struct mesh_node *node = data;
	uint32_t seq_num = mesh_net_get_seq_num(node->net);

	/* Preserve the last used sequence number */
	mesh_config_write_seq_number(node->cfg, seq_num, false);

	free_node_resources(node);
}

/*
 * This function is called to free resources and write the current
 * sequence numbers to the configuration file for each known node.
 */
void node_cleanup_all(void)
{
	l_queue_destroy(nodes, cleanup_node);
	l_dbus_unregister_interface(dbus_get_bus(), MESH_NODE_INTERFACE);
	l_dbus_unregister_interface(dbus_get_bus(), MESH_MANAGEMENT_INTERFACE);
}

bool node_is_provisioner(struct mesh_node *node)
{
	return node->provisioner;
}

bool node_is_busy(struct mesh_node *node)
{
	return node->busy;
}

void node_app_key_delete(struct mesh_node *node, uint16_t net_idx,
							uint16_t app_idx)
{
	const struct l_queue_entry *entry;

	entry = l_queue_get_entries(node->elements);
	for (; entry; entry = entry->next) {
		struct node_element *ele = entry->data;

		mesh_model_app_key_delete(node, ele->idx, ele->models, app_idx);
	}
}

uint16_t node_get_primary(struct mesh_node *node)
{
	if (!node)
		return UNASSIGNED_ADDRESS;
	else
		return node->primary;
}

bool node_refresh(struct mesh_node *node, bool hard, void *prov_info)
{
	struct mesh_prov_node_info *info = prov_info;
	bool res = true;

	if (!node || !info)
		return false;

	if (!IS_UNICAST(info->unicast))
		return false;

	/* Changing Unicast addresses requires a hard node reset */
	if (!hard && info->unicast != node->primary)
		return false;

	/*
	 * Hard refresh results in immediate use of new Device Key.
	 * Soft refresh saves new device key as Candidate until we
	 * successfully receive new incoming message on that key.
	 */
	if (hard) {
		if (!mesh_config_write_device_key(node->cfg, info->device_key))
			return false;

		memcpy(node->dev_key, info->device_key, sizeof(node->dev_key));

	} else if (!mesh_config_write_candidate(node->cfg, info->device_key))
		return false;

	/* Replace Primary Unicast address if it has changed */
	if (node->primary != info->unicast) {
		res = mesh_config_write_unicast(node->cfg, info->unicast);
		if (res) {
			node->primary = info->unicast;
			node->num_ele = info->num_ele;
			mesh_net_register_unicast(node->net, node->primary,
								node->num_ele);
		}
	}

	/* Replace Page 0 with Page 128 if it exists */
	if (res) {
		if (node_replace_comp(node, 0, 128))
			return true;
	}

	return res;
}

const uint8_t *node_get_device_key(struct mesh_node *node)
{
	if (!node)
		return NULL;

	return node->dev_key;
}

bool node_get_device_key_candidate(struct mesh_node *node, uint8_t *key)
{
	if (!node)
		return false;

	return mesh_config_read_candidate(node->cfg, key);
}

void node_finalize_candidate(struct mesh_node *node)
{
	if (!node)
		return;

	if (mesh_config_read_candidate(node->cfg, node->dev_key))
		mesh_config_finalize_candidate(node->cfg);
}

void node_set_token(struct mesh_node *node, uint8_t token[8])
{
	memcpy(node->token, token, 8);
}

const uint8_t *node_get_token(struct mesh_node *node)
{
	if (!node)
		return NULL;
	else
		return node->token;
}

uint8_t node_get_num_elements(struct mesh_node *node)
{
	return node->num_ele;
}

struct l_queue *node_get_element_models(struct mesh_node *node, uint8_t ele_idx)
{
	struct node_element *ele;

	if (!node)
		return NULL;

	ele = l_queue_find(node->elements, match_element_idx,
							L_UINT_TO_PTR(ele_idx));
	if (!ele)
		return NULL;

	return ele->models;
}

uint8_t node_default_ttl_get(struct mesh_node *node)
{
	if (!node)
		return TTL_MASK;
	return node->ttl;
}

bool node_default_ttl_set(struct mesh_node *node, uint8_t ttl)
{
	bool res;

	if (!node)
		return false;

	res = mesh_config_write_ttl(node->cfg, ttl);

	if (res) {
		node->ttl = ttl;
		mesh_net_set_default_ttl(node->net, ttl);
	}

	return res;
}

bool node_set_sequence_number(struct mesh_node *node, uint32_t seq)
{
	if (!node)
		return false;

	node->seq_number = seq;

	return mesh_config_write_seq_number(node->cfg, node->seq_number, true);
}

uint32_t node_get_sequence_number(struct mesh_node *node)
{
	if (!node)
		return 0xffffffff;

	return node->seq_number;
}

int node_get_element_idx(struct mesh_node *node, uint16_t ele_addr)
{
	uint16_t addr;
	uint8_t num_ele;

	if (!node)
		return -1;

	num_ele = node_get_num_elements(node);
	if (!num_ele)
		return -2;

	addr = node_get_primary(node);

	if (ele_addr < addr || ele_addr >= addr + num_ele)
		return -3;
	else
		return ele_addr - addr;
}

uint16_t node_get_crpl(struct mesh_node *node)
{
	if (!node)
		return 0;

	return node->comp.crpl;
}

uint8_t node_relay_mode_get(struct mesh_node *node, uint8_t *count,
							uint16_t *interval)
{
	if (!node) {
		*count = 0;
		*interval = 0;
		return MESH_MODE_DISABLED;
	}

	*count = node->relay.cnt;
	*interval = node->relay.interval;
	return node->relay.mode;
}

uint8_t node_lpn_mode_get(struct mesh_node *node)
{
	if (!node)
		return MESH_MODE_DISABLED;

	return node->lpn;
}

bool node_relay_mode_set(struct mesh_node *node, bool enable, uint8_t cnt,
							uint16_t interval)
{
	bool res;

	if (!node || node->relay.mode == MESH_MODE_UNSUPPORTED)
		return false;

	res = mesh_config_write_relay_mode(node->cfg, enable, cnt, interval);

	if (res) {
		node->relay.mode = enable ? MESH_MODE_ENABLED :
							MESH_MODE_DISABLED;
		node->relay.cnt = cnt;
		node->relay.interval = interval;
		mesh_net_set_relay_mode(node->net, enable, cnt, interval);
	}

	return res;
}

bool node_proxy_mode_set(struct mesh_node *node, bool enable)
{
	bool res;
	uint8_t proxy;

	if (!node || node->proxy == MESH_MODE_UNSUPPORTED)
		return false;

	proxy = enable ? MESH_MODE_ENABLED : MESH_MODE_DISABLED;
	res = mesh_config_write_mode(node->cfg, "proxy", proxy);

	if (res) {
		node->proxy = proxy;
		mesh_net_set_proxy_mode(node->net, enable);
	}

	return res;
}

uint8_t node_proxy_mode_get(struct mesh_node *node)
{
	if (!node)
		return MESH_MODE_DISABLED;

	return node->proxy;
}

bool node_beacon_mode_set(struct mesh_node *node, bool enable)
{
	bool res;
	uint8_t beacon;

	if (!node)
		return false;

	beacon = enable ? MESH_MODE_ENABLED : MESH_MODE_DISABLED;
	res = mesh_config_write_mode(node->cfg, "beacon", beacon);

	if (res) {
		node->beacon = beacon;
		mesh_net_set_snb_mode(node->net, enable);
	}

	return res;
}

uint8_t node_beacon_mode_get(struct mesh_node *node)
{
	if (!node)
		return MESH_MODE_DISABLED;

	return node->beacon;
}

bool node_mpb_mode_set(struct mesh_node *node, bool enable, uint8_t period)
{
	bool res;
	uint8_t beacon;

	if (!node)
		return false;

	beacon = enable ? MESH_MODE_ENABLED : MESH_MODE_DISABLED;
	res = mesh_config_write_mpb(node->cfg, beacon, period);

	if (res) {
		node->mpb = beacon;
		node->mpb_period = period;
		mesh_net_set_mpb_mode(node->net, enable, period, false);
	}

	return res;
}

uint8_t node_mpb_mode_get(struct mesh_node *node, uint8_t *period)
{
	if (!node)
		return MESH_MODE_DISABLED;

	*period = node->mpb_period;

	return node->mpb;
}

bool node_friend_mode_set(struct mesh_node *node, bool enable)
{
	bool res;
	uint8_t friend;

	if (!node || node->friend == MESH_MODE_UNSUPPORTED)
		return false;

	friend = enable ? MESH_MODE_ENABLED : MESH_MODE_DISABLED;
	res = mesh_config_write_mode(node->cfg, "friend", friend);

	if (res) {
		node->friend = friend;
		mesh_net_set_friend_mode(node->net, enable);
	}

	return res;
}

uint8_t node_friend_mode_get(struct mesh_node *node)
{
	if (!node)
		return MESH_MODE_DISABLED;

	return node->friend;
}

static uint16_t node_generate_comp(struct mesh_node *node, uint8_t *buf,
								uint16_t sz)
{
	uint16_t n, features, num_ele = 0;
	const struct l_queue_entry *entry;

	n = 0;

	l_put_le16(node->comp.cid, buf + n);
	n += 2;
	l_put_le16(node->comp.pid, buf + n);
	n += 2;
	l_put_le16(node->comp.vid, buf + n);
	n += 2;
	l_put_le16(node->comp.crpl, buf + n);
	n += 2;

	features = 0;

	if (node->relay.mode != MESH_MODE_UNSUPPORTED)
		features |= FEATURE_RELAY;
	if (node->proxy != MESH_MODE_UNSUPPORTED)
		features |= FEATURE_PROXY;
	if (node->friend != MESH_MODE_UNSUPPORTED)
		features |= FEATURE_FRIEND;
	if (node->lpn != MESH_MODE_UNSUPPORTED)
		features |= FEATURE_LPN;

	l_put_le16(features, buf + n);
	n += 2;

	entry = l_queue_get_entries(node->elements);

	for (; entry; entry = entry->next) {
		struct node_element *ele = entry->data;

		if (ele->idx != num_ele)
			return 0;

		num_ele++;

		/* At least fit location and zeros for number of models */
		if ((n + 4) > sz)
			return n;

		l_put_le16(ele->location, buf + n);
		n += 2;

		n += mesh_model_generate_composition(ele->models, sz - n,
								buf + n);
	}

	if (!num_ele)
		return 0;

	return n;
}

static bool match_page(const void *a, const void *b)
{
	const struct mesh_config_comp_page *page = a;
	uint8_t page_num = L_PTR_TO_UINT(b);

	return page->page_num == page_num;
}

static void convert_node_to_storage(struct mesh_node *node,
					struct mesh_config_node *db_node)
{
	const struct l_queue_entry *entry;

	memset(db_node, 0, sizeof(struct mesh_config_node));

	db_node->cid = node->comp.cid;
	db_node->pid = node->comp.pid;
	db_node->vid = node->comp.vid;
	db_node->crpl = node->comp.crpl;
	db_node->modes.lpn = node->lpn;
	db_node->modes.proxy = node->proxy;

	db_node->modes.friend = node->friend;
	db_node->modes.relay.state = node->relay.mode;
	db_node->modes.relay.cnt = node->relay.cnt;
	db_node->modes.relay.interval = node->relay.interval;
	db_node->modes.beacon = node->beacon;
	db_node->modes.mpb = node->mpb;
	db_node->modes.mpb_period = node->mpb_period;

	db_node->ttl = node->ttl;
	db_node->seq_number = node->seq_number;

	db_node->elements = l_queue_new();

	entry = l_queue_get_entries(node->elements);

	for (; entry; entry = entry->next) {
		struct node_element *ele = entry->data;
		struct mesh_config_element *db_ele;

		db_ele = l_new(struct mesh_config_element, 1);

		db_ele->index = ele->idx;
		db_ele->location = ele->location;
		db_ele->models = l_queue_new();

		mesh_model_convert_to_storage(db_ele->models, ele->models);

		l_queue_push_tail(db_node->elements, db_ele);
	}

}

static void free_db_storage(struct mesh_config_node *db_node)
{
	const struct l_queue_entry *entry;

	/* Free temporarily allocated resources */
	entry = l_queue_get_entries(db_node->elements);
	for (; entry; entry = entry->next) {
		struct mesh_config_element *db_ele = entry->data;

		l_queue_destroy(db_ele->models, l_free);
	}

	l_queue_destroy(db_node->elements, l_free);
}

static bool create_node_config(struct mesh_node *node, const uint8_t uuid[16])
{
	struct mesh_config_node db_node;
	const struct l_queue_entry *entry;
	const char *storage_dir;

	convert_node_to_storage(node, &db_node);
	storage_dir = mesh_get_storage_dir();
	node->cfg = mesh_config_create(storage_dir, uuid, &db_node);

	if (node->cfg)
		init_storage_dir(node);

	/* Free temporarily allocated resources */
	entry = l_queue_get_entries(db_node.elements);

	for (; entry; entry = entry->next) {
		struct mesh_config_element *db_ele = entry->data;

		l_queue_destroy(db_ele->models, l_free);
	}

	l_queue_destroy(db_node.elements, l_free);

	return node->cfg != NULL;
}

static void node_del_comp(struct mesh_node *node, uint8_t page_num)
{
	struct mesh_config_comp_page *page;

	if (!node)
		return;

	page = l_queue_remove_if(node->pages, match_page,
						L_UINT_TO_PTR(page_num));

	l_free(page);

	mesh_config_comp_page_del(node->cfg, page_num);
}

static bool node_set_comp(struct mesh_node *node, uint8_t page_num,
					const uint8_t *data, uint16_t len)
{
	struct mesh_config_comp_page *page;

	if (len < MIN_COMP_SIZE)
		return false;

	page = l_queue_remove_if(node->pages, match_page,
						L_UINT_TO_PTR(page_num));

	l_free(page);

	page = l_malloc(sizeof(struct mesh_config_comp_page) + len);
	page->len = len;
	page->page_num = page_num;
	memcpy(page->data, data, len);
	l_queue_push_tail(node->pages, page);

	return mesh_config_comp_page_add(node->cfg, page_num, page->data, len);
}

const uint8_t *node_get_comp(struct mesh_node *node, uint8_t page_num,
								uint16_t *len)
{
	struct mesh_config_comp_page *page = NULL;

	if (node)
		page = l_queue_find(node->pages, match_page,
						L_UINT_TO_PTR(page_num));

	if (!page) {
		*len = 0;
		return NULL;
	}

	*len = page->len;
	return page->data;
}

bool node_replace_comp(struct mesh_node *node, uint8_t retire, uint8_t with)
{
	struct mesh_config_comp_page *old_page, *keep;
	bool status;

	if (!node)
		return false;

	keep = l_queue_find(node->pages, match_page, L_UINT_TO_PTR(with));

	if (!keep)
		return false;

	old_page = l_queue_remove_if(node->pages, match_page,
							L_UINT_TO_PTR(retire));

	l_free(old_page);
	keep->page_num = retire;
	status = mesh_config_comp_page_add(node->cfg, keep->page_num,
							keep->data, keep->len);

	if (with != retire)
		mesh_config_comp_page_del(node->cfg, with);

	return status;
}

static void attach_io(void *a, void *b)
{
	struct mesh_node *node = a;
	struct mesh_io *io = b;

	if (node->net)
		mesh_net_attach(node->net, io);
}

/* Register callbacks for all nodes io */
void node_attach_io_all(struct mesh_io *io)
{
	l_queue_foreach(nodes, attach_io, io);
}

/* Register node object with D-Bus */
static bool register_node_object(struct mesh_node *node)
{
	char uuid[33];

	if (!hex2str(node->uuid, sizeof(node->uuid), uuid, sizeof(uuid)))
		return false;

	node->obj_path = l_strdup_printf(BLUEZ_MESH_PATH MESH_NODE_PATH_PREFIX
								"%s", uuid);

	if (!l_dbus_object_add_interface(dbus_get_bus(), node->obj_path,
						MESH_NODE_INTERFACE, node))
		return false;

	if (!l_dbus_object_add_interface(dbus_get_bus(), node->obj_path,
					MESH_MANAGEMENT_INTERFACE, node))
		return false;

	if (!l_dbus_object_add_interface(dbus_get_bus(), node->obj_path,
					L_DBUS_INTERFACE_PROPERTIES, NULL))
		return false;

	return true;
}

static void app_disc_cb(struct l_dbus *bus, void *user_data)
{
	struct mesh_node *node = user_data;

	l_info("App %s disconnected (%u)", node->owner, node->disc_watch);

	node->disc_watch = 0;

	/* In case of a provisioner, stop active scanning */
	if (node->provisioner)
		manager_scan_cancel(node);

	free_node_dbus_resources(node);
}

static bool get_sig_models_from_properties(struct mesh_node *node,
					struct node_element *ele,
					struct l_dbus_message_iter *property)
{
	struct l_dbus_message_iter mods, var;
	uint16_t m_id;

	if (!ele->models)
		ele->models = l_queue_new();

	if (!l_dbus_message_iter_get_variant(property, "a(qa{sv})", &mods))
		return false;

	/* Bluetooth SIG defined models */
	while (l_dbus_message_iter_next_entry(&mods, &m_id, &var)) {
		uint32_t id = SET_ID(SIG_VENDOR, m_id);

		/*
		 * Allow Config Server & Private Beacon Models only on
		 * the primary element
		 */
		if (ele->idx != PRIMARY_ELE_IDX) {
			if (id == CONFIG_SRV_MODEL)
				return false;
			if (id == PRV_BEACON_SRV_MODEL)
				return false;
		}

		if (!mesh_model_add(node, ele->models, id, &var))
			return false;
	}

	return true;
}

static bool get_vendor_models_from_properties(struct mesh_node *node,
					struct node_element *ele,
					struct l_dbus_message_iter *property)
{
	struct l_dbus_message_iter mods, var;
	uint16_t m_id, v_id;

	if (!ele->models)
		ele->models = l_queue_new();

	if (!l_dbus_message_iter_get_variant(property, "a(qqa{sv})", &mods))
		return false;

	/* Vendor defined models */
	while (l_dbus_message_iter_next_entry(&mods, &v_id, &m_id, &var)) {
		uint32_t id = SET_ID(v_id, m_id);

		if (!mesh_model_add(node, ele->models, id, &var))
			return false;
	}

	return true;
}

static bool get_element_properties(struct mesh_node *node, const char *path,
					struct l_dbus_message_iter *properties)
{
	struct node_element *ele = l_new(struct node_element, 1);
	const char *key;
	struct l_dbus_message_iter var;
	bool idx = false;
	bool mods = false;
	bool vendor_mods = false;

	l_debug("path %s", path);

	ele->location = DEFAULT_LOCATION;

	while (l_dbus_message_iter_next_entry(properties, &key, &var)) {
		if (!strcmp(key, "Index")) {

			if (idx || !l_dbus_message_iter_get_variant(&var, "y",
								&ele->idx))
				goto fail;

			idx = true;

		} else if (!strcmp(key, "Models")) {

			if (mods)
				goto fail;

			if (!get_sig_models_from_properties(node, ele, &var))
				goto fail;

			mods = true;
		} else if (!strcmp(key, "VendorModels")) {

			if (vendor_mods)
				goto fail;

			if (!get_vendor_models_from_properties(node, ele, &var))
				goto fail;

			vendor_mods = true;

		} else if (!strcmp(key, "Location")) {
			if (!l_dbus_message_iter_get_variant(&var, "q",
							&ele->location))
				goto fail;
		}
	}

	/* Check for the presence of the required properties */
	if (!idx || !mods || !vendor_mods)
		goto fail;

	if (l_queue_find(node->elements, match_element_idx,
						L_UINT_TO_PTR(ele->idx)))
		goto fail;

	l_queue_insert(node->elements, ele, compare_element_idx, NULL);

	ele->path = l_strdup(path);

	/*
	 * Add configuration server model on the primary element.
	 * We allow the application not to specify the presence of
	 * the Configuration Server model, since it's implemented by the
	 * daemon. If the model is present in the application properties,
	 * the operation below will be a "no-op".
	 */
	if (ele->idx == PRIMARY_ELE_IDX) {
		mesh_model_add(node, ele->models, CONFIG_SRV_MODEL, NULL);
		mesh_model_add(node, ele->models, PRV_BEACON_SRV_MODEL, NULL);
		mesh_model_add(node, ele->models, REM_PROV_SRV_MODEL, NULL);
		if (node->provisioner)
			mesh_model_add(node, ele->models, REM_PROV_CLI_MODEL,
									NULL);
	}

	return true;
fail:
	l_free(ele);

	return false;
}

static bool get_app_properties(struct mesh_node *node, const char *path,
					struct l_dbus_message_iter *properties)
{
	const char *key;
	struct l_dbus_message_iter variant;
	bool cid = false;
	bool pid = false;
	bool vid = false;

	l_debug("path %s", path);

	node->comp.crpl = mesh_get_crpl();

	while (l_dbus_message_iter_next_entry(properties, &key, &variant)) {
		if (!cid && !strcmp(key, "CompanyID")) {
			if (!l_dbus_message_iter_get_variant(&variant, "q",
							&node->comp.cid))
				return false;
			cid = true;
			continue;
		}

		if (!pid && !strcmp(key, "ProductID")) {
			if (!l_dbus_message_iter_get_variant(&variant, "q",
							&node->comp.pid))
				return false;
			pid = true;
			continue;
		}

		if (!vid && !strcmp(key, "VersionID")) {
			if (!l_dbus_message_iter_get_variant(&variant, "q",
							&node->comp.vid))
				return false;
			vid = true;
			continue;
		}

		if (!strcmp(key, "CRPL")) {
			if (!l_dbus_message_iter_get_variant(&variant, "q",
							&node->comp.crpl))
				return false;
			continue;
		}
	}

	if (!cid || !pid || !vid)
		return false;

	return true;
}

static void save_pages(void *data, void *user_data)
{
	struct mesh_config_comp_page *page = data;
	struct mesh_node *node = user_data;

	mesh_config_comp_page_add(node->cfg, page->page_num, page->data,
								page->len);
}

static bool add_local_node(struct mesh_node *node, uint16_t unicast, bool kr,
				bool ivu, uint32_t iv_idx,
				const uint8_t dev_key[16],
				uint16_t net_key_idx, const uint8_t net_key[16])
{
	if (!nodes)
		nodes = l_queue_new();

	l_queue_push_tail(nodes, node);

	if (!mesh_config_write_iv_index(node->cfg, iv_idx, ivu))
		return false;

	mesh_net_set_iv_index(node->net, iv_idx, ivu);

	if (!mesh_config_write_unicast(node->cfg, unicast))
		return false;

	l_getrandom(node->token, sizeof(node->token));
	if (!mesh_config_write_token(node->cfg, node->token))
		return false;

	memcpy(node->dev_key, dev_key, 16);
	if (!mesh_config_write_device_key(node->cfg, dev_key))
		return false;

	node->primary = unicast;
	mesh_net_register_unicast(node->net, unicast, node->num_ele);

	if (mesh_net_add_key(node->net, net_key_idx, net_key) !=
							MESH_STATUS_SUCCESS)
		return false;

	if (kr) {
		/* Duplicate net key, if the key refresh is on */
		if (mesh_net_update_key(node->net, net_key_idx, net_key) !=
							MESH_STATUS_SUCCESS)
			return false;

		if (mesh_net_key_refresh_phase_set(node->net, net_key_idx,
				KEY_REFRESH_PHASE_TWO) != MESH_STATUS_SUCCESS)
			return false;
	}

	l_queue_foreach(node->pages, save_pages, node);

	init_net_settings(node);

	/* Initialize internal server models */
	cfgmod_server_init(node, PRIMARY_ELE_IDX);
	remote_prov_server_init(node, PRIMARY_ELE_IDX);
	remote_prov_client_init(node, PRIMARY_ELE_IDX);

	/* Initialize Private Beacon server model */
	prv_beacon_server_init(node, PRIMARY_ELE_IDX);

	node->busy = true;

	return true;
}

static void update_composition(struct mesh_node *node, struct mesh_node *attach)
{
	if (node->comp.cid != attach->comp.cid)
		mesh_config_update_company_id(attach->cfg, node->comp.cid);

	if (node->comp.pid != attach->comp.pid)
		mesh_config_update_product_id(attach->cfg, node->comp.pid);

	if (node->comp.vid != attach->comp.vid)
		mesh_config_update_version_id(attach->cfg, node->comp.vid);

	if (node->comp.crpl != attach->comp.crpl)
		mesh_config_update_crpl(attach->cfg, node->comp.crpl);

	attach->comp = node->comp;
}

static void update_model_options(struct mesh_node *node,
						struct mesh_node *attach)
{
	uint32_t len, i;
	struct node_element *ele, *ele_attach;

	len = l_queue_length(node->elements);

	for (i = 0; i < len; i++) {

		ele = l_queue_find(node->elements, match_element_idx,
							L_UINT_TO_PTR(i));
		ele_attach = l_queue_find(attach->elements, match_element_idx,
							L_UINT_TO_PTR(i));
		if (!ele || !ele_attach)
			continue;

		mesh_model_update_opts(node, ele->idx, ele_attach->models,
								ele->models);
	}
}

static bool check_req_node(struct managed_obj_request *req)
{
	struct mesh_node *node;
	const int offset = 8;
	uint16_t node_len, len;
	uint8_t comp[MAX_MSG_LEN - 2];
	const uint8_t *node_comp;

	if (req->type != REQUEST_TYPE_ATTACH) {
		node = req->node;

		if (!create_node_config(node, node->uuid))
			return false;
	} else
		node = req->attach;

	node_comp = node_get_comp(node, 0, &node_len);
	len = node_generate_comp(req->node, comp, sizeof(comp));

	/* If no page 0 exists, then current composition as valid */
	if (req->type != REQUEST_TYPE_ATTACH || !node_len)
		goto page_zero_valid;

	/*
	 * If composition has materially changed, save new composition
	 * in page 128 until next NPPI procedure. But we do allow
	 * for CID, PID, VID and/or CRPL to freely change without
	 * requiring a NPPI procedure.
	 */
	if (node_len != len || memcmp(&node_comp[offset], &comp[offset],
							node_len - offset))
		return node_set_comp(node, 128, comp, len);

page_zero_valid:
	/* If page 0 represents current App, ensure page 128 doesn't exist */
	node_del_comp(node, 128);

	if (len == node_len && !memcmp(node_comp, comp, len))
		return true;

	return node_set_comp(node, 0, comp, len);
}

static bool is_zero(const void *a, const void *b)
{
	const struct node_element *element = a;

	return !element->idx;
}

static bool attach_req_node(struct mesh_node *attach, struct mesh_node *node)
{
	const struct l_queue_entry *attach_entry;
	const struct l_queue_entry *node_entry;
	bool comp_changed = false;

	attach->obj_path = node->obj_path;
	node->obj_path = NULL;

	if (!register_node_object(attach)) {
		free_node_dbus_resources(attach);
		return false;
	}

	if (attach->num_ele != node->num_ele) {
		struct mesh_config_node db_node;
		struct node_element *old_ele, *new_ele;

		convert_node_to_storage(node, &db_node);

		/*
		 * If composition has materially changed, we need to discard
		 * everything we knew about elements in the old application,
		 * and start from what they are telling us now.
		 */
		old_ele = l_queue_remove_if(attach->elements, is_zero, NULL);
		new_ele = l_queue_remove_if(node->elements, is_zero, NULL);
		element_free(new_ele);

		l_queue_destroy(attach->elements, element_free);
		attach->elements = node->elements;
		attach->num_ele = node->num_ele;

		/* Restore primary elements */
		l_queue_push_head(attach->elements, old_ele);

		comp_changed = true;

		mesh_config_reset(attach->cfg, &db_node);
		free_db_storage(&db_node);
	}

	attach_entry = l_queue_get_entries(attach->elements);
	node_entry = l_queue_get_entries(node->elements);

	/*
	 * Update existing node with paths collected in temporary node,
	 * then remove the temporary.
	 */
	while (attach_entry && node_entry) {
		struct node_element *attach_ele = attach_entry->data;
		struct node_element *node_ele = node_entry->data;

		attach_ele->path = node_ele->path;
		node_ele->path = NULL;

		attach_entry = attach_entry->next;
		node_entry = node_entry->next;

		/* Only need the Primary element during Composition change */
		if (comp_changed)
			break;
	}

	mesh_agent_remove(attach->agent);
	attach->agent = node->agent;
	node->agent = NULL;

	attach->provisioner = node->provisioner;

	attach->app_path = node->app_path;
	node->app_path = NULL;

	attach->owner = node->owner;
	node->owner = NULL;

	update_composition(node, attach);

	update_model_options(node, attach);

	if (comp_changed)
		node->elements = NULL;

	node_remove(node);

	return true;
}

static void get_managed_objects_cb(struct l_dbus_message *msg, void *user_data)
{
	struct l_dbus_message_iter objects, interfaces;
	struct managed_obj_request *req = user_data;
	const char *path;
	struct mesh_node *node = req->node;
	struct node_import *import;
	bool have_app = false;
	unsigned int num_ele;
	struct keyring_net_key net_key;
	uint8_t dev_key[16];

	if (req->type == REQUEST_TYPE_ATTACH)
		req->attach->busy = false;

	if (!msg || l_dbus_message_is_error(msg)) {
		l_error("Failed to get app's dbus objects");
		goto fail;
	}

	if (!l_dbus_message_get_arguments(msg, "a{oa{sa{sv}}}", &objects)) {
		l_error("Failed to parse app's dbus objects");
		goto fail;
	}

	while (l_dbus_message_iter_next_entry(&objects, &path, &interfaces)) {
		struct l_dbus_message_iter properties;
		const char *interface;

		while (l_dbus_message_iter_next_entry(&interfaces, &interface,
								&properties)) {
			bool res;

			if (!strcmp(MESH_ELEMENT_INTERFACE, interface)) {
				res = get_element_properties(node, path,
								&properties);
				if (!res)
					goto fail;
			} else if (!strcmp(MESH_APPLICATION_INTERFACE,
								interface)) {
				if (have_app)
					goto fail;

				req->node->app_path = l_strdup(path);

				res = get_app_properties(node, path,
								&properties);
				if (!res)
					goto fail;

				have_app = true;

			} else if (!strcmp(MESH_PROVISION_AGENT_INTERFACE,
								interface)) {
				const char *sender;

				sender = l_dbus_message_get_sender(msg);
				node->agent = mesh_agent_create(path, sender,
								&properties);
				if (!node->agent)
					goto fail;

			} else if (!strcmp(MESH_PROVISIONER_INTERFACE,
								interface)) {
				node->provisioner = true;
			}
		}
	}

	if (!have_app) {
		l_error("Interface %s not found", MESH_APPLICATION_INTERFACE);
		goto fail;
	}

	if (l_queue_isempty(node->elements)) {
		l_error("Interface %s not found", MESH_ELEMENT_INTERFACE);
		goto fail;
	}

	if (!l_queue_find(node->elements, match_element_idx,
				L_UINT_TO_PTR(PRIMARY_ELE_IDX))) {

		l_debug("Primary element not detected");
		goto fail;
	}

	num_ele = l_queue_length(node->elements);

	if (num_ele > MAX_ELE_COUNT)
		goto fail;

	node->num_ele = num_ele;

	if (!check_req_node(req))
		goto fail;

	switch (req->type) {
	case REQUEST_TYPE_ATTACH:
		if (!attach_req_node(req->attach, node))
			goto fail;

		req->attach->disc_watch = l_dbus_add_disconnect_watch(
					dbus_get_bus(), req->attach->owner,
					app_disc_cb, req->attach, NULL);

		req->ready_cb(req->pending_msg, MESH_ERROR_NONE, req->attach);
		return;

	case REQUEST_TYPE_JOIN:
		if (!node->agent) {
			l_error("Interface %s not found",
						MESH_PROVISION_AGENT_INTERFACE);
			goto fail;
		}

		req->join_ready_cb(node, node->agent);

		return;

	case REQUEST_TYPE_IMPORT:
		import = req->import;
		if (!add_local_node(node, import->unicast, import->flags.kr,
					import->flags.ivu,
					import->iv_index, import->dev_key,
					import->net_idx, import->net_key))
			goto fail;

		req->ready_cb(req->pending_msg, MESH_ERROR_NONE, node);
		l_free(import);

		return;

	case REQUEST_TYPE_CREATE:
		/* Generate device and primary network keys */
		l_getrandom(dev_key, sizeof(dev_key));
		l_getrandom(net_key.old_key, sizeof(net_key.old_key));
		memcpy(net_key.new_key, net_key.old_key,
						sizeof(net_key.old_key));
		net_key.net_idx = PRIMARY_NET_IDX;
		net_key.phase = KEY_REFRESH_PHASE_NONE;

		if (!add_local_node(node, DEFAULT_NEW_UNICAST, false, false,
						DEFAULT_IV_INDEX, dev_key,
						PRIMARY_NET_IDX,
						net_key.old_key))
			goto fail;

		if (!keyring_put_remote_dev_key(node, DEFAULT_NEW_UNICAST,
						node->num_ele, dev_key))
			goto fail;

		if (!keyring_put_net_key(node, PRIMARY_NET_IDX, &net_key))
			goto fail;

		req->ready_cb(req->pending_msg, MESH_ERROR_NONE, node);
		return;

	default:
		goto fail;
	}

fail:
	/* Handle failed requests */
	node_remove(node);

	if (req->type == REQUEST_TYPE_JOIN)
		req->join_ready_cb(NULL, NULL);
	else
		req->ready_cb(req->pending_msg, MESH_ERROR_FAILED, NULL);

	if (req->type == REQUEST_TYPE_IMPORT)
		l_free(req->import);
}

static void send_managed_objects_request(const char *destination,
						const char *path,
						struct managed_obj_request *req)
{
	struct l_dbus_message *msg;

	msg = l_dbus_message_new_method_call(dbus_get_bus(), destination, path,
						L_DBUS_INTERFACE_OBJECT_MANAGER,
						"GetManagedObjects");
	l_dbus_message_set_arguments(msg, "");
	dbus_send_with_timeout(dbus_get_bus(), msg, get_managed_objects_cb,
					req, l_free, DEFAULT_DBUS_TIMEOUT);
}

/* Establish relationship between application and mesh node */
void node_attach(const char *app_root, const char *sender, uint64_t token,
					node_ready_func_t cb, void *user_data)
{
	struct managed_obj_request *req;
	struct mesh_node *node;

	node = l_queue_find(nodes, match_token, (void *) &token);
	if (!node) {
		cb(user_data, MESH_ERROR_NOT_FOUND, NULL);
		return;
	}

	/* Check if there is a pending request associated with this node */
	if (node->busy) {
		cb(user_data, MESH_ERROR_BUSY, NULL);
		return;
	}

	/* Check if the node is already in use */
	if (node->owner) {
		l_warn("The node is already in use");
		cb(user_data, MESH_ERROR_ALREADY_EXISTS, NULL);
		return;
	}

	req = l_new(struct managed_obj_request, 1);

	/*
	 * Create a temporary node to collect composition data from attaching
	 * application. Existing node is passed in req->attach.
	 */
	req->node = node_new(node->uuid);
	req->node->owner = l_strdup(sender);
	req->ready_cb = cb;
	req->pending_msg = user_data;
	req->attach = node;
	req->type = REQUEST_TYPE_ATTACH;

	node->busy = true;

	send_managed_objects_request(sender, app_root, req);
}

/* Create a temporary pre-provisioned node */
void node_join(const char *app_root, const char *sender, const uint8_t *uuid,
						node_join_ready_func_t cb)
{
	struct managed_obj_request *req;

	l_debug("");

	req = l_new(struct managed_obj_request, 1);
	req->node = node_new(uuid);
	req->join_ready_cb = cb;
	req->type = REQUEST_TYPE_JOIN;

	send_managed_objects_request(sender, app_root, req);
}

void node_import(const char *app_root, const char *sender, const uint8_t *uuid,
			const uint8_t dev_key[16], const uint8_t net_key[16],
			uint16_t net_idx, bool kr, bool ivu,
			uint32_t iv_index, uint16_t unicast,
			node_ready_func_t cb, void *user_data)
{
	struct managed_obj_request *req;

	l_debug("");

	req = l_new(struct managed_obj_request, 1);

	req->node = node_new(uuid);
	req->ready_cb = cb;
	req->pending_msg = user_data;

	req->import = l_new(struct node_import, 1);
	memcpy(req->import->dev_key, dev_key, 16);
	memcpy(req->import->net_key, net_key, 16);
	req->import->net_idx = net_idx;
	req->import->flags.kr = kr;
	req->import->flags.ivu = ivu;
	req->import->iv_index = iv_index;
	req->import->unicast = unicast;

	req->type = REQUEST_TYPE_IMPORT;

	send_managed_objects_request(sender, app_root, req);
}

void node_create(const char *app_root, const char *sender, const uint8_t *uuid,
					node_ready_func_t cb, void *user_data)
{
	struct managed_obj_request *req;

	l_debug("");

	req = l_new(struct managed_obj_request, 1);
	req->node = node_new(uuid);
	req->ready_cb = cb;
	req->pending_msg = user_data;
	req->type = REQUEST_TYPE_CREATE;

	send_managed_objects_request(sender, app_root, req);
}

static void build_element_config(void *a, void *b)
{
	struct node_element *ele = a;
	struct l_dbus_message_builder *builder = b;

	l_debug("Element %u", ele->idx);

	l_dbus_message_builder_enter_struct(builder, "ya(qa{sv})");

	/* Element index */
	l_dbus_message_builder_append_basic(builder, 'y', &ele->idx);

	l_dbus_message_builder_enter_array(builder, "(qa{sv})");

	/* Iterate over models */
	l_queue_foreach(ele->models, mesh_model_build_config, builder);

	l_dbus_message_builder_leave_array(builder);

	l_dbus_message_builder_leave_struct(builder);
}

void node_build_attach_reply(struct mesh_node *node,
						struct l_dbus_message *reply)
{
	struct l_dbus_message_builder *builder;

	builder = l_dbus_message_builder_new(reply);

	/* Node object path */
	l_dbus_message_builder_append_basic(builder, 'o', node->obj_path);

	/* Array of element configurations "a*/
	l_dbus_message_builder_enter_array(builder, "(ya(qa{sv}))");
	l_queue_foreach(node->elements, build_element_config, builder);
	l_dbus_message_builder_leave_array(builder);
	l_dbus_message_builder_finalize(builder);
	l_dbus_message_builder_destroy(builder);
}

static bool parse_send_options(struct l_dbus_message_iter *itr,
						struct send_options *opts)
{
	const char *key;
	struct l_dbus_message_iter var;

	opts->segmented = false;
	opts->vendor_id = SIG_VENDOR;

	while (l_dbus_message_iter_next_entry(itr, &key, &var)) {
		if (!strcmp(key, "ForceSegmented")) {
			if (!l_dbus_message_iter_get_variant(&var, "b",
							&opts->segmented))
				return false;
		}

		if (!strcmp(key, "Vendor")) {
			if (!l_dbus_message_iter_get_variant(&var, "q",
							&opts->vendor_id))
				return false;
		}
	}

	return true;
}

static struct l_dbus_message *send_call(struct l_dbus *dbus,
						struct l_dbus_message *msg,
						void *user_data)
{
	struct mesh_node *node = user_data;
	const char *sender, *ele_path;
	struct l_dbus_message_iter dict, iter_data;
	struct send_options opts;
	struct node_element *ele;
	uint16_t dst, app_idx, net_idx, src;
	uint8_t *data;
	uint32_t len;

	l_debug("Send");

	sender = l_dbus_message_get_sender(msg);

	if (strcmp(sender, node->owner))
		return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);

	if (!l_dbus_message_get_arguments(msg, "oqqa{sv}ay", &ele_path, &dst,
						&app_idx, &dict, &iter_data))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	ele = l_queue_find(node->elements, match_element_path, ele_path);
	if (!ele)
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
							"Element not found");

	if (!parse_send_options(&dict, &opts))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	src = node_get_primary(node) + ele->idx;

	if (!l_dbus_message_iter_get_fixed_array(&iter_data, &data, &len) ||
					!len || len > MAX_MSG_LEN)
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
							"Incorrect data");

	if (app_idx & ~APP_IDX_MASK)
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
						"Invalid key index");

	net_idx = appkey_net_idx(node_get_net(node), app_idx);
	if (net_idx == NET_IDX_INVALID)
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
							"Key not found");

	if (!mesh_model_send(node, src, dst, app_idx, net_idx, DEFAULT_TTL,
						opts.segmented, len, data))
		return dbus_error(msg, MESH_ERROR_FAILED, NULL);

	return l_dbus_message_new_method_return(msg);
}

static struct l_dbus_message *dev_key_send_call(struct l_dbus *dbus,
						struct l_dbus_message *msg,
						void *user_data)
{
	struct mesh_node *node = user_data;
	const char *sender, *ele_path;
	struct l_dbus_message_iter iter_data, dict;
	struct send_options opts;
	struct node_element *ele;
	uint16_t dst, app_idx, net_idx, src;
	bool remote;
	uint8_t *data;
	uint32_t len;

	l_debug("DevKeySend");

	sender = l_dbus_message_get_sender(msg);

	if (strcmp(sender, node->owner))
		return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);

	if (!l_dbus_message_get_arguments(msg, "oqbqa{sv}ay", &ele_path, &dst,
					&remote, &net_idx, &dict, &iter_data))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	/* Loopbacks to local servers must use *remote* addressing */
	if (!remote && mesh_net_is_local_address(node->net, dst, 1))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	ele = l_queue_find(node->elements, match_element_path, ele_path);
	if (!ele)
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
							"Element not found");

	if (!parse_send_options(&dict, &opts))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	src = node_get_primary(node) + ele->idx;

	if (!l_dbus_message_iter_get_fixed_array(&iter_data, &data, &len) ||
						!len || len > MAX_MSG_LEN)
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
							"Incorrect data");

	app_idx = remote ? APP_IDX_DEV_REMOTE : APP_IDX_DEV_LOCAL;
	if (!mesh_model_send(node, src, dst, app_idx, net_idx, DEFAULT_TTL,
						opts.segmented, len, data))
		return dbus_error(msg, MESH_ERROR_NOT_FOUND, NULL);

	return l_dbus_message_new_method_return(msg);
}

static struct l_dbus_message *add_netkey_call(struct l_dbus *dbus,
						struct l_dbus_message *msg,
						void *user_data)
{
	struct mesh_node *node = user_data;
	const char *sender, *ele_path;
	struct node_element *ele;
	uint16_t dst, sub_idx, net_idx, src;
	bool update;
	struct keyring_net_key key;
	uint8_t data[20];

	l_debug("AddNetKey");

	sender = l_dbus_message_get_sender(msg);

	if (strcmp(sender, node->owner))
		return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);

	if (!l_dbus_message_get_arguments(msg, "oqqqb", &ele_path, &dst,
						&sub_idx, &net_idx, &update))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	ele = l_queue_find(node->elements, match_element_path, ele_path);
	if (!ele)
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
							"Element not found");

	src = node_get_primary(node) + ele->idx;

	if (!keyring_get_net_key(node, sub_idx, &key))
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
							"NetKey not found");

	if (!update) {
		l_put_be16(OP_NETKEY_ADD, data);

		if (key.phase != KEY_REFRESH_PHASE_TWO)
			memcpy(data + 4, key.old_key, 16);
		else
			memcpy(data + 4, key.new_key, 16);
	} else {
		if (key.phase != KEY_REFRESH_PHASE_ONE)
			return dbus_error(msg, MESH_ERROR_FAILED,
							"Cannot update");
		l_put_be16(OP_NETKEY_UPDATE, data);
		memcpy(data + 4, key.new_key, 16);
	}

	l_put_le16(sub_idx, &data[2]);

	if (!mesh_model_send(node, src, dst, APP_IDX_DEV_REMOTE, net_idx,
						DEFAULT_TTL, false, 20, data))
		return dbus_error(msg, MESH_ERROR_NOT_FOUND, NULL);

	return l_dbus_message_new_method_return(msg);
}

static struct l_dbus_message *add_appkey_call(struct l_dbus *dbus,
						struct l_dbus_message *msg,
						void *user_data)
{
	struct mesh_node *node = user_data;
	const char *sender, *ele_path;
	struct node_element *ele;
	uint16_t dst, app_idx, net_idx, src;
	bool update;
	struct keyring_net_key net_key;
	struct keyring_app_key app_key;
	uint8_t data[20];

	l_debug("AddAppKey");

	sender = l_dbus_message_get_sender(msg);

	if (strcmp(sender, node->owner))
		return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);

	if (!l_dbus_message_get_arguments(msg, "oqqqb", &ele_path, &dst,
						&app_idx, &net_idx, &update))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	ele = l_queue_find(node->elements, match_element_path, ele_path);
	if (!ele)
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
							"Element not found");

	src = node_get_primary(node) + ele->idx;

	if (!keyring_get_app_key(node, app_idx, &app_key))
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
							"AppKey not found");

	if (!keyring_get_net_key(node, app_key.net_idx, &net_key)) {
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
						"Bound NetKey not found");
	}

	if (!update) {
		data[0] = OP_APPKEY_ADD;
		if (net_key.phase != KEY_REFRESH_PHASE_TWO)
			memcpy(data + 4, app_key.old_key, 16);
		else
			memcpy(data + 4, app_key.new_key, 16);
	} else {
		if (net_key.phase != KEY_REFRESH_PHASE_ONE)
			return dbus_error(msg, MESH_ERROR_FAILED,
							"Cannot update");
		data[0] = OP_APPKEY_UPDATE;
		memcpy(data + 4, app_key.new_key, 16);
	}

	/* Pack bound NetKey and AppKey into 3 octets */
	data[1] = app_key.net_idx;
	data[2] = ((app_key.net_idx >> 8) & 0xf) | ((app_idx << 4) & 0xf0);
	data[3] = app_idx >> 4;

	if (!mesh_model_send(node, src, dst, APP_IDX_DEV_REMOTE, net_idx,
						DEFAULT_TTL, false, 20, data))
		return dbus_error(msg, MESH_ERROR_NOT_FOUND, NULL);

	return l_dbus_message_new_method_return(msg);
}

static struct l_dbus_message *publish_call(struct l_dbus *dbus,
						struct l_dbus_message *msg,
						void *user_data)
{
	struct mesh_node *node = user_data;
	const char *sender, *ele_path;
	struct l_dbus_message_iter iter_data, dict;
	uint16_t mod_id, src;
	struct send_options opts;
	struct node_element *ele;
	uint8_t *data;
	uint32_t len, id;
	int result;

	l_debug("Publish");

	sender = l_dbus_message_get_sender(msg);

	if (strcmp(sender, node->owner))
		return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);

	if (!l_dbus_message_get_arguments(msg, "oqa{sv}ay", &ele_path, &mod_id,
							&dict, &iter_data))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	ele = l_queue_find(node->elements, match_element_path, ele_path);
	if (!ele)
		return dbus_error(msg, MESH_ERROR_NOT_FOUND,
							"Element not found");

	if (!parse_send_options(&dict, &opts))
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);

	src = node_get_primary(node) + ele->idx;

	if (!l_dbus_message_iter_get_fixed_array(&iter_data, &data, &len) ||
					!len || len > MAX_MSG_LEN)
		return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
							"Incorrect data");

	id = SET_ID(opts.vendor_id, mod_id);

	result = mesh_model_publish(node, id, src, opts.segmented, len, data);

	if (result != MESH_ERROR_NONE)
		return dbus_error(msg, result, NULL);

	return l_dbus_message_new_method_return(msg);
}

static bool features_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct mesh_node *node = user_data;
	uint8_t friend = node_friend_mode_get(node);
	uint8_t lpn = node_lpn_mode_get(node);
	uint8_t proxy = node_proxy_mode_get(node);
	uint8_t count;
	uint16_t interval;
	uint8_t relay = node_relay_mode_get(node, &count, &interval);

	l_dbus_message_builder_enter_array(builder, "{sv}");

	if (friend != MESH_MODE_UNSUPPORTED)
		dbus_append_dict_entry_basic(builder, "Friend", "b", &friend);

	if (lpn != MESH_MODE_UNSUPPORTED)
		dbus_append_dict_entry_basic(builder, "LowPower", "b", &lpn);

	if (proxy != MESH_MODE_UNSUPPORTED)
		dbus_append_dict_entry_basic(builder, "Proxy", "b", &proxy);

	if (relay != MESH_MODE_UNSUPPORTED)
		dbus_append_dict_entry_basic(builder, "Relay", "b", &relay);

	l_dbus_message_builder_leave_array(builder);

	return true;
}

static bool beacon_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct mesh_node *node = user_data;
	bool beacon_mode = node_beacon_mode_get(node) == MESH_MODE_ENABLED;

	l_dbus_message_builder_append_basic(builder, 'b', &beacon_mode);

	return true;
}

static bool ivupdate_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct mesh_node *node = user_data;
	struct mesh_net *net = node_get_net(node);
	uint8_t flags;
	uint32_t iv_index;
	bool ivu;

	mesh_net_get_snb_state(net, &flags, &iv_index);

	ivu = flags & IV_INDEX_UPDATE;

	l_dbus_message_builder_append_basic(builder, 'b', &ivu);

	return true;
}

static bool ivindex_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct mesh_node *node = user_data;
	struct mesh_net *net = node_get_net(node);
	uint8_t flags;
	uint32_t iv_index;

	mesh_net_get_snb_state(net, &flags, &iv_index);

	l_dbus_message_builder_append_basic(builder, 'u', &iv_index);

	return true;
}

static bool seq_num_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
				struct l_dbus_message_builder *builder,
				void *user_data)
{
	struct mesh_node *node = user_data;
	struct mesh_net *net = node_get_net(node);
	uint32_t seq_nr = mesh_net_get_seq_num(net);

	l_dbus_message_builder_append_basic(builder, 'u', &seq_nr);

	return true;
}

static bool lastheard_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct mesh_node *node = user_data;
	struct mesh_net *net = node_get_net(node);
	struct timeval now;
	uint32_t last_heard;

	gettimeofday(&now, NULL);

	last_heard = now.tv_sec - mesh_net_get_instant(net);

	l_dbus_message_builder_append_basic(builder, 'u', &last_heard);

	return true;

}

static bool addresses_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct mesh_node *node = user_data;
	const struct l_queue_entry *entry;

	l_dbus_message_builder_enter_array(builder, "q");

	entry = l_queue_get_entries(node->elements);
	for (; entry; entry = entry->next) {
		const struct node_element *ele = entry->data;
		uint16_t address = node->primary + ele->idx;

		l_dbus_message_builder_append_basic(builder, 'q', &address);
	}

	l_dbus_message_builder_leave_array(builder);

	return true;
}

static void setup_node_interface(struct l_dbus_interface *iface)
{
	l_dbus_interface_method(iface, "Send", 0, send_call, "", "oqqa{sv}ay",
						"element_path", "destination",
						"key_index", "options", "data");
	l_dbus_interface_method(iface, "DevKeySend", 0, dev_key_send_call, "",
						"oqbqa{sv}ay", "element_path",
						"destination", "remote",
						"net_index", "options", "data");
	l_dbus_interface_method(iface, "AddNetKey", 0, add_netkey_call, "",
					"oqqqb", "element_path", "destination",
					"subnet_index", "net_index", "update");
	l_dbus_interface_method(iface, "AddAppKey", 0, add_appkey_call, "",
					"oqqqb", "element_path", "destination",
					"app_index", "net_index", "update");
	l_dbus_interface_method(iface, "Publish", 0, publish_call, "",
					"oqa{sv}ay", "element_path", "model_id",
							"options", "data");
	l_dbus_interface_property(iface, "Features", 0, "a{sv}",
							features_getter, NULL);
	l_dbus_interface_property(iface, "Beacon", 0, "b", beacon_getter, NULL);
	l_dbus_interface_property(iface, "IvUpdate", 0, "b", ivupdate_getter,
									NULL);
	l_dbus_interface_property(iface, "IvIndex", 0, "u", ivindex_getter,
									NULL);
	l_dbus_interface_property(iface, "SequenceNumber", 0, "u",
							seq_num_getter, NULL);
	l_dbus_interface_property(iface, "SecondsSinceLastHeard", 0, "u",
					lastheard_getter, NULL);
	l_dbus_interface_property(iface, "Addresses", 0, "aq", addresses_getter,
									NULL);
}

void node_property_changed(struct mesh_node *node, const char *property)
{
	struct l_dbus *bus = dbus_get_bus();

	if (bus && node->obj_path)
		l_dbus_property_changed(dbus_get_bus(), node->obj_path,
						MESH_NODE_INTERFACE, property);
}

bool node_dbus_init(struct l_dbus *bus)
{
	if (!l_dbus_register_interface(bus, MESH_NODE_INTERFACE,
						setup_node_interface,
						NULL, false)) {
		l_info("Unable to register %s interface", MESH_NODE_INTERFACE);
		return false;
	}

	return true;
}

const char *node_get_owner(struct mesh_node *node)
{
	return node->owner;
}

const char *node_get_element_path(struct mesh_node *node, uint8_t ele_idx)
{
	struct node_element *ele;

	ele = l_queue_find(node->elements, match_element_idx,
							L_UINT_TO_PTR(ele_idx));

	if (!ele)
		return NULL;

	return ele->path;
}

bool node_add_pending_local(struct mesh_node *node,
					const struct mesh_prov_node_info *info)
{
	bool kr = !!(info->flags & PROV_FLAG_KR);
	bool ivu = !!(info->flags & PROV_FLAG_IVU);

	return add_local_node(node, info->unicast, kr, ivu, info->iv_index,
			info->device_key, info->net_index, info->net_key);
}

struct mesh_config *node_config_get(struct mesh_node *node)
{
	return node->cfg;
}

const char *node_get_storage_dir(struct mesh_node *node)
{
	return node->storage_dir;
}

const char *node_get_app_path(struct mesh_node *node)
{
	if (!node)
		return NULL;

	return node->app_path;
}

struct mesh_net *node_get_net(struct mesh_node *node)
{
	return node->net;
}

struct mesh_agent *node_get_agent(struct mesh_node *node)
{
	return node->agent;
}

bool node_load_from_storage(const char *storage_dir)
{
	return mesh_config_load_nodes(storage_dir, init_from_storage, NULL);
}

/*
 * This is called for a new node that:
 *         - has been created as a result of successful completion of Join()
 *           or Create() or Import() methods
 *     and
 *         - has been confirmed via successful token delivery to the application
 *
 * After a node has been created, the information gathered during initial
 * GetManagedObjects() call is cleared. The subsequent call to Attach() would
 * verify node's integrity and re-initialize node's D-Bus resources.
 */
void node_finalize_new_node(struct mesh_node *node, struct mesh_io *io)
{
	if (!node)
		return;

	free_node_dbus_resources(node);
	mesh_agent_remove(node->agent);
	node->agent = NULL;

	node->busy = false;

	/* Register callback for the node's io */
	attach_io(node, io);
}