f00a87776d1c1fd74522990ac964377772cfb614
[platform/upstream/bluez.git] / mesh / node.c
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3  *
4  *  BlueZ - Bluetooth protocol stack for Linux
5  *
6  *  Copyright (C) 2017-2020  Intel Corporation. All rights reserved.
7  *
8  *
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #ifndef TIZEN_FEATURE_BLUEZ_MODIFY
16 #define _GNU_SOURCE
17 #endif
18 #include <dirent.h>
19 #include <stdio.h>
20 #include <sys/time.h>
21
22 #include <ell/ell.h>
23
24 #include "mesh/mesh-defs.h"
25 #include "mesh/mesh.h"
26 #include "mesh/net.h"
27 #include "mesh/net-keys.h"
28 #include "mesh/appkey.h"
29 #include "mesh/mesh-config.h"
30 #include "mesh/provision.h"
31 #include "mesh/keyring.h"
32 #include "mesh/model.h"
33 #include "mesh/cfgmod.h"
34 #include "mesh/util.h"
35 #include "mesh/error.h"
36 #include "mesh/dbus.h"
37 #include "mesh/agent.h"
38 #include "mesh/manager.h"
39 #include "mesh/rpl.h"
40 #include "mesh/node.h"
41
42 #define MESH_NODE_PATH_PREFIX "/node"
43
44 /* Default values for a new locally created node */
45 #define DEFAULT_NEW_UNICAST 0x0001
46 #define DEFAULT_IV_INDEX 0x0000
47
48 /* Default element location: unknown */
49 #define DEFAULT_LOCATION 0x0000
50
51 enum request_type {
52         REQUEST_TYPE_JOIN,
53         REQUEST_TYPE_ATTACH,
54         REQUEST_TYPE_CREATE,
55         REQUEST_TYPE_IMPORT,
56 };
57
58 struct node_element {
59         char *path;
60         struct l_queue *models;
61         uint16_t location;
62         uint8_t idx;
63 };
64
65 struct node_composition {
66         uint16_t cid;
67         uint16_t pid;
68         uint16_t vid;
69         uint16_t crpl;
70 };
71
72 struct mesh_node {
73         struct mesh_net *net;
74         struct l_queue *elements;
75         struct l_queue *pages;
76         char *app_path;
77         char *owner;
78         char *obj_path;
79         struct mesh_agent *agent;
80         struct mesh_config *cfg;
81         char *storage_dir;
82         uint32_t disc_watch;
83         uint32_t seq_number;
84         bool busy;
85         bool provisioner;
86         uint16_t primary;
87         struct node_composition comp;
88         struct {
89                 uint16_t interval;
90                 uint8_t cnt;
91                 uint8_t mode;
92         } relay;
93         uint8_t uuid[16];
94         uint8_t dev_key[16];
95         uint8_t token[8];
96         uint8_t num_ele;
97         uint8_t ttl;
98         uint8_t lpn;
99         uint8_t proxy;
100         uint8_t friend;
101         uint8_t beacon;
102 };
103
104 struct node_import {
105         uint8_t dev_key[16];
106         uint8_t net_key[16];
107         uint16_t net_idx;
108         struct {
109                 bool ivu;
110                 bool kr;
111         } flags;
112         uint32_t iv_index;
113         uint16_t unicast;
114 };
115
116 struct managed_obj_request {
117         struct mesh_node *node;
118         union {
119                 node_ready_func_t ready_cb;
120                 node_join_ready_func_t join_ready_cb;
121         };
122         struct l_dbus_message *pending_msg;
123         enum request_type type;
124         union {
125                 struct mesh_node *attach;
126                 struct node_import *import;
127         };
128 };
129
130 struct send_options {
131         bool segmented;
132         uint16_t vendor_id;
133 };
134
135 static struct l_queue *nodes;
136
137 static bool match_device_uuid(const void *a, const void *b)
138 {
139         const struct mesh_node *node = a;
140         const uint8_t *uuid = b;
141
142         return (memcmp(node->uuid, uuid, 16) == 0);
143 }
144
145 static bool match_token(const void *a, const void *b)
146 {
147         const struct mesh_node *node = a;
148         const uint64_t *token = b;
149         const uint64_t tmp = l_get_be64(node->token);
150
151         return *token == tmp;
152 }
153
154 static bool match_element_idx(const void *a, const void *b)
155 {
156         const struct node_element *element = a;
157         uint32_t index = L_PTR_TO_UINT(b);
158
159         return (element->idx == index);
160 }
161
162 static int compare_element_idx(const void *a, const void *b, void *user_data)
163 {
164         uint32_t a_idx = ((const struct node_element *)a)->idx;
165         uint32_t b_idx = ((const struct node_element *)b)->idx;
166
167         if (a_idx < b_idx)
168                 return -1;
169
170         if (a_idx > b_idx)
171                 return 1;
172
173         return 0;
174 }
175
176 static bool match_element_path(const void *a, const void *b)
177 {
178         const struct node_element *element = a;
179         const char *path = b;
180
181         if (!element->path)
182                 return false;
183
184         return (!strcmp(element->path, path));
185 }
186
187 struct mesh_node *node_find_by_uuid(uint8_t uuid[16])
188 {
189         return l_queue_find(nodes, match_device_uuid, uuid);
190 }
191
192 struct mesh_node *node_find_by_token(uint64_t token)
193 {
194         return l_queue_find(nodes, match_token, (void *) &token);
195 }
196
197 uint8_t *node_uuid_get(struct mesh_node *node)
198 {
199         if (!node)
200                 return NULL;
201         return node->uuid;
202 }
203
204 static void set_defaults(struct mesh_node *node)
205 {
206         node->lpn = MESH_MODE_UNSUPPORTED;
207         node->proxy = MESH_MODE_UNSUPPORTED;
208         node->friend = (mesh_friendship_supported()) ? MESH_MODE_DISABLED :
209                                                         MESH_MODE_UNSUPPORTED;
210         node->beacon = (mesh_beacon_enabled()) ? MESH_MODE_ENABLED :
211                                                         MESH_MODE_DISABLED;
212         node->relay.mode = (mesh_relay_supported()) ? MESH_MODE_DISABLED :
213                                                         MESH_MODE_UNSUPPORTED;
214         node->ttl = TTL_MASK;
215         node->seq_number = DEFAULT_SEQUENCE_NUMBER;
216 }
217
218 static struct mesh_node *node_new(const uint8_t uuid[16])
219 {
220         struct mesh_node *node;
221
222         node = l_new(struct mesh_node, 1);
223         node->net = mesh_net_new(node);
224         node->elements = l_queue_new();
225         node->pages = l_queue_new();
226         memcpy(node->uuid, uuid, sizeof(node->uuid));
227         set_defaults(node);
228
229         return node;
230 }
231
232 static void free_element_path(void *a, void *b)
233 {
234         struct node_element *element = a;
235
236         l_free(element->path);
237         element->path = NULL;
238 }
239
240 static void element_free(void *data)
241 {
242         struct node_element *element = data;
243
244         l_queue_destroy(element->models, mesh_model_free);
245         l_free(element->path);
246         l_free(element);
247 }
248
249 static void free_node_dbus_resources(struct mesh_node *node)
250 {
251         if (!node)
252                 return;
253
254         if (node->disc_watch) {
255                 l_dbus_remove_watch(dbus_get_bus(), node->disc_watch);
256                 node->disc_watch = 0;
257         }
258
259         l_queue_foreach(node->elements, free_element_path, NULL);
260         l_free(node->owner);
261         node->owner = NULL;
262         l_free(node->app_path);
263         node->app_path = NULL;
264
265         if (node->obj_path) {
266                 l_dbus_object_remove_interface(dbus_get_bus(), node->obj_path,
267                                                         MESH_NODE_INTERFACE);
268
269                 l_dbus_object_remove_interface(dbus_get_bus(), node->obj_path,
270                                                 MESH_MANAGEMENT_INTERFACE);
271
272                 l_dbus_object_remove_interface(dbus_get_bus(), node->obj_path,
273                                                 L_DBUS_INTERFACE_PROPERTIES);
274
275                 l_free(node->obj_path);
276                 node->obj_path = NULL;
277         }
278 }
279
280 static void free_node_resources(void *data)
281 {
282         struct mesh_node *node = data;
283
284         /* Unregister io callbacks */
285         mesh_net_detach(node->net);
286
287
288         /* In case of a provisioner, stop active scanning */
289         if (node->provisioner)
290                 manager_scan_cancel(node);
291
292         /* Free dynamic resources */
293         free_node_dbus_resources(node);
294         l_queue_destroy(node->elements, element_free);
295         l_queue_destroy(node->pages, l_free);
296         mesh_agent_remove(node->agent);
297         mesh_config_release(node->cfg);
298         mesh_net_free(node->net);
299         l_free(node->storage_dir);
300         l_free(node);
301 }
302
303 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
304 /*
305  * This function is called to free resources
306  */
307 void node_release_resources(struct mesh_node *node)
308 {
309         if (!node)
310                 return;
311
312         /* Free dynamic resources */
313         free_node_dbus_resources(node);
314
315         l_debug("Node DBUS Resources are removed");
316 }
317 #endif
318
319 /*
320  * This function is called to free resources and remove the
321  * configuration files for the specified node.
322  */
323 void node_remove(struct mesh_node *node)
324 {
325         if (!node)
326                 return;
327
328         l_queue_remove(nodes, node);
329
330         mesh_config_destroy_nvm(node->cfg);
331
332         free_node_resources(node);
333 }
334
335 static bool add_element_from_storage(struct mesh_node *node,
336                                         struct mesh_config_element *db_ele)
337 {
338         struct node_element *ele;
339
340         ele = l_new(struct node_element, 1);
341         if (!ele)
342                 return false;
343
344         ele->idx = db_ele->index;
345         ele->location = db_ele->location;
346         ele->models = l_queue_new();
347         l_queue_push_tail(node->elements, ele);
348
349         if (!mesh_model_add_from_storage(node, ele->idx, ele->models,
350                                                         db_ele->models))
351                 return false;
352
353         return true;
354 }
355
356 static bool add_elements_from_storage(struct mesh_node *node,
357                                         struct mesh_config_node *db_node)
358 {
359         const struct l_queue_entry *entry;
360
361         entry = l_queue_get_entries(db_node->elements);
362
363         for (; entry; entry = entry->next)
364                 if (!add_element_from_storage(node, entry->data))
365                         return false;
366
367         return true;
368 }
369
370 static void set_net_key(void *a, void *b)
371 {
372         struct mesh_config_netkey *netkey = a;
373         struct mesh_node *node = b;
374
375         mesh_net_set_key(node->net, netkey->idx, netkey->key, netkey->new_key,
376                                                                 netkey->phase);
377 }
378
379 static void set_appkey(void *a, void *b)
380 {
381         struct mesh_config_appkey *appkey = a;
382         struct mesh_node *node = b;
383
384         appkey_key_init(node->net, appkey->net_idx, appkey->app_idx,
385                                                 appkey->key, appkey->new_key);
386 }
387
388 static bool init_storage_dir(struct mesh_node *node)
389 {
390         char uuid[33];
391         char dir_name[PATH_MAX];
392
393         if (node->storage_dir)
394                 return true;
395
396         if (!hex2str(node->uuid, 16, uuid, sizeof(uuid)))
397                 return false;
398
399         snprintf(dir_name, PATH_MAX, "%s/%s", mesh_get_storage_dir(), uuid);
400
401         if (strlen(dir_name) >= PATH_MAX)
402                 return false;
403
404         create_dir(dir_name);
405
406         node->storage_dir = l_strdup(dir_name);
407
408         /* Initialize directory for storing RPL info */
409         return rpl_init(node->storage_dir);
410 }
411
412 static void update_net_settings(struct mesh_node *node)
413 {
414         struct mesh_net *net = node->net;
415
416         mesh_net_set_proxy_mode(net, node->proxy == MESH_MODE_ENABLED);
417
418         mesh_net_set_friend_mode(net, node->friend == MESH_MODE_ENABLED);
419
420         mesh_net_set_relay_mode(net, node->relay.mode == MESH_MODE_ENABLED,
421                                         node->relay.cnt, node->relay.interval);
422
423         mesh_net_set_beacon_mode(net, node->beacon == MESH_MODE_ENABLED);
424 }
425
426 static bool init_from_storage(struct mesh_config_node *db_node,
427                         const uint8_t uuid[16], struct mesh_config *cfg,
428                         void *user_data)
429 {
430         unsigned int num_ele;
431
432         struct mesh_node *node = node_new(uuid);
433
434         if (!nodes)
435                 nodes = l_queue_new();
436
437         l_queue_push_tail(nodes, node);
438
439         node->comp.cid = db_node->cid;
440         node->comp.pid = db_node->pid;
441         node->comp.vid = db_node->vid;
442         node->comp.crpl = db_node->crpl;
443         node->lpn = db_node->modes.lpn;
444
445         node->proxy = db_node->modes.proxy;
446         node->friend = db_node->modes.friend;
447         node->relay.mode = db_node->modes.relay.state;
448         node->relay.cnt = db_node->modes.relay.cnt;
449         node->relay.interval = db_node->modes.relay.interval;
450         node->beacon = db_node->modes.beacon;
451
452         l_debug("relay %2.2x, proxy %2.2x, lpn %2.2x, friend %2.2x",
453                         node->relay.mode, node->proxy, node->lpn, node->friend);
454         node->ttl = db_node->ttl;
455         node->seq_number = db_node->seq_number;
456
457         memcpy(node->dev_key, db_node->dev_key, 16);
458         memcpy(node->token, db_node->token, 8);
459
460         num_ele = l_queue_length(db_node->elements);
461         if (num_ele > MAX_ELE_COUNT)
462                 goto fail;
463
464         node->num_ele = num_ele;
465
466         if (num_ele != 0 && !add_elements_from_storage(node, db_node))
467                 goto fail;
468
469         node->primary = db_node->unicast;
470
471         if (!db_node->netkeys)
472                 goto fail;
473
474         if (!IS_UNASSIGNED(node->primary) &&
475                 !mesh_net_register_unicast(node->net, node->primary, num_ele))
476                 goto fail;
477
478         mesh_net_set_iv_index(node->net, db_node->iv_index, db_node->iv_update);
479
480         /* Initialize directory for storing keyring and RPL info */
481         if (!init_storage_dir(node) || !mesh_net_load_rpl(node->net))
482                 goto fail;
483
484         if (db_node->net_transmit)
485                 mesh_net_transmit_params_set(node->net,
486                                         db_node->net_transmit->count,
487                                         db_node->net_transmit->interval);
488
489         l_queue_foreach(db_node->netkeys, set_net_key, node);
490
491         l_queue_foreach(db_node->appkeys, set_appkey, node);
492
493         while (l_queue_length(db_node->pages)) {
494                 struct mesh_config_comp_page *page;
495
496                 /* Move the composition pages to the node struct */
497                 page = l_queue_pop_head(db_node->pages);
498                 l_queue_push_tail(node->pages, page);
499         }
500
501         mesh_net_set_seq_num(node->net, node->seq_number);
502         mesh_net_set_default_ttl(node->net, node->ttl);
503
504         update_net_settings(node);
505
506         /* Initialize configuration server model */
507         cfgmod_server_init(node, PRIMARY_ELE_IDX);
508
509         node->cfg = cfg;
510
511         return true;
512 fail:
513         node_remove(node);
514         return false;
515 }
516
517 static void cleanup_node(void *data)
518 {
519         struct mesh_node *node = data;
520         uint32_t seq_num = mesh_net_get_seq_num(node->net);
521
522         /* Preserve the last used sequence number */
523         mesh_config_write_seq_number(node->cfg, seq_num, false);
524
525         free_node_resources(node);
526 }
527
528 /*
529  * This function is called to free resources and write the current
530  * sequence numbers to the configuration file for each known node.
531  */
532 void node_cleanup_all(void)
533 {
534         l_queue_destroy(nodes, cleanup_node);
535         l_dbus_unregister_interface(dbus_get_bus(), MESH_NODE_INTERFACE);
536         l_dbus_unregister_interface(dbus_get_bus(), MESH_MANAGEMENT_INTERFACE);
537 }
538
539 bool node_is_provisioner(struct mesh_node *node)
540 {
541         return node->provisioner;
542 }
543
544 bool node_is_busy(struct mesh_node *node)
545 {
546         return node->busy;
547 }
548
549 void node_app_key_delete(struct mesh_node *node, uint16_t net_idx,
550                                                         uint16_t app_idx)
551 {
552         const struct l_queue_entry *entry;
553
554         entry = l_queue_get_entries(node->elements);
555         for (; entry; entry = entry->next) {
556                 struct node_element *ele = entry->data;
557
558                 mesh_model_app_key_delete(node, ele->idx, ele->models, app_idx);
559         }
560 }
561
562 uint16_t node_get_primary(struct mesh_node *node)
563 {
564         if (!node)
565                 return UNASSIGNED_ADDRESS;
566         else
567                 return node->primary;
568 }
569
570 const uint8_t *node_get_device_key(struct mesh_node *node)
571 {
572         if (!node)
573                 return NULL;
574         else
575                 return node->dev_key;
576 }
577
578 void node_set_token(struct mesh_node *node, uint8_t token[8])
579 {
580         memcpy(node->token, token, 8);
581 }
582
583 const uint8_t *node_get_token(struct mesh_node *node)
584 {
585         if (!node)
586                 return NULL;
587         else
588                 return node->token;
589 }
590
591 uint8_t node_get_num_elements(struct mesh_node *node)
592 {
593         return node->num_ele;
594 }
595
596 struct l_queue *node_get_element_models(struct mesh_node *node, uint8_t ele_idx)
597 {
598         struct node_element *ele;
599
600         if (!node)
601                 return NULL;
602
603         ele = l_queue_find(node->elements, match_element_idx,
604                                                         L_UINT_TO_PTR(ele_idx));
605         if (!ele)
606                 return NULL;
607
608         return ele->models;
609 }
610
611 uint8_t node_default_ttl_get(struct mesh_node *node)
612 {
613         if (!node)
614                 return TTL_MASK;
615         return node->ttl;
616 }
617
618 bool node_default_ttl_set(struct mesh_node *node, uint8_t ttl)
619 {
620         bool res;
621
622         if (!node)
623                 return false;
624
625         res = mesh_config_write_ttl(node->cfg, ttl);
626
627         if (res) {
628                 node->ttl = ttl;
629                 mesh_net_set_default_ttl(node->net, ttl);
630         }
631
632         return res;
633 }
634
635 bool node_set_sequence_number(struct mesh_node *node, uint32_t seq)
636 {
637         if (!node)
638                 return false;
639
640         node->seq_number = seq;
641
642         return mesh_config_write_seq_number(node->cfg, node->seq_number, true);
643 }
644
645 uint32_t node_get_sequence_number(struct mesh_node *node)
646 {
647         if (!node)
648                 return 0xffffffff;
649
650         return node->seq_number;
651 }
652
653 int node_get_element_idx(struct mesh_node *node, uint16_t ele_addr)
654 {
655         uint16_t addr;
656         uint8_t num_ele;
657
658         if (!node)
659                 return -1;
660
661         num_ele = node_get_num_elements(node);
662         if (!num_ele)
663                 return -2;
664
665         addr = node_get_primary(node);
666
667         if (ele_addr < addr || ele_addr >= addr + num_ele)
668                 return -3;
669         else
670                 return ele_addr - addr;
671 }
672
673 uint16_t node_get_crpl(struct mesh_node *node)
674 {
675         if (!node)
676                 return 0;
677
678         return node->comp.crpl;
679 }
680
681 uint8_t node_relay_mode_get(struct mesh_node *node, uint8_t *count,
682                                                         uint16_t *interval)
683 {
684         if (!node) {
685                 *count = 0;
686                 *interval = 0;
687                 return MESH_MODE_DISABLED;
688         }
689
690         *count = node->relay.cnt;
691         *interval = node->relay.interval;
692         return node->relay.mode;
693 }
694
695 uint8_t node_lpn_mode_get(struct mesh_node *node)
696 {
697         if (!node)
698                 return MESH_MODE_DISABLED;
699
700         return node->lpn;
701 }
702
703 bool node_relay_mode_set(struct mesh_node *node, bool enable, uint8_t cnt,
704                                                         uint16_t interval)
705 {
706         bool res;
707
708         if (!node || node->relay.mode == MESH_MODE_UNSUPPORTED)
709                 return false;
710
711         res = mesh_config_write_relay_mode(node->cfg, enable, cnt, interval);
712
713         if (res) {
714                 node->relay.mode = enable ? MESH_MODE_ENABLED :
715                                                         MESH_MODE_DISABLED;
716                 node->relay.cnt = cnt;
717                 node->relay.interval = interval;
718                 mesh_net_set_relay_mode(node->net, enable, cnt, interval);
719         }
720
721         return res;
722 }
723
724 bool node_proxy_mode_set(struct mesh_node *node, bool enable)
725 {
726         bool res;
727         uint8_t proxy;
728
729         if (!node || node->proxy == MESH_MODE_UNSUPPORTED)
730                 return false;
731
732         proxy = enable ? MESH_MODE_ENABLED : MESH_MODE_DISABLED;
733         res = mesh_config_write_mode(node->cfg, "proxy", proxy);
734
735         if (res) {
736                 node->proxy = proxy;
737                 mesh_net_set_proxy_mode(node->net, enable);
738         }
739
740         return res;
741 }
742
743 uint8_t node_proxy_mode_get(struct mesh_node *node)
744 {
745         if (!node)
746                 return MESH_MODE_DISABLED;
747
748         return node->proxy;
749 }
750
751 bool node_beacon_mode_set(struct mesh_node *node, bool enable)
752 {
753         bool res;
754         uint8_t beacon;
755
756         if (!node)
757                 return false;
758
759         beacon = enable ? MESH_MODE_ENABLED : MESH_MODE_DISABLED;
760         res = mesh_config_write_mode(node->cfg, "beacon", beacon);
761
762         if (res) {
763                 node->beacon = beacon;
764                 mesh_net_set_beacon_mode(node->net, enable);
765         }
766
767         return res;
768 }
769
770 uint8_t node_beacon_mode_get(struct mesh_node *node)
771 {
772         if (!node)
773                 return MESH_MODE_DISABLED;
774
775         return node->beacon;
776 }
777
778 bool node_friend_mode_set(struct mesh_node *node, bool enable)
779 {
780         bool res;
781         uint8_t friend;
782
783         if (!node || node->friend == MESH_MODE_UNSUPPORTED)
784                 return false;
785
786         friend = enable ? MESH_MODE_ENABLED : MESH_MODE_DISABLED;
787         res = mesh_config_write_mode(node->cfg, "friend", friend);
788
789         if (res) {
790                 node->friend = friend;
791                 mesh_net_set_friend_mode(node->net, enable);
792         }
793
794         return res;
795 }
796
797 uint8_t node_friend_mode_get(struct mesh_node *node)
798 {
799         if (!node)
800                 return MESH_MODE_DISABLED;
801
802         return node->friend;
803 }
804
805 static uint16_t generate_node_comp(struct mesh_node *node, uint8_t *buf,
806                                                                 uint16_t sz)
807 {
808         uint16_t n, features, num_ele = 0;
809         const struct l_queue_entry *entry;
810
811         n = 0;
812
813         l_put_le16(node->comp.cid, buf + n);
814         n += 2;
815         l_put_le16(node->comp.pid, buf + n);
816         n += 2;
817         l_put_le16(node->comp.vid, buf + n);
818         n += 2;
819         l_put_le16(node->comp.crpl, buf + n);
820         n += 2;
821
822         features = 0;
823
824         if (node->relay.mode != MESH_MODE_UNSUPPORTED)
825                 features |= FEATURE_RELAY;
826         if (node->proxy != MESH_MODE_UNSUPPORTED)
827                 features |= FEATURE_PROXY;
828         if (node->friend != MESH_MODE_UNSUPPORTED)
829                 features |= FEATURE_FRIEND;
830         if (node->lpn != MESH_MODE_UNSUPPORTED)
831                 features |= FEATURE_LPN;
832
833         l_put_le16(features, buf + n);
834         n += 2;
835
836         entry = l_queue_get_entries(node->elements);
837
838         for (; entry; entry = entry->next) {
839                 struct node_element *ele = entry->data;
840
841                 if (ele->idx != num_ele)
842                         return 0;
843
844                 num_ele++;
845
846                 /* At least fit location and zeros for number of models */
847                 if ((n + 4) > sz)
848                         return n;
849
850                 l_put_le16(ele->location, buf + n);
851                 n += 2;
852
853                 n += mesh_model_generate_composition(ele->models, sz - n,
854                                                                 buf + n);
855         }
856
857         if (!num_ele)
858                 return 0;
859
860         return n;
861 }
862
863 static bool match_page(const void *a, const void *b)
864 {
865         const struct mesh_config_comp_page *page = a;
866         uint8_t page_num = L_PTR_TO_UINT(b);
867
868         return page->page_num == page_num;
869 }
870
871 static void convert_node_to_storage(struct mesh_node *node,
872                                         struct mesh_config_node *db_node)
873 {
874         const struct l_queue_entry *entry;
875
876         memset(db_node, 0, sizeof(struct mesh_config_node));
877
878         db_node->cid = node->comp.cid;
879         db_node->pid = node->comp.pid;
880         db_node->vid = node->comp.vid;
881         db_node->crpl = node->comp.crpl;
882         db_node->modes.lpn = node->lpn;
883         db_node->modes.proxy = node->proxy;
884
885         db_node->modes.friend = node->friend;
886         db_node->modes.relay.state = node->relay.mode;
887         db_node->modes.relay.cnt = node->relay.cnt;
888         db_node->modes.relay.interval = node->relay.interval;
889         db_node->modes.beacon = node->beacon;
890
891         db_node->ttl = node->ttl;
892         db_node->seq_number = node->seq_number;
893
894         db_node->elements = l_queue_new();
895
896         entry = l_queue_get_entries(node->elements);
897
898         for (; entry; entry = entry->next) {
899                 struct node_element *ele = entry->data;
900                 struct mesh_config_element *db_ele;
901
902                 db_ele = l_new(struct mesh_config_element, 1);
903
904                 db_ele->index = ele->idx;
905                 db_ele->location = ele->location;
906                 db_ele->models = l_queue_new();
907
908                 mesh_model_convert_to_storage(db_ele->models, ele->models);
909
910                 l_queue_push_tail(db_node->elements, db_ele);
911         }
912
913 }
914
915 static bool create_node_config(struct mesh_node *node, const uint8_t uuid[16])
916 {
917         struct mesh_config_node db_node;
918         const struct l_queue_entry *entry;
919         const char *storage_dir;
920
921         convert_node_to_storage(node, &db_node);
922         storage_dir = mesh_get_storage_dir();
923         node->cfg = mesh_config_create(storage_dir, uuid, &db_node);
924
925         if (node->cfg)
926                 init_storage_dir(node);
927
928         /* Free temporarily allocated resources */
929         entry = l_queue_get_entries(db_node.elements);
930
931         for (; entry; entry = entry->next) {
932                 struct mesh_config_element *db_ele = entry->data;
933
934                 l_queue_destroy(db_ele->models, l_free);
935         }
936
937         l_queue_destroy(db_node.elements, l_free);
938
939         return node->cfg != NULL;
940 }
941
942 static bool set_node_comp(struct mesh_node *node, uint8_t page_num,
943                                         const uint8_t *data, uint16_t len)
944 {
945         struct mesh_config_comp_page *page;
946
947         if (len < MIN_COMP_SIZE)
948                 return false;
949
950         page = l_queue_remove_if(node->pages, match_page,
951                                                 L_UINT_TO_PTR(page_num));
952
953         l_free(page);
954
955         page = l_malloc(sizeof(struct mesh_config_comp_page) + len);
956         page->len = len;
957         page->page_num = page_num;
958         memcpy(page->data, data, len);
959         l_queue_push_tail(node->pages, page);
960
961         return mesh_config_comp_page_add(node->cfg, page_num, page->data, len);
962 }
963
964 static bool create_node_comp(struct mesh_node *node)
965 {
966         uint16_t len;
967         uint8_t comp[MAX_MSG_LEN - 2];
968
969         len = generate_node_comp(node, comp, sizeof(comp));
970
971         return set_node_comp(node, 0, comp, len);
972 }
973
974 const uint8_t *node_get_comp(struct mesh_node *node, uint8_t page_num,
975                                                                 uint16_t *len)
976 {
977         struct mesh_config_comp_page *page = NULL;
978
979         if (node)
980                 page = l_queue_find(node->pages, match_page,
981                                                 L_UINT_TO_PTR(page_num));
982
983         if (!page) {
984                 *len = 0;
985                 return NULL;
986         }
987
988         *len = page->len;
989         return page->data;
990 }
991
992 bool node_replace_comp(struct mesh_node *node, uint8_t retire, uint8_t with)
993 {
994         struct mesh_config_comp_page *old_page, *keep;
995
996         if (!node)
997                 return false;
998
999         keep = l_queue_find(node->pages, match_page, L_UINT_TO_PTR(with));
1000
1001         if (!keep)
1002                 return false;
1003
1004         old_page = l_queue_remove_if(node->pages, match_page,
1005                                                         L_UINT_TO_PTR(retire));
1006
1007         l_free(old_page);
1008         keep->page_num = retire;
1009         mesh_config_comp_page_mv(node->cfg, with, retire);
1010
1011         return true;
1012 }
1013
1014 static void attach_io(void *a, void *b)
1015 {
1016         struct mesh_node *node = a;
1017         struct mesh_io *io = b;
1018
1019         if (node->net)
1020                 mesh_net_attach(node->net, io);
1021 }
1022
1023 /* Register callbacks for all nodes io */
1024 void node_attach_io_all(struct mesh_io *io)
1025 {
1026         l_queue_foreach(nodes, attach_io, io);
1027 }
1028
1029 /* Register node object with D-Bus */
1030 static bool register_node_object(struct mesh_node *node)
1031 {
1032         char uuid[33];
1033
1034         if (!hex2str(node->uuid, sizeof(node->uuid), uuid, sizeof(uuid)))
1035                 return false;
1036
1037         node->obj_path = l_strdup_printf(BLUEZ_MESH_PATH MESH_NODE_PATH_PREFIX
1038                                                                 "%s", uuid);
1039
1040         if (!l_dbus_object_add_interface(dbus_get_bus(), node->obj_path,
1041                                                 MESH_NODE_INTERFACE, node))
1042                 return false;
1043
1044         if (!l_dbus_object_add_interface(dbus_get_bus(), node->obj_path,
1045                                         MESH_MANAGEMENT_INTERFACE, node))
1046                 return false;
1047
1048         if (!l_dbus_object_add_interface(dbus_get_bus(), node->obj_path,
1049                                         L_DBUS_INTERFACE_PROPERTIES, NULL))
1050                 return false;
1051
1052         return true;
1053 }
1054
1055 static void app_disc_cb(struct l_dbus *bus, void *user_data)
1056 {
1057         struct mesh_node *node = user_data;
1058
1059         l_info("App %s disconnected (%u)", node->owner, node->disc_watch);
1060
1061         node->disc_watch = 0;
1062
1063         /* In case of a provisioner, stop active scanning */
1064         if (node->provisioner)
1065                 manager_scan_cancel(node);
1066
1067         free_node_dbus_resources(node);
1068 }
1069
1070 static bool get_sig_models_from_properties(struct mesh_node *node,
1071                                         struct node_element *ele,
1072                                         struct l_dbus_message_iter *property)
1073 {
1074         struct l_dbus_message_iter mods, var;
1075         uint16_t m_id;
1076
1077         if (!ele->models)
1078                 ele->models = l_queue_new();
1079
1080         if (!l_dbus_message_iter_get_variant(property, "a(qa{sv})", &mods))
1081                 return false;
1082
1083         /* Bluetooth SIG defined models */
1084         while (l_dbus_message_iter_next_entry(&mods, &m_id, &var)) {
1085                 uint32_t id = SET_ID(SIG_VENDOR, m_id);
1086
1087                 /* Allow Config Server Model only on the primary element */
1088                 if (ele->idx != PRIMARY_ELE_IDX && id == CONFIG_SRV_MODEL)
1089                         return false;
1090
1091                 if (!mesh_model_add(node, ele->models, id, &var))
1092                         return false;
1093         }
1094
1095         return true;
1096 }
1097
1098 static bool get_vendor_models_from_properties(struct mesh_node *node,
1099                                         struct node_element *ele,
1100                                         struct l_dbus_message_iter *property)
1101 {
1102         struct l_dbus_message_iter mods, var;
1103         uint16_t m_id, v_id;
1104
1105         if (!ele->models)
1106                 ele->models = l_queue_new();
1107
1108         if (!l_dbus_message_iter_get_variant(property, "a(qqa{sv})", &mods))
1109                 return false;
1110
1111         /* Vendor defined models */
1112         while (l_dbus_message_iter_next_entry(&mods, &v_id, &m_id, &var)) {
1113                 uint32_t id = SET_ID(v_id, m_id);
1114
1115                 if (!mesh_model_add(node, ele->models, id, &var))
1116                         return false;
1117         }
1118
1119         return true;
1120 }
1121
1122 static bool get_element_properties(struct mesh_node *node, const char *path,
1123                                         struct l_dbus_message_iter *properties)
1124 {
1125         struct node_element *ele = l_new(struct node_element, 1);
1126         const char *key;
1127         struct l_dbus_message_iter var;
1128         bool idx = false;
1129         bool mods = false;
1130         bool vendor_mods = false;
1131
1132         l_debug("path %s", path);
1133
1134         ele->location = DEFAULT_LOCATION;
1135
1136         while (l_dbus_message_iter_next_entry(properties, &key, &var)) {
1137                 if (!strcmp(key, "Index")) {
1138
1139                         if (idx || !l_dbus_message_iter_get_variant(&var, "y",
1140                                                                 &ele->idx))
1141                                 goto fail;
1142
1143                         idx = true;
1144
1145                 } else if (!strcmp(key, "Models")) {
1146
1147                         if (mods)
1148                                 goto fail;
1149
1150                         if (!get_sig_models_from_properties(node, ele, &var))
1151                                 goto fail;
1152
1153                         mods = true;
1154                 } else if (!strcmp(key, "VendorModels")) {
1155
1156                         if (vendor_mods)
1157                                 goto fail;
1158
1159                         if (!get_vendor_models_from_properties(node, ele, &var))
1160                                 goto fail;
1161
1162                         vendor_mods = true;
1163
1164                 } else if (!strcmp(key, "Location")) {
1165                         if (!l_dbus_message_iter_get_variant(&var, "q",
1166                                                         &ele->location))
1167                                 goto fail;
1168                 }
1169         }
1170
1171         /* Check for the presence of the required properties */
1172         if (!idx || !mods || !vendor_mods)
1173                 goto fail;
1174
1175         if (l_queue_find(node->elements, match_element_idx,
1176                                                 L_UINT_TO_PTR(ele->idx)))
1177                 goto fail;
1178
1179         l_queue_insert(node->elements, ele, compare_element_idx, NULL);
1180
1181         ele->path = l_strdup(path);
1182
1183         /*
1184          * Add configuration server model on the primary element.
1185          * We allow the application not to specify the presense of
1186          * the Configuration Server model, since it's implemented by the
1187          * daemon. If the model is present in the application properties,
1188          * the operation below will be a "no-op".
1189          */
1190         if (ele->idx == PRIMARY_ELE_IDX)
1191                 mesh_model_add(node, ele->models, CONFIG_SRV_MODEL, NULL);
1192
1193         return true;
1194 fail:
1195         l_free(ele);
1196
1197         return false;
1198 }
1199
1200 static bool get_app_properties(struct mesh_node *node, const char *path,
1201                                         struct l_dbus_message_iter *properties)
1202 {
1203         const char *key;
1204         struct l_dbus_message_iter variant;
1205         bool cid = false;
1206         bool pid = false;
1207         bool vid = false;
1208
1209         l_debug("path %s", path);
1210
1211         node->comp.crpl = mesh_get_crpl();
1212
1213         while (l_dbus_message_iter_next_entry(properties, &key, &variant)) {
1214                 if (!cid && !strcmp(key, "CompanyID")) {
1215                         if (!l_dbus_message_iter_get_variant(&variant, "q",
1216                                                         &node->comp.cid))
1217                                 return false;
1218                         cid = true;
1219                         continue;
1220                 }
1221
1222                 if (!pid && !strcmp(key, "ProductID")) {
1223                         if (!l_dbus_message_iter_get_variant(&variant, "q",
1224                                                         &node->comp.pid))
1225                                 return false;
1226                         pid = true;
1227                         continue;
1228                 }
1229
1230                 if (!vid && !strcmp(key, "VersionID")) {
1231                         if (!l_dbus_message_iter_get_variant(&variant, "q",
1232                                                         &node->comp.vid))
1233                                 return false;
1234                         vid = true;
1235                         continue;
1236                 }
1237
1238                 if (!strcmp(key, "CRPL")) {
1239                         if (!l_dbus_message_iter_get_variant(&variant, "q",
1240                                                         &node->comp.crpl))
1241                                 return false;
1242                         continue;
1243                 }
1244         }
1245
1246         if (!cid || !pid || !vid)
1247                 return false;
1248
1249         return true;
1250 }
1251
1252 static bool add_local_node(struct mesh_node *node, uint16_t unicast, bool kr,
1253                                 bool ivu, uint32_t iv_idx, uint8_t dev_key[16],
1254                                 uint16_t net_key_idx, uint8_t net_key[16])
1255 {
1256         if (!nodes)
1257                 nodes = l_queue_new();
1258
1259         l_queue_push_tail(nodes, node);
1260
1261         if (!mesh_config_write_iv_index(node->cfg, iv_idx, ivu))
1262                 return false;
1263
1264         mesh_net_set_iv_index(node->net, iv_idx, ivu);
1265
1266         if (!mesh_config_write_unicast(node->cfg, unicast))
1267                 return false;
1268
1269         l_getrandom(node->token, sizeof(node->token));
1270         if (!mesh_config_write_token(node->cfg, node->token))
1271                 return false;
1272
1273         memcpy(node->dev_key, dev_key, 16);
1274         if (!mesh_config_write_device_key(node->cfg, dev_key))
1275                 return false;
1276
1277         node->primary = unicast;
1278         mesh_net_register_unicast(node->net, unicast, node->num_ele);
1279
1280         if (mesh_net_add_key(node->net, net_key_idx, net_key) !=
1281                                                         MESH_STATUS_SUCCESS)
1282                 return false;
1283
1284         if (kr) {
1285                 /* Duplicate net key, if the key refresh is on */
1286                 if (mesh_net_update_key(node->net, net_key_idx, net_key) !=
1287                                                         MESH_STATUS_SUCCESS)
1288                         return false;
1289
1290                 if (!mesh_config_net_key_set_phase(node->cfg, net_key_idx,
1291                                                         KEY_REFRESH_PHASE_TWO))
1292                         return false;
1293         }
1294
1295         update_net_settings(node);
1296
1297         /* Initialize configuration server model */
1298         cfgmod_server_init(node, PRIMARY_ELE_IDX);
1299
1300         node->busy = true;
1301
1302         return true;
1303 }
1304
1305 static void update_composition(struct mesh_node *node, struct mesh_node *attach)
1306 {
1307         if (node->comp.cid != attach->comp.cid)
1308                 mesh_config_update_company_id(attach->cfg, node->comp.cid);
1309
1310         if (node->comp.pid != attach->comp.pid)
1311                 mesh_config_update_product_id(attach->cfg, node->comp.pid);
1312
1313         if (node->comp.vid != attach->comp.vid)
1314                 mesh_config_update_version_id(attach->cfg, node->comp.vid);
1315
1316         if (node->comp.crpl != attach->comp.crpl)
1317                 mesh_config_update_crpl(attach->cfg, node->comp.crpl);
1318
1319         attach->comp = node->comp;
1320 }
1321
1322 static void update_model_options(struct mesh_node *node,
1323                                                 struct mesh_node *attach)
1324 {
1325         uint32_t len, i;
1326         struct node_element *ele, *ele_attach;
1327
1328         len = l_queue_length(node->elements);
1329
1330         for (i = 0; i < len; i++) {
1331
1332                 ele = l_queue_find(node->elements, match_element_idx,
1333                                                         L_UINT_TO_PTR(i));
1334                 ele_attach = l_queue_find(attach->elements, match_element_idx,
1335                                                         L_UINT_TO_PTR(i));
1336                 if (!ele || !ele_attach)
1337                         continue;
1338
1339                 mesh_model_update_opts(node, ele->idx, ele_attach->models,
1340                                                                 ele->models);
1341         }
1342 }
1343
1344 static bool check_req_node(struct managed_obj_request *req)
1345 {
1346         const int offset = 8;
1347         uint16_t node_len, len;
1348         uint8_t comp[MAX_MSG_LEN - 2];
1349         const uint8_t *node_comp;
1350
1351         len = generate_node_comp(req->node, comp, sizeof(comp));
1352
1353         if (len < MIN_COMP_SIZE)
1354                 return false;
1355
1356         node_comp = node_get_comp(req->attach, 0, &node_len);
1357
1358         /* If no page 0 exists, create it and accept */
1359         if (!node_len || !node_comp)
1360                 return set_node_comp(req->attach, 0, comp, len);
1361
1362         /* Test Element/Model part of composition and reject if changed */
1363         if (node_len != len || memcmp(&node_comp[offset], &comp[offset],
1364                                                         node_len - offset))
1365                 return false;
1366
1367         /* If comp has changed, but not Element/Models, resave and accept */
1368         else if (memcmp(node_comp, comp, node_len))
1369                 return set_node_comp(req->attach, 0, comp, len);
1370
1371         /* Nothing has changed */
1372         return true;
1373 }
1374
1375 static bool attach_req_node(struct mesh_node *attach, struct mesh_node *node)
1376 {
1377         const struct l_queue_entry *attach_entry;
1378         const struct l_queue_entry *node_entry;
1379
1380         attach->obj_path = node->obj_path;
1381         node->obj_path = NULL;
1382
1383         if (!register_node_object(attach)) {
1384                 free_node_dbus_resources(attach);
1385                 return false;
1386         }
1387
1388         attach_entry = l_queue_get_entries(attach->elements);
1389         node_entry = l_queue_get_entries(node->elements);
1390
1391         /*
1392          * Update existing node with paths collected in temporary node,
1393          * then remove the temporary.
1394          */
1395         while (attach_entry && node_entry) {
1396                 struct node_element *attach_ele = attach_entry->data;
1397                 struct node_element *node_ele = node_entry->data;
1398
1399                 attach_ele->path = node_ele->path;
1400                 node_ele->path = NULL;
1401
1402                 attach_entry = attach_entry->next;
1403                 node_entry = node_entry->next;
1404         }
1405
1406         mesh_agent_remove(attach->agent);
1407         attach->agent = node->agent;
1408         node->agent = NULL;
1409
1410         attach->provisioner = node->provisioner;
1411
1412         attach->app_path = node->app_path;
1413         node->app_path = NULL;
1414
1415         attach->owner = node->owner;
1416         node->owner = NULL;
1417
1418         update_composition(node, attach);
1419         update_model_options(node, attach);
1420
1421         node_remove(node);
1422
1423         return true;
1424 }
1425
1426 static void get_managed_objects_cb(struct l_dbus_message *msg, void *user_data)
1427 {
1428         struct l_dbus_message_iter objects, interfaces;
1429         struct managed_obj_request *req = user_data;
1430         const char *path;
1431         struct mesh_node *node = req->node;
1432         struct node_import *import;
1433         bool have_app = false;
1434         unsigned int num_ele;
1435         struct keyring_net_key net_key;
1436         uint8_t dev_key[16];
1437
1438         if (req->type == REQUEST_TYPE_ATTACH)
1439                 req->attach->busy = false;
1440
1441         if (!msg || l_dbus_message_is_error(msg)) {
1442                 l_error("Failed to get app's dbus objects");
1443                 goto fail;
1444         }
1445
1446         if (!l_dbus_message_get_arguments(msg, "a{oa{sa{sv}}}", &objects)) {
1447                 l_error("Failed to parse app's dbus objects");
1448                 goto fail;
1449         }
1450
1451         while (l_dbus_message_iter_next_entry(&objects, &path, &interfaces)) {
1452                 struct l_dbus_message_iter properties;
1453                 const char *interface;
1454
1455                 while (l_dbus_message_iter_next_entry(&interfaces, &interface,
1456                                                                 &properties)) {
1457                         bool res;
1458
1459                         if (!strcmp(MESH_ELEMENT_INTERFACE, interface)) {
1460                                 res = get_element_properties(node, path,
1461                                                                 &properties);
1462                                 if (!res)
1463                                         goto fail;
1464                         } else if (!strcmp(MESH_APPLICATION_INTERFACE,
1465                                                                 interface)) {
1466                                 if (have_app)
1467                                         goto fail;
1468
1469                                 req->node->app_path = l_strdup(path);
1470
1471                                 res = get_app_properties(node, path,
1472                                                                 &properties);
1473                                 if (!res)
1474                                         goto fail;
1475
1476                                 have_app = true;
1477
1478                         } else if (!strcmp(MESH_PROVISION_AGENT_INTERFACE,
1479                                                                 interface)) {
1480                                 const char *sender;
1481
1482                                 sender = l_dbus_message_get_sender(msg);
1483                                 node->agent = mesh_agent_create(path, sender,
1484                                                                 &properties);
1485                                 if (!node->agent)
1486                                         goto fail;
1487
1488                         } else if (!strcmp(MESH_PROVISIONER_INTERFACE,
1489                                                                 interface)) {
1490                                 node->provisioner = true;
1491                         }
1492                 }
1493         }
1494
1495         if (!have_app) {
1496                 l_error("Interface %s not found", MESH_APPLICATION_INTERFACE);
1497                 goto fail;
1498         }
1499
1500         if (l_queue_isempty(node->elements)) {
1501                 l_error("Interface %s not found", MESH_ELEMENT_INTERFACE);
1502                 goto fail;
1503         }
1504
1505         if (!l_queue_find(node->elements, match_element_idx,
1506                                 L_UINT_TO_PTR(PRIMARY_ELE_IDX))) {
1507
1508                 l_debug("Primary element not detected");
1509                 goto fail;
1510         }
1511
1512         num_ele = l_queue_length(node->elements);
1513
1514         if (num_ele > MAX_ELE_COUNT)
1515                 goto fail;
1516
1517         node->num_ele = num_ele;
1518
1519         if (req->type != REQUEST_TYPE_ATTACH) {
1520                 /* Generate node configuration for a brand new node */
1521                 if (!create_node_config(node, node->uuid))
1522                         goto fail;
1523
1524                 /* Create node composition */
1525                 if (!create_node_comp(node))
1526                         goto fail;
1527         } else if (!check_req_node(req))
1528                 /* Check the integrity of the node composition */
1529                 goto fail;
1530
1531         switch (req->type) {
1532         case REQUEST_TYPE_ATTACH:
1533                 if (!attach_req_node(req->attach, node))
1534                         goto fail;
1535
1536                 req->attach->disc_watch = l_dbus_add_disconnect_watch(
1537                                         dbus_get_bus(), req->attach->owner,
1538                                         app_disc_cb, req->attach, NULL);
1539
1540                 req->ready_cb(req->pending_msg, MESH_ERROR_NONE, req->attach);
1541                 return;
1542
1543         case REQUEST_TYPE_JOIN:
1544                 if (!node->agent) {
1545                         l_error("Interface %s not found",
1546                                                 MESH_PROVISION_AGENT_INTERFACE);
1547                         goto fail;
1548                 }
1549
1550                 req->join_ready_cb(node, node->agent);
1551
1552                 return;
1553
1554         case REQUEST_TYPE_IMPORT:
1555                 import = req->import;
1556                 if (!add_local_node(node, import->unicast, import->flags.kr,
1557                                         import->flags.ivu,
1558                                         import->iv_index, import->dev_key,
1559                                         import->net_idx, import->net_key))
1560                         goto fail;
1561
1562                 req->ready_cb(req->pending_msg, MESH_ERROR_NONE, node);
1563                 l_free(import);
1564
1565                 return;
1566
1567         case REQUEST_TYPE_CREATE:
1568                 /* Generate device and primary network keys */
1569                 l_getrandom(dev_key, sizeof(dev_key));
1570                 l_getrandom(net_key.old_key, sizeof(net_key.old_key));
1571                 memcpy(net_key.new_key, net_key.old_key,
1572                                                 sizeof(net_key.old_key));
1573                 net_key.net_idx = PRIMARY_NET_IDX;
1574                 net_key.phase = KEY_REFRESH_PHASE_NONE;
1575
1576                 if (!add_local_node(node, DEFAULT_NEW_UNICAST, false, false,
1577                                                 DEFAULT_IV_INDEX, dev_key,
1578                                                 PRIMARY_NET_IDX,
1579                                                 net_key.old_key))
1580                         goto fail;
1581
1582                 if (!keyring_put_remote_dev_key(node, DEFAULT_NEW_UNICAST,
1583                                                 node->num_ele, dev_key))
1584                         goto fail;
1585
1586                 if (!keyring_put_net_key(node, PRIMARY_NET_IDX, &net_key))
1587                         goto fail;
1588
1589                 req->ready_cb(req->pending_msg, MESH_ERROR_NONE, node);
1590                 return;
1591
1592         default:
1593                 goto fail;
1594         }
1595
1596 fail:
1597         /* Handle failed requests */
1598         node_remove(node);
1599
1600         if (req->type == REQUEST_TYPE_JOIN)
1601                 req->join_ready_cb(NULL, NULL);
1602         else
1603                 req->ready_cb(req->pending_msg, MESH_ERROR_FAILED, NULL);
1604
1605         if (req->type == REQUEST_TYPE_IMPORT)
1606                 l_free(req->import);
1607 }
1608
1609 static void send_managed_objects_request(const char *destination,
1610                                                 const char *path,
1611                                                 struct managed_obj_request *req)
1612 {
1613         struct l_dbus_message *msg;
1614
1615         msg = l_dbus_message_new_method_call(dbus_get_bus(), destination, path,
1616                                                 L_DBUS_INTERFACE_OBJECT_MANAGER,
1617                                                 "GetManagedObjects");
1618         l_dbus_message_set_arguments(msg, "");
1619         dbus_send_with_timeout(dbus_get_bus(), msg, get_managed_objects_cb,
1620                                         req, l_free, DEFAULT_DBUS_TIMEOUT);
1621 }
1622
1623 /* Establish relationship between application and mesh node */
1624 void node_attach(const char *app_root, const char *sender, uint64_t token,
1625                                         node_ready_func_t cb, void *user_data)
1626 {
1627         struct managed_obj_request *req;
1628         struct mesh_node *node;
1629
1630         node = l_queue_find(nodes, match_token, (void *) &token);
1631         if (!node) {
1632                 cb(user_data, MESH_ERROR_NOT_FOUND, NULL);
1633                 return;
1634         }
1635
1636         /* Check if there is a pending request associated with this node */
1637         if (node->busy) {
1638                 cb(user_data, MESH_ERROR_BUSY, NULL);
1639                 return;
1640         }
1641
1642         /* Check if the node is already in use */
1643         if (node->owner) {
1644                 l_warn("The node is already in use");
1645                 cb(user_data, MESH_ERROR_ALREADY_EXISTS, NULL);
1646                 return;
1647         }
1648
1649         req = l_new(struct managed_obj_request, 1);
1650
1651         /*
1652          * Create a temporary node to collect composition data from attaching
1653          * application. Existing node is passed in req->attach.
1654          */
1655         req->node = node_new(node->uuid);
1656         req->node->owner = l_strdup(sender);
1657         req->ready_cb = cb;
1658         req->pending_msg = user_data;
1659         req->attach = node;
1660         req->type = REQUEST_TYPE_ATTACH;
1661
1662         node->busy = true;
1663
1664         l_dbus_method_call(dbus_get_bus(), sender, app_root,
1665                                         L_DBUS_INTERFACE_OBJECT_MANAGER,
1666                                         "GetManagedObjects", NULL,
1667                                         get_managed_objects_cb,
1668                                         req, l_free);
1669 }
1670
1671 /* Create a temporary pre-provisioned node */
1672 void node_join(const char *app_root, const char *sender, const uint8_t *uuid,
1673                                                 node_join_ready_func_t cb)
1674 {
1675         struct managed_obj_request *req;
1676
1677         l_debug("");
1678
1679         req = l_new(struct managed_obj_request, 1);
1680         req->node = node_new(uuid);
1681         req->join_ready_cb = cb;
1682         req->type = REQUEST_TYPE_JOIN;
1683
1684         send_managed_objects_request(sender, app_root, req);
1685 }
1686
1687 void node_import(const char *app_root, const char *sender, const uint8_t *uuid,
1688                         const uint8_t dev_key[16], const uint8_t net_key[16],
1689                         uint16_t net_idx, bool kr, bool ivu,
1690                         uint32_t iv_index, uint16_t unicast,
1691                         node_ready_func_t cb, void *user_data)
1692 {
1693         struct managed_obj_request *req;
1694
1695         l_debug("");
1696
1697         req = l_new(struct managed_obj_request, 1);
1698
1699         req->node = node_new(uuid);
1700         req->ready_cb = cb;
1701         req->pending_msg = user_data;
1702
1703         req->import = l_new(struct node_import, 1);
1704         memcpy(req->import->dev_key, dev_key, 16);
1705         memcpy(req->import->net_key, net_key, 16);
1706         req->import->net_idx = net_idx;
1707         req->import->flags.kr = kr;
1708         req->import->flags.ivu = ivu;
1709         req->import->iv_index = iv_index;
1710         req->import->unicast = unicast;
1711
1712         req->type = REQUEST_TYPE_IMPORT;
1713
1714         send_managed_objects_request(sender, app_root, req);
1715 }
1716
1717 void node_create(const char *app_root, const char *sender, const uint8_t *uuid,
1718                                         node_ready_func_t cb, void *user_data)
1719 {
1720         struct managed_obj_request *req;
1721
1722         l_debug("");
1723
1724         req = l_new(struct managed_obj_request, 1);
1725         req->node = node_new(uuid);
1726         req->ready_cb = cb;
1727         req->pending_msg = user_data;
1728         req->type = REQUEST_TYPE_CREATE;
1729
1730         send_managed_objects_request(sender, app_root, req);
1731 }
1732
1733 static void build_element_config(void *a, void *b)
1734 {
1735         struct node_element *ele = a;
1736         struct l_dbus_message_builder *builder = b;
1737
1738         l_debug("Element %u", ele->idx);
1739
1740         l_dbus_message_builder_enter_struct(builder, "ya(qa{sv})");
1741
1742         /* Element index */
1743         l_dbus_message_builder_append_basic(builder, 'y', &ele->idx);
1744
1745         l_dbus_message_builder_enter_array(builder, "(qa{sv})");
1746
1747         /* Iterate over models */
1748         l_queue_foreach(ele->models, mesh_model_build_config, builder);
1749
1750         l_dbus_message_builder_leave_array(builder);
1751
1752         l_dbus_message_builder_leave_struct(builder);
1753 }
1754
1755 void node_build_attach_reply(struct mesh_node *node,
1756                                                 struct l_dbus_message *reply)
1757 {
1758         struct l_dbus_message_builder *builder;
1759
1760         builder = l_dbus_message_builder_new(reply);
1761
1762         /* Node object path */
1763         l_dbus_message_builder_append_basic(builder, 'o', node->obj_path);
1764
1765         /* Array of element configurations "a*/
1766         l_dbus_message_builder_enter_array(builder, "(ya(qa{sv}))");
1767         l_queue_foreach(node->elements, build_element_config, builder);
1768         l_dbus_message_builder_leave_array(builder);
1769         l_dbus_message_builder_finalize(builder);
1770         l_dbus_message_builder_destroy(builder);
1771 }
1772
1773 static bool parse_send_options(struct l_dbus_message_iter *itr,
1774                                                 struct send_options *opts)
1775 {
1776         const char *key;
1777         struct l_dbus_message_iter var;
1778
1779         opts->segmented = false;
1780         opts->vendor_id = SIG_VENDOR;
1781
1782         while (l_dbus_message_iter_next_entry(itr, &key, &var)) {
1783                 if (!strcmp(key, "ForceSegmented")) {
1784                         if (!l_dbus_message_iter_get_variant(&var, "b",
1785                                                         &opts->segmented))
1786                                 return false;
1787                 }
1788
1789                 if (!strcmp(key, "Vendor")) {
1790                         if (!l_dbus_message_iter_get_variant(&var, "q",
1791                                                         &opts->vendor_id))
1792                                 return false;
1793                 }
1794         }
1795
1796         return true;
1797 }
1798
1799 static struct l_dbus_message *send_call(struct l_dbus *dbus,
1800                                                 struct l_dbus_message *msg,
1801                                                 void *user_data)
1802 {
1803         struct mesh_node *node = user_data;
1804         const char *sender, *ele_path;
1805         struct l_dbus_message_iter dict, iter_data;
1806         struct send_options opts;
1807         struct node_element *ele;
1808         uint16_t dst, app_idx, net_idx, src;
1809         uint8_t *data;
1810         uint32_t len;
1811
1812         l_debug("Send");
1813
1814         sender = l_dbus_message_get_sender(msg);
1815
1816         if (strcmp(sender, node->owner))
1817                 return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);
1818
1819         if (!l_dbus_message_get_arguments(msg, "oqqa{sv}ay", &ele_path, &dst,
1820                                                 &app_idx, &dict, &iter_data))
1821                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
1822
1823         ele = l_queue_find(node->elements, match_element_path, ele_path);
1824         if (!ele)
1825                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
1826                                                         "Element not found");
1827
1828         if (!parse_send_options(&dict, &opts))
1829                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
1830
1831         src = node_get_primary(node) + ele->idx;
1832
1833         if (!l_dbus_message_iter_get_fixed_array(&iter_data, &data, &len) ||
1834                                         !len || len > MAX_MSG_LEN)
1835                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
1836                                                         "Incorrect data");
1837
1838         if (app_idx & ~APP_IDX_MASK)
1839                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
1840                                                 "Invalid key index");
1841
1842         net_idx = appkey_net_idx(node_get_net(node), app_idx);
1843         if (net_idx == NET_IDX_INVALID)
1844                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
1845                                                         "Key not found");
1846
1847         if (!mesh_model_send(node, src, dst, app_idx, net_idx, DEFAULT_TTL,
1848                                                 opts.segmented, len, data))
1849                 return dbus_error(msg, MESH_ERROR_FAILED, NULL);
1850
1851         return l_dbus_message_new_method_return(msg);
1852 }
1853
1854 static struct l_dbus_message *dev_key_send_call(struct l_dbus *dbus,
1855                                                 struct l_dbus_message *msg,
1856                                                 void *user_data)
1857 {
1858         struct mesh_node *node = user_data;
1859         const char *sender, *ele_path;
1860         struct l_dbus_message_iter iter_data, dict;
1861         struct send_options opts;
1862         struct node_element *ele;
1863         uint16_t dst, app_idx, net_idx, src;
1864         bool remote;
1865         uint8_t *data;
1866         uint32_t len;
1867
1868         l_debug("DevKeySend");
1869
1870         sender = l_dbus_message_get_sender(msg);
1871
1872         if (strcmp(sender, node->owner))
1873                 return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);
1874
1875         if (!l_dbus_message_get_arguments(msg, "oqbqa{sv}ay", &ele_path, &dst,
1876                                         &remote, &net_idx, &dict, &iter_data))
1877                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
1878
1879         /* Loopbacks to local servers must use *remote* addressing */
1880         if (!remote && mesh_net_is_local_address(node->net, dst, 1))
1881                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
1882
1883         ele = l_queue_find(node->elements, match_element_path, ele_path);
1884         if (!ele)
1885                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
1886                                                         "Element not found");
1887
1888         if (!parse_send_options(&dict, &opts))
1889                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
1890
1891         src = node_get_primary(node) + ele->idx;
1892
1893         if (!l_dbus_message_iter_get_fixed_array(&iter_data, &data, &len) ||
1894                                                 !len || len > MAX_MSG_LEN)
1895                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
1896                                                         "Incorrect data");
1897
1898         app_idx = remote ? APP_IDX_DEV_REMOTE : APP_IDX_DEV_LOCAL;
1899         if (!mesh_model_send(node, src, dst, app_idx, net_idx, DEFAULT_TTL,
1900                                                 opts.segmented, len, data))
1901                 return dbus_error(msg, MESH_ERROR_NOT_FOUND, NULL);
1902
1903         return l_dbus_message_new_method_return(msg);
1904 }
1905
1906 static struct l_dbus_message *add_netkey_call(struct l_dbus *dbus,
1907                                                 struct l_dbus_message *msg,
1908                                                 void *user_data)
1909 {
1910         struct mesh_node *node = user_data;
1911         const char *sender, *ele_path;
1912         struct node_element *ele;
1913         uint16_t dst, sub_idx, net_idx, src;
1914         bool update;
1915         struct keyring_net_key key;
1916         uint8_t data[20];
1917
1918         l_debug("AddNetKey");
1919
1920         sender = l_dbus_message_get_sender(msg);
1921
1922         if (strcmp(sender, node->owner))
1923                 return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);
1924
1925         if (!l_dbus_message_get_arguments(msg, "oqqqb", &ele_path, &dst,
1926                                                 &sub_idx, &net_idx, &update))
1927                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
1928
1929         ele = l_queue_find(node->elements, match_element_path, ele_path);
1930         if (!ele)
1931                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
1932                                                         "Element not found");
1933
1934         src = node_get_primary(node) + ele->idx;
1935
1936         if (!keyring_get_net_key(node, sub_idx, &key))
1937                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
1938                                                         "NetKey not found");
1939
1940         if (!update) {
1941                 l_put_be16(OP_NETKEY_ADD, data);
1942
1943                 if (key.phase != KEY_REFRESH_PHASE_TWO)
1944                         memcpy(data + 4, key.old_key, 16);
1945                 else
1946                         memcpy(data + 4, key.new_key, 16);
1947         } else {
1948                 if (key.phase != KEY_REFRESH_PHASE_ONE)
1949                         return dbus_error(msg, MESH_ERROR_FAILED,
1950                                                         "Cannot update");
1951                 l_put_be16(OP_NETKEY_UPDATE, data);
1952                 memcpy(data + 4, key.new_key, 16);
1953         }
1954
1955         l_put_le16(sub_idx, &data[2]);
1956
1957         if (!mesh_model_send(node, src, dst, APP_IDX_DEV_REMOTE, net_idx,
1958                                                 DEFAULT_TTL, false, 20, data))
1959                 return dbus_error(msg, MESH_ERROR_NOT_FOUND, NULL);
1960
1961         return l_dbus_message_new_method_return(msg);
1962 }
1963
1964 static struct l_dbus_message *add_appkey_call(struct l_dbus *dbus,
1965                                                 struct l_dbus_message *msg,
1966                                                 void *user_data)
1967 {
1968         struct mesh_node *node = user_data;
1969         const char *sender, *ele_path;
1970         struct node_element *ele;
1971         uint16_t dst, app_idx, net_idx, src;
1972         bool update;
1973         struct keyring_net_key net_key;
1974         struct keyring_app_key app_key;
1975         uint8_t data[20];
1976
1977         l_debug("AddAppKey");
1978
1979         sender = l_dbus_message_get_sender(msg);
1980
1981         if (strcmp(sender, node->owner))
1982                 return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);
1983
1984         if (!l_dbus_message_get_arguments(msg, "oqqqb", &ele_path, &dst,
1985                                                 &app_idx, &net_idx, &update))
1986                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
1987
1988         ele = l_queue_find(node->elements, match_element_path, ele_path);
1989         if (!ele)
1990                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
1991                                                         "Element not found");
1992
1993         src = node_get_primary(node) + ele->idx;
1994
1995         if (!keyring_get_app_key(node, app_idx, &app_key))
1996                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
1997                                                         "AppKey not found");
1998
1999         if (!keyring_get_net_key(node, app_key.net_idx, &net_key)) {
2000                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
2001                                                 "Bound NetKey not found");
2002         }
2003
2004         if (!update) {
2005                 data[0] = OP_APPKEY_ADD;
2006                 if (net_key.phase != KEY_REFRESH_PHASE_TWO)
2007                         memcpy(data + 4, app_key.old_key, 16);
2008                 else
2009                         memcpy(data + 4, app_key.new_key, 16);
2010         } else {
2011                 if (net_key.phase != KEY_REFRESH_PHASE_ONE)
2012                         return dbus_error(msg, MESH_ERROR_FAILED,
2013                                                         "Cannot update");
2014                 data[0] = OP_APPKEY_UPDATE;
2015                 memcpy(data + 4, app_key.new_key, 16);
2016         }
2017
2018         /* Pack bound NetKey and AppKey into 3 octets */
2019         data[1] = app_key.net_idx;
2020         data[2] = ((app_key.net_idx >> 8) & 0xf) | ((app_idx << 4) & 0xf0);
2021         data[3] = app_idx >> 4;
2022
2023         if (!mesh_model_send(node, src, dst, APP_IDX_DEV_REMOTE, net_idx,
2024                                                 DEFAULT_TTL, false, 20, data))
2025                 return dbus_error(msg, MESH_ERROR_NOT_FOUND, NULL);
2026
2027         return l_dbus_message_new_method_return(msg);
2028 }
2029
2030 static struct l_dbus_message *publish_call(struct l_dbus *dbus,
2031                                                 struct l_dbus_message *msg,
2032                                                 void *user_data)
2033 {
2034         struct mesh_node *node = user_data;
2035         const char *sender, *ele_path;
2036         struct l_dbus_message_iter iter_data, dict;
2037         uint16_t mod_id, src;
2038         struct send_options opts;
2039         struct node_element *ele;
2040         uint8_t *data;
2041         uint32_t len, id;
2042         int result;
2043
2044         l_debug("Publish");
2045
2046         sender = l_dbus_message_get_sender(msg);
2047
2048         if (strcmp(sender, node->owner))
2049                 return dbus_error(msg, MESH_ERROR_NOT_AUTHORIZED, NULL);
2050
2051         if (!l_dbus_message_get_arguments(msg, "oqa{sv}ay", &ele_path, &mod_id,
2052                                                         &dict, &iter_data))
2053                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
2054
2055         ele = l_queue_find(node->elements, match_element_path, ele_path);
2056         if (!ele)
2057                 return dbus_error(msg, MESH_ERROR_NOT_FOUND,
2058                                                         "Element not found");
2059
2060         if (!parse_send_options(&dict, &opts))
2061                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS, NULL);
2062
2063         src = node_get_primary(node) + ele->idx;
2064
2065         if (!l_dbus_message_iter_get_fixed_array(&iter_data, &data, &len) ||
2066                                         !len || len > MAX_MSG_LEN)
2067                 return dbus_error(msg, MESH_ERROR_INVALID_ARGS,
2068                                                         "Incorrect data");
2069
2070         id = SET_ID(opts.vendor_id, mod_id);
2071
2072         result = mesh_model_publish(node, id, src, opts.segmented, len, data);
2073
2074         if (result != MESH_ERROR_NONE)
2075                 return dbus_error(msg, result, NULL);
2076
2077         return l_dbus_message_new_method_return(msg);
2078 }
2079
2080 static bool features_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
2081                                         struct l_dbus_message_builder *builder,
2082                                         void *user_data)
2083 {
2084         struct mesh_node *node = user_data;
2085         uint8_t friend = node_friend_mode_get(node);
2086         uint8_t lpn = node_lpn_mode_get(node);
2087         uint8_t proxy = node_proxy_mode_get(node);
2088         uint8_t count;
2089         uint16_t interval;
2090         uint8_t relay = node_relay_mode_get(node, &count, &interval);
2091
2092         l_dbus_message_builder_enter_array(builder, "{sv}");
2093
2094         if (friend != MESH_MODE_UNSUPPORTED)
2095                 dbus_append_dict_entry_basic(builder, "Friend", "b", &friend);
2096
2097         if (lpn != MESH_MODE_UNSUPPORTED)
2098                 dbus_append_dict_entry_basic(builder, "LowPower", "b", &lpn);
2099
2100         if (proxy != MESH_MODE_UNSUPPORTED)
2101                 dbus_append_dict_entry_basic(builder, "Proxy", "b", &proxy);
2102
2103         if (relay != MESH_MODE_UNSUPPORTED)
2104                 dbus_append_dict_entry_basic(builder, "Relay", "b", &relay);
2105
2106         l_dbus_message_builder_leave_array(builder);
2107
2108         return true;
2109 }
2110
2111 static bool beacon_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
2112                                         struct l_dbus_message_builder *builder,
2113                                         void *user_data)
2114 {
2115         struct mesh_node *node = user_data;
2116         bool beacon_mode = node_beacon_mode_get(node) == MESH_MODE_ENABLED;
2117
2118         l_dbus_message_builder_append_basic(builder, 'b', &beacon_mode);
2119
2120         return true;
2121 }
2122
2123 static bool ivupdate_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
2124                                         struct l_dbus_message_builder *builder,
2125                                         void *user_data)
2126 {
2127         struct mesh_node *node = user_data;
2128         struct mesh_net *net = node_get_net(node);
2129         uint8_t flags;
2130         uint32_t iv_index;
2131         bool ivu;
2132
2133         mesh_net_get_snb_state(net, &flags, &iv_index);
2134
2135         ivu = flags & IV_INDEX_UPDATE;
2136
2137         l_dbus_message_builder_append_basic(builder, 'b', &ivu);
2138
2139         return true;
2140 }
2141
2142 static bool ivindex_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
2143                                         struct l_dbus_message_builder *builder,
2144                                         void *user_data)
2145 {
2146         struct mesh_node *node = user_data;
2147         struct mesh_net *net = node_get_net(node);
2148         uint8_t flags;
2149         uint32_t iv_index;
2150
2151         mesh_net_get_snb_state(net, &flags, &iv_index);
2152
2153         l_dbus_message_builder_append_basic(builder, 'u', &iv_index);
2154
2155         return true;
2156 }
2157
2158 static bool seq_num_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
2159                                 struct l_dbus_message_builder *builder,
2160                                 void *user_data)
2161 {
2162         struct mesh_node *node = user_data;
2163         struct mesh_net *net = node_get_net(node);
2164         uint32_t seq_nr = mesh_net_get_seq_num(net);
2165
2166         l_dbus_message_builder_append_basic(builder, 'u', &seq_nr);
2167
2168         return true;
2169 }
2170
2171 static bool lastheard_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
2172                                         struct l_dbus_message_builder *builder,
2173                                         void *user_data)
2174 {
2175         struct mesh_node *node = user_data;
2176         struct mesh_net *net = node_get_net(node);
2177         struct timeval now;
2178         uint32_t last_heard;
2179
2180         gettimeofday(&now, NULL);
2181
2182         last_heard = now.tv_sec - mesh_net_get_instant(net);
2183
2184         l_dbus_message_builder_append_basic(builder, 'u', &last_heard);
2185
2186         return true;
2187
2188 }
2189
2190 static bool addresses_getter(struct l_dbus *dbus, struct l_dbus_message *msg,
2191                                         struct l_dbus_message_builder *builder,
2192                                         void *user_data)
2193 {
2194         struct mesh_node *node = user_data;
2195         const struct l_queue_entry *entry;
2196
2197         l_dbus_message_builder_enter_array(builder, "q");
2198
2199         entry = l_queue_get_entries(node->elements);
2200         for (; entry; entry = entry->next) {
2201                 const struct node_element *ele = entry->data;
2202                 uint16_t address = node->primary + ele->idx;
2203
2204                 l_dbus_message_builder_append_basic(builder, 'q', &address);
2205         }
2206
2207         l_dbus_message_builder_leave_array(builder);
2208
2209         return true;
2210 }
2211
2212 static void setup_node_interface(struct l_dbus_interface *iface)
2213 {
2214         l_dbus_interface_method(iface, "Send", 0, send_call, "", "oqqa{sv}ay",
2215                                                 "element_path", "destination",
2216                                                 "key_index", "options", "data");
2217         l_dbus_interface_method(iface, "DevKeySend", 0, dev_key_send_call, "",
2218                                                 "oqbqa{sv}ay", "element_path",
2219                                                 "destination", "remote",
2220                                                 "net_index", "options", "data");
2221         l_dbus_interface_method(iface, "AddNetKey", 0, add_netkey_call, "",
2222                                         "oqqqb", "element_path", "destination",
2223                                         "subnet_index", "net_index", "update");
2224         l_dbus_interface_method(iface, "AddAppKey", 0, add_appkey_call, "",
2225                                         "oqqqb", "element_path", "destination",
2226                                         "app_index", "net_index", "update");
2227         l_dbus_interface_method(iface, "Publish", 0, publish_call, "",
2228                                         "oqa{sv}ay", "element_path", "model_id",
2229                                                         "options", "data");
2230         l_dbus_interface_property(iface, "Features", 0, "a{sv}",
2231                                                         features_getter, NULL);
2232         l_dbus_interface_property(iface, "Beacon", 0, "b", beacon_getter, NULL);
2233         l_dbus_interface_property(iface, "IvUpdate", 0, "b", ivupdate_getter,
2234                                                                         NULL);
2235         l_dbus_interface_property(iface, "IvIndex", 0, "u", ivindex_getter,
2236                                                                         NULL);
2237         l_dbus_interface_property(iface, "SequenceNumber", 0, "u",
2238                                                         seq_num_getter, NULL);
2239         l_dbus_interface_property(iface, "SecondsSinceLastHeard", 0, "u",
2240                                         lastheard_getter, NULL);
2241         l_dbus_interface_property(iface, "Addresses", 0, "aq", addresses_getter,
2242                                                                         NULL);
2243 }
2244
2245 void node_property_changed(struct mesh_node *node, const char *property)
2246 {
2247         struct l_dbus *bus = dbus_get_bus();
2248
2249         if (bus && node->obj_path)
2250                 l_dbus_property_changed(dbus_get_bus(), node->obj_path,
2251                                                 MESH_NODE_INTERFACE, property);
2252 }
2253
2254 bool node_dbus_init(struct l_dbus *bus)
2255 {
2256         if (!l_dbus_register_interface(bus, MESH_NODE_INTERFACE,
2257                                                 setup_node_interface,
2258                                                 NULL, false)) {
2259                 l_info("Unable to register %s interface", MESH_NODE_INTERFACE);
2260                 return false;
2261         }
2262
2263         return true;
2264 }
2265
2266 const char *node_get_owner(struct mesh_node *node)
2267 {
2268         return node->owner;
2269 }
2270
2271 const char *node_get_element_path(struct mesh_node *node, uint8_t ele_idx)
2272 {
2273         struct node_element *ele;
2274
2275         ele = l_queue_find(node->elements, match_element_idx,
2276                                                         L_UINT_TO_PTR(ele_idx));
2277
2278         if (!ele)
2279                 return NULL;
2280
2281         return ele->path;
2282 }
2283
2284 bool node_add_pending_local(struct mesh_node *node, void *prov_node_info)
2285 {
2286         struct mesh_prov_node_info *info = prov_node_info;
2287         bool kr = !!(info->flags & PROV_FLAG_KR);
2288         bool ivu = !!(info->flags & PROV_FLAG_IVU);
2289
2290         return add_local_node(node, info->unicast, kr, ivu, info->iv_index,
2291                         info->device_key, info->net_index, info->net_key);
2292 }
2293
2294 struct mesh_config *node_config_get(struct mesh_node *node)
2295 {
2296         return node->cfg;
2297 }
2298
2299 const char *node_get_storage_dir(struct mesh_node *node)
2300 {
2301         return node->storage_dir;
2302 }
2303
2304 const char *node_get_app_path(struct mesh_node *node)
2305 {
2306         if (!node)
2307                 return NULL;
2308
2309         return node->app_path;
2310 }
2311
2312 struct mesh_net *node_get_net(struct mesh_node *node)
2313 {
2314         return node->net;
2315 }
2316
2317 struct mesh_agent *node_get_agent(struct mesh_node *node)
2318 {
2319         return node->agent;
2320 }
2321
2322 bool node_load_from_storage(const char *storage_dir)
2323 {
2324         return mesh_config_load_nodes(storage_dir, init_from_storage, NULL);
2325 }
2326
2327 /*
2328  * This is called for a new node that:
2329  *         - has been created as a result of successful completion of Join()
2330  *           or Create() or Import() methods
2331  *     and
2332  *         - has been confirmed via successful token delivery to the application
2333  *
2334  * After a node has been created, the information gathered during initial
2335  * GetManagedObjects() call is cleared. The subsequent call to Attach() would
2336  * verify node's integrity and re-initialize node's D-Bus resources.
2337  */
2338 void node_finalize_new_node(struct mesh_node *node, struct mesh_io *io)
2339 {
2340         if (!node)
2341                 return;
2342
2343         free_node_dbus_resources(node);
2344         mesh_agent_remove(node->agent);
2345         node->agent = NULL;
2346
2347         node->busy = false;
2348
2349         /* Register callback for the node's io */
2350         attach_io(node, io);
2351 }