1 /*
2  * SPDX-FileCopyrightText: 2018 Intel Corporation
3  * SPDX-FileContributor: 2018-2021 Espressif Systems (Shanghai) CO LTD
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <errno.h>
9 #include <string.h>
10 
11 #include "mesh.h"
12 #include "crypto.h"
13 #include "transport.h"
14 #include "access.h"
15 #include "foundation.h"
16 #include "proxy_server.h"
17 #include "cfg_srv.h"
18 #include "mesh_common.h"
19 #include "settings_nvs.h"
20 #include "settings.h"
21 #include "settings_uid.h"
22 #include "provisioner_main.h"
23 #include "provisioner_prov.h"
24 
25 /* BLE Mesh NVS Key and corresponding data struct.
26  * Note: The length of nvs key must be <= 15.
27  *       "xxxx" (2 octet) means the rpl_src, net_idx, app_idx, model_key, etc.
28  *       Model model_key is a combination "elem_idx << 8 | model_idx".
29  * key: "mesh/net"    -> write/read to set/get NET data
30  * key: "mesh/iv"     -> write/read to set/get IV data
31  * key: "mesh/seq"    -> write/read to set/get SEQ data
32  * key: "mesh/hb_pub" -> write/read to set/get CFG HB_PUB data
33  * key: "mesh/cfg"    -> write/read to set/get CFG data
34  * key: "mesh/rpl"    -> write/read to set/get all RPL src.
35  *      key: "mesh/rpl/xxxx" -> write/read to set/get the "xxxx" RPL data
36  * key: "mesh/netkey" -> write/read to set/get all NetKey Indexes
37  *      key: "mesh/nk/xxxx" -> write/read to set/get the "xxxx" NetKey data
38  * key: "mesh/appkey" -> write/read to set/get all AppKey Indexes
39  *      key: "mesh/ak/xxxx" -> write/read to set/get the "xxxx" AppKey data
40  * key: "mesh/sig" -> write/read to set/get all SIG MODEL model_keys.
41  *      key: "mesh/s/xxxx/b"  -> write/read to set/get SIG MODEL Bind AppKey List
42  *      key: "mesh/s/xxxx/s" -> write/read to set/get SIG MODEL Subscription List
43  *      key: "mesh/s/xxxx/p" -> write/read to set/get SIG MODEL Publication
44  * key: "mesh/vnd" -> write/read to set/get all VENDOR MODEL model_keys.
45  *      key: "mesh/v/xxxx/b"  -> write/read to set/get VENDOR MODEL Bind AppKey List
46  *      key: "mesh/v/xxxx/s" -> write/read to set/get VENDOR MODEL Subscription List
47  *      key: "mesh/v/xxxx/p" -> write/read to set/get VENDOR MODEL Publication
48  * key: "mesh/vaddr" -> write/read to set/get all virtual addresses
49  *      key: "mesh/va/xxxx" -> write/read to set/get the "xxxx" virtual address
50  */
51 
52 #if CONFIG_BLE_MESH_SETTINGS
53 
54 /* Tracking of what storage changes are pending for App and Net Keys. We
55  * track this in a separate array here instead of within the respective
56  * bt_mesh_app_key and bt_mesh_subnet structs themselves, since once a key
57  * gets deleted its struct becomes invalid and may be reused for other keys.
58  */
59 static struct key_update {
60     uint16_t key_idx:12, /* AppKey or NetKey Index */
61              valid:1,    /* 1 if this entry is valid, 0 if not */
62              app_key:1,  /* 1 if this is an AppKey, 0 if a NetKey */
63              clear:1;    /* 1 if key needs clearing, 0 if storing */
64 } key_updates[CONFIG_BLE_MESH_APP_KEY_COUNT + CONFIG_BLE_MESH_SUBNET_COUNT];
65 
66 static struct k_delayed_work pending_store;
67 static void store_pending(struct k_work *work);
68 
69 /* Mesh network storage information */
70 struct net_val {
71     uint16_t primary_addr;
72     uint8_t  dev_key[16];
73 } __packed;
74 
75 /* Sequence number storage */
76 struct seq_val {
77     uint8_t val[3];
78 } __packed;
79 
80 /* Heartbeat Publication storage */
81 struct hb_pub_val {
82     uint16_t dst;
83     uint8_t  period;
84     uint8_t  ttl;
85     uint16_t feat;
86     uint16_t net_idx:12,
87              indefinite:1;
88 };
89 
90 /* Miscellaneous configuration server model states */
91 struct cfg_val {
92     uint8_t net_transmit;
93     uint8_t relay;
94     uint8_t relay_retransmit;
95     uint8_t beacon;
96     uint8_t gatt_proxy;
97     uint8_t frnd;
98     uint8_t default_ttl;
99 };
100 
101 /* IV Index & IV Update storage */
102 struct iv_val {
103     uint32_t iv_index;
104     uint8_t  iv_update:1,
105              iv_duration:7;
106 } __packed;
107 
108 /* Replay Protection List storage */
109 struct rpl_val {
110     uint32_t seq:24,
111              old_iv:1;
112 };
113 
114 /* NetKey storage information */
115 struct net_key_val {
116     uint8_t kr_flag:1,
117             kr_phase:7;
118     uint8_t val[2][16];
119 } __packed;
120 
121 /* AppKey storage information */
122 struct app_key_val {
123     uint16_t net_idx;
124     bool     updated;
125     uint8_t  val[2][16];
126 } __packed;
127 
128 struct mod_pub_val {
129     uint16_t addr;
130     uint16_t key;
131     uint8_t  ttl;
132     uint8_t  retransmit;
133     uint8_t  period;
134     uint8_t  period_div:4,
135              cred:1;
136 };
137 
138 /* Virtual Address information */
139 struct va_val {
140     uint16_t ref;
141     uint16_t addr;
142     uint8_t  uuid[16];
143 } __packed;
144 
145 /* We need this so we don't overwrite app-hardcoded values in case FCB
146  * contains a history of changes but then has a NULL at the end.
147  */
148 static struct {
149     bool valid;
150     struct cfg_val cfg;
151 } stored_cfg;
152 
153 struct prov_info {
154     uint16_t primary_addr;
155     uint16_t alloc_addr;
156 };
157 
158 struct node_info {
159     uint8_t  addr[6];
160     uint8_t  addr_type;
161     uint8_t  dev_uuid[16];
162     uint16_t oob_info;
163     uint16_t unicast_addr;
164     uint8_t  element_num;
165     uint16_t net_idx;
166     uint8_t  flags;
167     uint32_t iv_index;
168     uint8_t  dev_key[16];
169 } __packed;
170 
171 static bt_mesh_mutex_t settings_lock;
172 
bt_mesh_settings_mutex_new(void)173 static inline void bt_mesh_settings_mutex_new(void)
174 {
175     if (settings_lock.mutex == NULL) {
176         bt_mesh_mutex_create(&settings_lock);
177     }
178 }
179 
180 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_settings_mutex_free(void)181 static inline void bt_mesh_settings_mutex_free(void)
182 {
183     bt_mesh_mutex_free(&settings_lock);
184 }
185 #endif /* CONFIG_BLE_MESH_DEINIT */
186 
bt_mesh_settings_lock(void)187 void bt_mesh_settings_lock(void)
188 {
189     bt_mesh_mutex_lock(&settings_lock);
190 }
191 
bt_mesh_settings_unlock(void)192 void bt_mesh_settings_unlock(void)
193 {
194     bt_mesh_mutex_unlock(&settings_lock);
195 }
196 
role_set(const char * name)197 static int role_set(const char *name)
198 {
199     bool exist = false;
200     int err = 0;
201 
202     BT_DBG("%s", __func__);
203 
204     err = bt_mesh_load_core_settings(name, (uint8_t *)bt_mesh.flags, sizeof(bt_mesh.flags), &exist);
205     if (err) {
206         BT_ERR("Failed to load mesh device role");
207         return err;
208     }
209 
210     if (exist == false) {
211 #if CONFIG_BLE_MESH_SETTINGS_BACKWARD_COMPATIBILITY
212         if (IS_ENABLED(CONFIG_BLE_MESH_NODE) &&
213             !IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER)) {
214             bt_mesh_atomic_set_bit(bt_mesh.flags, BLE_MESH_NODE);
215         }
216 #else
217         return 0;
218 #endif
219     }
220 
221     return 0;
222 }
223 
net_set(const char * name)224 static int net_set(const char *name)
225 {
226     struct net_val net = {0};
227     bool exist = false;
228     int err = 0;
229 
230     BT_DBG("%s", __func__);
231 
232     err = bt_mesh_load_core_settings(name, (uint8_t *)&net, sizeof(net), &exist);
233     if (err) {
234         BT_ERR("Failed to load node net info");
235         memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key));
236         bt_mesh_comp_unprovision();
237         return 0;
238     }
239 
240     if (exist == false) {
241         return 0;
242     }
243 
244     memcpy(bt_mesh.dev_key, net.dev_key, sizeof(bt_mesh.dev_key));
245     bt_mesh_comp_provision(net.primary_addr);
246 
247     BT_INFO("Restored Primary Address 0x%04x", net.primary_addr);
248     BT_INFO("Restored DevKey %s", bt_hex(bt_mesh.dev_key, 16));
249 
250     return 0;
251 }
252 
iv_set(const char * name)253 static int iv_set(const char *name)
254 {
255     struct iv_val iv = {0};
256     bool exist = false;
257     int err = 0;
258 
259     BT_DBG("%s", __func__);
260 
261     err = bt_mesh_load_core_settings(name, (uint8_t *)&iv, sizeof(iv), &exist);
262     if (err) {
263         BT_ERR("Failed to load iv_index");
264         bt_mesh.iv_index = 0U;
265         bt_mesh_atomic_clear_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS);
266         return 0;
267     }
268 
269     if (exist == false) {
270         return 0;
271     }
272 
273     bt_mesh.iv_index = iv.iv_index;
274     bt_mesh_atomic_set_bit_to(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS, iv.iv_update);
275     bt_mesh.ivu_duration = iv.iv_duration;
276 
277     BT_INFO("Restored IV Index 0x%08x (IV Update Flag %u) duration %u hours",
278            iv.iv_index, iv.iv_update, iv.iv_duration);
279 
280     return 0;
281 }
282 
seq_set(const char * name)283 static int seq_set(const char *name)
284 {
285     struct seq_val seq = {0};
286     bool exist = false;
287     int err = 0;
288 
289     BT_DBG("%s", __func__);
290 
291     err = bt_mesh_load_core_settings(name, (uint8_t *)&seq, sizeof(seq), &exist);
292     if (err) {
293         BT_ERR("Failed to load sequence number");
294         bt_mesh.seq = 0U;
295         return 0;
296     }
297 
298     if (exist == false) {
299         return 0;
300     }
301 
302     bt_mesh.seq = sys_get_le24(seq.val);
303 
304 #if CONFIG_BLE_MESH_SEQ_STORE_RATE > 0
305     /* Make sure we have a large enough sequence number. We
306      * subtract 1 so that the first transmission causes a write
307      * to the settings storage.
308      */
309     bt_mesh.seq += (CONFIG_BLE_MESH_SEQ_STORE_RATE -
310                     (bt_mesh.seq % CONFIG_BLE_MESH_SEQ_STORE_RATE));
311     bt_mesh.seq--;
312 #endif
313 
314     BT_INFO("Restored Sequence Number 0x%06x", bt_mesh.seq);
315 
316     return 0;
317 }
318 
rpl_find(uint16_t src)319 static struct bt_mesh_rpl *rpl_find(uint16_t src)
320 {
321     int i;
322 
323     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
324         if (bt_mesh.rpl[i].src == src) {
325             return &bt_mesh.rpl[i];
326         }
327     }
328 
329     return NULL;
330 }
331 
rpl_alloc(uint16_t src)332 static struct bt_mesh_rpl *rpl_alloc(uint16_t src)
333 {
334     int i;
335 
336     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
337         if (bt_mesh.rpl[i].src == BLE_MESH_ADDR_UNASSIGNED) {
338             bt_mesh.rpl[i].src = src;
339             return &bt_mesh.rpl[i];
340         }
341     }
342 
343     return NULL;
344 }
345 
rpl_set(const char * name)346 static int rpl_set(const char *name)
347 {
348     struct net_buf_simple *buf = NULL;
349     struct bt_mesh_rpl *entry = NULL;
350     struct rpl_val rpl = {0};
351     char get[16] = {'\0'};
352     bool exist = false;
353     size_t length = 0U;
354     int err = 0;
355     int i;
356 
357     BT_DBG("%s", __func__);
358 
359     buf = bt_mesh_get_core_settings_item(name);
360     if (!buf) {
361         return 0;
362     }
363 
364     length = buf->len;
365 
366     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
367         uint16_t src = net_buf_simple_pull_le16(buf);
368 
369         if (!BLE_MESH_ADDR_IS_UNICAST(src)) {
370             BT_ERR("Invalid source address 0x%04x", src);
371             continue;
372         }
373 
374         sprintf(get, "mesh/rpl/%04x", src);
375 
376         err = bt_mesh_load_core_settings(get, (uint8_t *)&rpl, sizeof(rpl), &exist);
377         if (err) {
378             BT_ERR("Failed to load RPL entry 0x%04x", src);
379             continue;
380         }
381 
382         if (exist == false) {
383             continue;
384         }
385 
386         entry = rpl_find(src);
387         if (!entry) {
388             entry = rpl_alloc(src);
389             if (!entry) {
390                 BT_ERR("No space for a new RPL 0x%04x", src);
391                 err = -ENOMEM;
392                 goto free;
393             }
394         }
395 
396         entry->src = src;
397         entry->seq = rpl.seq;
398         entry->old_iv = rpl.old_iv;
399 
400         BT_INFO("Restored RPL entry 0x%04x: seq 0x%06x, old_iv %u", src, rpl.seq, rpl.old_iv);
401     }
402 
403 free:
404     bt_mesh_free_buf(buf);
405     return err;
406 }
407 
subnet_alloc(uint16_t net_idx)408 static struct bt_mesh_subnet *subnet_alloc(uint16_t net_idx)
409 {
410     int i;
411 
412     for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
413         if (bt_mesh.sub[i].net_idx == BLE_MESH_KEY_UNUSED) {
414             bt_mesh.sub[i].net_idx = net_idx;
415             return &bt_mesh.sub[i];
416         }
417     }
418 
419     return NULL;
420 }
421 
net_key_set(const char * name)422 static int net_key_set(const char *name)
423 {
424     struct net_buf_simple *buf = NULL;
425     struct bt_mesh_subnet *sub = NULL;
426     struct net_key_val key = {0};
427     char get[16] = {'\0'};
428     bool exist = false;
429     size_t length = 0U;
430     int err = 0;
431     int i;
432 
433     BT_DBG("%s", __func__);
434 
435     buf = bt_mesh_get_core_settings_item(name);
436     if (!buf) {
437         return 0;
438     }
439 
440     length = buf->len;
441 
442     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
443         uint16_t net_idx = net_buf_simple_pull_le16(buf);
444         sprintf(get, "mesh/nk/%04x", net_idx);
445 
446         err = bt_mesh_load_core_settings(get, (uint8_t *)&key, sizeof(key), &exist);
447         if (err) {
448             BT_ERR("Failed to load NetKey 0x%03x", net_idx);
449             continue;
450         }
451 
452         if (exist == false) {
453             continue;
454         }
455 
456         sub = bt_mesh_subnet_get(net_idx);
457         if (!sub) {
458             sub = subnet_alloc(net_idx);
459             if (!sub) {
460                 BT_ERR("No space for a new subnet 0x%03x", net_idx);
461                 err = -ENOMEM;
462                 goto free;
463             }
464         }
465 
466         sub->net_idx = net_idx;
467         sub->kr_flag = key.kr_flag;
468         sub->kr_phase = key.kr_phase;
469         memcpy(sub->keys[0].net, &key.val[0], 16);
470         memcpy(sub->keys[1].net, &key.val[1], 16);
471 
472         BT_INFO("Restored NetKeyIndex 0x%03x", sub->net_idx);
473         BT_INFO("Restored NetKey %s", bt_hex(sub->keys[0].net, 16));
474     }
475 
476 free:
477     bt_mesh_free_buf(buf);
478     return err;
479 }
480 
app_key_set(const char * name)481 static int app_key_set(const char *name)
482 {
483     struct bt_mesh_app_key *app = NULL;
484     struct bt_mesh_subnet *sub = NULL;
485     struct net_buf_simple *buf = NULL;
486     struct app_key_val key = {0};
487     char get[16] = {'\0'};
488     bool exist = false;
489     size_t length = 0U;
490     int err = 0;
491     int i;
492 
493     BT_DBG("%s", __func__);
494 
495     buf = bt_mesh_get_core_settings_item(name);
496     if (!buf) {
497         return 0;
498     }
499 
500     length = buf->len;
501 
502     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
503         uint16_t app_idx = net_buf_simple_pull_le16(buf);
504         sprintf(get, "mesh/ak/%04x", app_idx);
505 
506         err = bt_mesh_load_core_settings(get, (uint8_t *)&key, sizeof(key), &exist);
507         if (err) {
508             BT_ERR("Failed to load AppKey 0x%03x", app_idx);
509             continue;
510         }
511 
512         if (exist == false) {
513             continue;
514         }
515 
516         sub = bt_mesh_subnet_get(key.net_idx);
517         if (!sub) {
518             BT_ERR("Failed to find subnet 0x%03x", key.net_idx);
519             continue;
520         }
521 
522         app = bt_mesh_app_key_find(app_idx);
523         if (!app) {
524             app = bt_mesh_app_key_alloc(app_idx);
525             if (!app) {
526                 BT_ERR("No space for a new appkey 0x%03x", app_idx);
527                 err = -ENOMEM;
528                 goto free;
529             }
530         }
531 
532         app->net_idx = key.net_idx;
533         app->app_idx = app_idx;
534         app->updated = key.updated;
535         memcpy(app->keys[0].val, key.val[0], 16);
536         memcpy(app->keys[1].val, key.val[1], 16);
537         bt_mesh_app_id(app->keys[0].val, &app->keys[0].id);
538         bt_mesh_app_id(app->keys[1].val, &app->keys[1].id);
539 
540         BT_INFO("Restored AppKeyIndex 0x%03x, NetKeyIndex 0x%03x",
541             app->app_idx, app->net_idx);
542         BT_INFO("Restored AppKey %s", bt_hex(app->keys[0].val, 16));
543     }
544 
545 free:
546     bt_mesh_free_buf(buf);
547     return err;
548 }
549 
hb_pub_set(const char * name)550 static int hb_pub_set(const char *name)
551 {
552     struct bt_mesh_hb_pub *hb_pub = bt_mesh_hb_pub_get();
553     struct hb_pub_val hb_val = {0};
554     bool exist = false;
555     int err = 0;
556 
557     BT_DBG("%s", __func__);
558 
559     if (!hb_pub) {
560         BT_ERR("Invalid heartbeat publication");
561         return -EINVAL;
562     }
563 
564     err = bt_mesh_load_core_settings(name, (uint8_t *)&hb_val, sizeof(hb_val), &exist);
565     if (err) {
566         BT_ERR("Failed to load heartbeat publication");
567         hb_pub->dst = BLE_MESH_ADDR_UNASSIGNED;
568         hb_pub->count = 0U;
569         hb_pub->ttl = 0U;
570         hb_pub->period = 0U;
571         hb_pub->feat = 0U;
572         return 0;
573     }
574 
575     if (exist == false) {
576         return 0;
577     }
578 
579     hb_pub->dst = hb_val.dst;
580     hb_pub->period = hb_val.period;
581     hb_pub->ttl = hb_val.ttl;
582     hb_pub->feat = hb_val.feat;
583     hb_pub->net_idx = hb_val.net_idx;
584     if (hb_val.indefinite) {
585         hb_pub->count = 0xffff;
586     } else {
587         hb_pub->count = 0U;
588     }
589 
590     BT_INFO("Restored Heartbeat Publication, dst 0x%04x, period %d, net_idx 0x%03x",
591             hb_pub->dst, hb_pub->period, hb_pub->net_idx);
592 
593     return 0;
594 }
595 
cfg_set(const char * name)596 static int cfg_set(const char *name)
597 {
598     struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get();
599     struct cfg_val val = {0};
600     bool exist = false;
601     int err = 0;
602 
603     BT_DBG("%s", __func__);
604 
605     if (!cfg) {
606         BT_ERR("Invalid configuration");
607         stored_cfg.valid = false;
608         return -EINVAL;
609     }
610 
611     err = bt_mesh_load_core_settings(name, (uint8_t *)&val, sizeof(val), &exist);
612     if (err) {
613         BT_ERR("Failed to load configuration state");
614         stored_cfg.valid = false;
615         return 0;
616     }
617 
618     if (exist == false) {
619         return 0;
620     }
621 
622     memcpy(&stored_cfg.cfg, &val, sizeof(val));
623     stored_cfg.valid = true;
624 
625     BT_INFO("Restored Configuration, ttl %d, transmit 0x%02x, retransmit 0x%02x",
626             val.default_ttl, val.net_transmit, val.relay_retransmit);
627 
628     return 0;
629 }
630 
model_set_bind(bool vnd,struct bt_mesh_model * model,uint16_t model_key)631 static int model_set_bind(bool vnd, struct bt_mesh_model *model, uint16_t model_key)
632 {
633     char name[16] = {'\0'};
634     bool exist = false;
635     int err = 0;
636     int i;
637 
638     /* Start with empty array regardless of cleared or set value */
639     for (i = 0; i < ARRAY_SIZE(model->keys); i++) {
640         model->keys[i] = BLE_MESH_KEY_UNUSED;
641     }
642 
643     sprintf(name, "mesh/%s/%04x/b", vnd ? "v" : "s", model_key);
644     err = bt_mesh_load_core_settings(name, (uint8_t *)model->keys, sizeof(model->keys), &exist);
645     if (err) {
646         BT_ERR("Failed to load model bound keys");
647         return -EIO;
648     }
649 
650     if (exist == true) {
651         BT_INFO("Restored Model Bound AppKey, index %s", bt_hex(model->keys, sizeof(model->keys)));
652     }
653 
654     return 0;
655 }
656 
model_set_sub(bool vnd,struct bt_mesh_model * model,uint16_t model_key)657 static int model_set_sub(bool vnd, struct bt_mesh_model *model, uint16_t model_key)
658 {
659     char name[16] = {'\0'};
660     bool exist = false;
661     int err = 0;
662     int i;
663 
664     /* Start with empty array regardless of cleared or set value */
665     for (i = 0; i < ARRAY_SIZE(model->groups); i++) {
666         model->groups[i] = BLE_MESH_ADDR_UNASSIGNED;
667     }
668 
669     sprintf(name, "mesh/%s/%04x/s", vnd ? "v" : "s", model_key);
670     err = bt_mesh_load_core_settings(name, (uint8_t *)model->groups, sizeof(model->groups), &exist);
671     if (err) {
672         BT_ERR("Failed to load model subscriptions");
673         return -EIO;
674     }
675 
676     if (exist == true) {
677         BT_INFO("Restored Model Subscription, address %s", bt_hex(model->groups, sizeof(model->groups)));
678     }
679 
680     return 0;
681 }
682 
model_set_pub(bool vnd,struct bt_mesh_model * model,uint16_t model_key)683 static int model_set_pub(bool vnd, struct bt_mesh_model *model, uint16_t model_key)
684 {
685     struct mod_pub_val pub = {0};
686     char name[16] = {'\0'};
687     bool exist = false;
688     int err = 0;
689 
690     if (!model->pub) {
691         BT_INFO("Not support publication, model_id 0x%04x, cid 0x%04x",
692             vnd ? model->vnd.id : model->id, vnd ? model->vnd.company : 0xFFFF);
693         return 0;
694     }
695 
696     sprintf(name, "mesh/%s/%04x/p", vnd ? "v" : "s", model_key);
697     err = bt_mesh_load_core_settings(name, (uint8_t *)&pub, sizeof(pub), &exist);
698     if (err) {
699         BT_ERR("Failed to load model publication");
700         model->pub->addr = BLE_MESH_ADDR_UNASSIGNED;
701         model->pub->key = 0U;
702         model->pub->cred = 0U;
703         model->pub->ttl = 0U;
704         model->pub->period = 0U;
705         model->pub->retransmit = 0U;
706         model->pub->count = 0U;
707         return -EIO;
708     }
709 
710     if (exist == false) {
711         return 0;
712     }
713 
714     model->pub->addr = pub.addr;
715     model->pub->key = pub.key;
716     model->pub->cred = pub.cred;
717     model->pub->ttl = pub.ttl;
718     model->pub->period = pub.period;
719     model->pub->retransmit = pub.retransmit;
720     model->pub->count = 0U;
721 
722     BT_INFO("Restored Model Publication, address 0x%04x, app_idx 0x%03x", pub.addr, pub.key);
723 
724     return 0;
725 }
726 
model_set(bool vnd,const char * name)727 static int model_set(bool vnd, const char *name)
728 {
729     struct bt_mesh_model *model = NULL;
730     struct net_buf_simple *buf = NULL;
731     uint8_t elem_idx = 0U, model_idx = 0U;
732     size_t length = 0U;
733     int i;
734 
735     BT_DBG("%s", __func__);
736 
737     buf = bt_mesh_get_core_settings_item(name);
738     if (!buf) {
739         return 0;
740     }
741 
742     length = buf->len;
743 
744     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
745         uint16_t model_key = net_buf_simple_pull_le16(buf);
746 
747         elem_idx = BLE_MESH_GET_ELEM_IDX(model_key);
748         model_idx = BLE_MESH_GET_MODEL_IDX(model_key);
749 
750         model = bt_mesh_model_get(vnd, elem_idx, model_idx);
751         if (!model) {
752             BT_ERR("%s model not found, elem_idx %u, model_idx %u",
753                 vnd ? "vnd" : "sig", elem_idx, model_idx);
754             continue;
755         }
756 
757         model_set_bind(vnd, model, model_key);
758         model_set_sub(vnd, model, model_key);
759         model_set_pub(vnd, model, model_key);
760     }
761 
762     bt_mesh_free_buf(buf);
763     return 0;
764 }
765 
sig_mod_set(const char * name)766 static int sig_mod_set(const char *name)
767 {
768     return model_set(false, name);
769 }
770 
vnd_mod_set(const char * name)771 static int vnd_mod_set(const char *name)
772 {
773     return model_set(true, name);
774 }
775 
776 #if CONFIG_BLE_MESH_LABEL_COUNT > 0
va_set(const char * name)777 static int va_set(const char *name)
778 {
779     struct net_buf_simple *buf = NULL;
780     struct va_val va = {0};
781     char get[16] = {'\0'};
782     struct label *lab = NULL;
783     size_t length = 0U;
784     bool exist = false;
785     int err = 0;
786     int i;
787 
788     BT_DBG("%s", __func__);
789 
790     buf = bt_mesh_get_core_settings_item(name);
791     if (!buf) {
792         return 0;
793     }
794 
795     length = buf->len;
796 
797     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
798         uint16_t index = net_buf_simple_pull_le16(buf);
799         sprintf(get, "mesh/va/%04x", index);
800 
801         err = bt_mesh_load_core_settings(get, (uint8_t *)&va, sizeof(va), &exist);
802         if (err) {
803             BT_ERR("Failed to load virtual address 0x%04x", index);
804             continue;
805         }
806 
807         if (exist == false) {
808             continue;
809         }
810 
811         if (va.ref == 0) {
812             BT_DBG("Ignore virtual address %s with ref = 0", get);
813             continue;
814         }
815 
816         lab = get_label(index);
817         if (lab == NULL) {
818             BT_WARN("Out of labels buffers");
819             err = -ENOBUFS;
820             goto free;
821         }
822 
823         memcpy(lab->uuid, va.uuid, 16);
824         lab->addr = va.addr;
825         lab->ref = va.ref;
826 
827         BT_INFO("Restored Virtual Address 0x%04x, ref 0x%04x", index, lab->ref);
828     }
829 
830 free:
831     bt_mesh_free_buf(buf);
832     return err;
833 }
834 #endif
835 
836 #if CONFIG_BLE_MESH_PROVISIONER
p_prov_set(const char * name)837 static int p_prov_set(const char *name)
838 {
839     struct prov_info val = {0};
840     bool exist = false;
841     int err = 0;
842 
843     BT_DBG("%s", __func__);
844 
845     err = bt_mesh_load_core_settings(name, (uint8_t *)&val, sizeof(val), &exist);
846     if (err) {
847         BT_ERR("Failed to load next address allocation");
848         return 0;
849     }
850 
851     if (exist == false) {
852         return 0;
853     }
854 
855     bt_mesh_provisioner_restore_prov_info(val.primary_addr, val.alloc_addr);
856 
857     BT_INFO("Restored Primary Address 0x%04x, next address alloc 0x%04x",
858         val.primary_addr, val.alloc_addr);
859 
860     return 0;
861 }
862 
p_net_idx_set(const char * name)863 static int p_net_idx_set(const char *name)
864 {
865     uint16_t net_idx = 0U;
866     bool exist = false;
867     int err = 0;
868 
869     BT_DBG("%s", __func__);
870 
871     err = bt_mesh_load_core_settings(name, (uint8_t *)&net_idx, sizeof(net_idx), &exist);
872     if (err) {
873         BT_ERR("Failed to load next NetKeyIndex alloc");
874         return 0;
875     }
876 
877     if (exist == false) {
878         return 0;
879     }
880 
881     bt_mesh.p_net_idx_next = net_idx;
882 
883     BT_INFO("Restored next NetKeyIndex alloc 0x%03x", bt_mesh.p_net_idx_next);
884 
885     return 0;
886 }
887 
p_app_idx_set(const char * name)888 static int p_app_idx_set(const char *name)
889 {
890     uint16_t app_idx = 0U;
891     bool exist = false;
892     int err = 0;
893 
894     BT_DBG("%s", __func__);
895 
896     err = bt_mesh_load_core_settings(name, (uint8_t *)&app_idx, sizeof(app_idx), &exist);
897     if (err) {
898         BT_ERR("Failed to load next AppKeyIndex alloc");
899         return 0;
900     }
901 
902     if (exist == false) {
903         return 0;
904     }
905 
906     bt_mesh.p_app_idx_next = app_idx;
907 
908     BT_INFO("Restored next AppKeyIndex alloc 0x%03x", bt_mesh.p_app_idx_next);
909 
910     return 0;
911 }
912 
p_subnet_alloc(void)913 static struct bt_mesh_subnet *p_subnet_alloc(void)
914 {
915     int i;
916 
917     for (i = 0; i < ARRAY_SIZE(bt_mesh.p_sub); i++) {
918         if (bt_mesh.p_sub[i] == NULL) {
919             bt_mesh.p_sub[i] = bt_mesh_calloc(sizeof(struct bt_mesh_subnet));
920             if (!bt_mesh.p_sub[i]) {
921                 BT_ERR("%s, Out of memory", __func__);
922                 return NULL;
923             }
924 
925             return bt_mesh.p_sub[i];
926         }
927     }
928 
929     return NULL;
930 }
931 
p_appkey_alloc(void)932 static struct bt_mesh_app_key *p_appkey_alloc(void)
933 {
934     int i;
935 
936     for (i = 0; i < ARRAY_SIZE(bt_mesh.p_app_keys); i++) {
937         if (bt_mesh.p_app_keys[i] == NULL) {
938             bt_mesh.p_app_keys[i] = bt_mesh_calloc(sizeof(struct bt_mesh_app_key));
939             if (!bt_mesh.p_app_keys[i]) {
940                 BT_ERR("%s, Out of memory", __func__);
941                 return NULL;
942             }
943 
944             return bt_mesh.p_app_keys[i];
945         }
946     }
947 
948     return NULL;
949 }
950 
p_net_key_set(const char * name)951 static int p_net_key_set(const char *name)
952 {
953     struct net_buf_simple *buf = NULL;
954     struct bt_mesh_subnet *sub = NULL;
955     struct net_key_val key = {0};
956     char get[16] = {'\0'};
957     size_t length = 0U;
958     bool exist = false;
959     int err = 0;
960     int i;
961 
962     BT_DBG("%s", __func__);
963 
964     buf = bt_mesh_get_core_settings_item(name);
965     if (!buf) {
966         return 0;
967     }
968 
969     length = buf->len;
970 
971     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
972         uint16_t net_idx = net_buf_simple_pull_le16(buf);
973         sprintf(get, "mesh/pnk/%04x", net_idx);
974 
975         err = bt_mesh_load_core_settings(get, (uint8_t *)&key, sizeof(key), &exist);
976         if (err) {
977             BT_ERR("Failed to load NetKey 0x%03x", net_idx);
978             continue;
979         }
980 
981         if (exist == false) {
982             continue;
983         }
984 
985         sub = bt_mesh_provisioner_subnet_get(net_idx);
986         if (!sub) {
987             sub = p_subnet_alloc();
988             if (!sub) {
989                 BT_ERR("No space for a new subnet 0x%03x", net_idx);
990                 err = -ENOMEM;
991                 goto free;
992             }
993         }
994 
995         sub->net_idx = net_idx;
996         sub->kr_flag = key.kr_flag;
997         sub->kr_phase = key.kr_phase;
998         memcpy(sub->keys[0].net, &key.val[0], 16);
999         memcpy(sub->keys[1].net, &key.val[1], 16);
1000 
1001         BT_INFO("Restored NetKeyIndex 0x%03x", sub->net_idx);
1002         BT_INFO("Restored NetKey %s", bt_hex(sub->keys[0].net, 16));
1003     }
1004 
1005 free:
1006     bt_mesh_free_buf(buf);
1007     return err;
1008 }
1009 
p_app_key_set(const char * name)1010 static int p_app_key_set(const char *name)
1011 {
1012     struct bt_mesh_app_key *app = NULL;
1013     struct bt_mesh_subnet *sub = NULL;
1014     struct net_buf_simple *buf = NULL;
1015     struct app_key_val key = {0};
1016     char get[16] = {'\0'};
1017     size_t length = 0U;
1018     bool exist = false;
1019     int err = 0;
1020     int i;
1021 
1022     BT_DBG("%s", __func__);
1023 
1024     buf = bt_mesh_get_core_settings_item(name);
1025     if (!buf) {
1026         return 0;
1027     }
1028 
1029     length = buf->len;
1030 
1031     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
1032         uint16_t app_idx = net_buf_simple_pull_le16(buf);
1033         sprintf(get, "mesh/pak/%04x", app_idx);
1034 
1035         err = bt_mesh_load_core_settings(get, (uint8_t *)&key, sizeof(key), &exist);
1036         if (err) {
1037             BT_ERR("Failed to load AppKey 0x%03x", app_idx);
1038             continue;
1039         }
1040 
1041         if (exist == false) {
1042             continue;
1043         }
1044 
1045         sub = bt_mesh_provisioner_subnet_get(key.net_idx);
1046         if (!sub) {
1047             BT_ERR("Failed to find subnet 0x%03x", key.net_idx);
1048             continue;
1049         }
1050 
1051         app = bt_mesh_provisioner_app_key_find(app_idx);
1052         if (!app) {
1053             app = p_appkey_alloc();
1054             if (!app) {
1055                 BT_ERR("No space for a new appkey 0x%03x", app_idx);
1056                 err = -ENOMEM;
1057                 goto free;
1058             }
1059         }
1060 
1061         app->net_idx = key.net_idx;
1062         app->app_idx = app_idx;
1063         app->updated = key.updated;
1064         memcpy(app->keys[0].val, key.val[0], 16);
1065         memcpy(app->keys[1].val, key.val[1], 16);
1066         bt_mesh_app_id(app->keys[0].val, &app->keys[0].id);
1067         bt_mesh_app_id(app->keys[1].val, &app->keys[1].id);
1068 
1069         BT_INFO("Restored AppKeyIndex 0x%03x, NetKeyIndex 0x%03x",
1070             app->app_idx, app->net_idx);
1071         BT_INFO("Restored AppKey %s", bt_hex(app->keys[0].val, 16));
1072     }
1073 
1074 free:
1075     bt_mesh_free_buf(buf);
1076     return err;
1077 }
1078 
node_info_set(uint16_t addr,bool * exist)1079 static int node_info_set(uint16_t addr, bool *exist)
1080 {
1081     struct bt_mesh_node node = {0};
1082     struct node_info info = {0};
1083     char get[16] = {'\0'};
1084     int err = 0;
1085 
1086     sprintf(get, "mesh/pn/%04x/i", addr);
1087     err = bt_mesh_load_core_settings(get, (uint8_t *)&info, sizeof(info), exist);
1088     if (err) {
1089         BT_ERR("Failed to load node 0x%04x info", addr);
1090         return -EIO;
1091     }
1092 
1093     if (*exist == false) {
1094         return 0;
1095     }
1096 
1097     memcpy(node.addr, info.addr, BLE_MESH_ADDR_LEN);
1098     node.addr_type = info.addr_type;
1099     memcpy(node.dev_uuid, info.dev_uuid, 16);
1100     node.oob_info = info.oob_info;
1101     node.unicast_addr = info.unicast_addr;
1102     node.element_num = info.element_num;
1103     node.net_idx = info.net_idx;
1104     node.flags = info.flags;
1105     node.iv_index = info.iv_index;
1106     memcpy(node.dev_key, info.dev_key, 16);
1107 
1108     err = bt_mesh_provisioner_restore_node_info(&node);
1109     if (err) {
1110         BT_ERR("Failed to restore node 0x%04x info", addr);
1111         return -EIO;
1112     }
1113 
1114     BT_INFO("Restored Node 0x%04x, UUID %s", addr, bt_hex(node.dev_uuid, 16));
1115 
1116     return 0;
1117 }
1118 
node_name_set(uint16_t addr)1119 static int node_name_set(uint16_t addr)
1120 {
1121     char name[BLE_MESH_NODE_NAME_SIZE + 1] = {0};
1122     char get[16] = {'\0'};
1123     bool exist = false;
1124     int err = 0;
1125 
1126     sprintf(get, "mesh/pn/%04x/n", addr);
1127     err = bt_mesh_load_core_settings(get, (uint8_t *)name, BLE_MESH_NODE_NAME_SIZE, &exist);
1128     if (err) {
1129         BT_ERR("Failed to load node 0x%04x name", addr);
1130         return -EIO;
1131     }
1132 
1133     if (exist == false) {
1134         return 0;
1135     }
1136 
1137     err = bt_mesh_provisioner_restore_node_name(addr, name);
1138     if (err) {
1139         BT_ERR("Failed to restore node 0x%04x name", addr);
1140         return -EIO;
1141     }
1142 
1143     BT_INFO("Restored Node 0x%04x, Name %s", addr, name);
1144 
1145     return 0;
1146 }
1147 
node_comp_data_set(uint16_t addr)1148 static int node_comp_data_set(uint16_t addr)
1149 {
1150     struct net_buf_simple *buf = NULL;
1151     char get[16] = {'\0'};
1152     int err = 0;
1153 
1154     sprintf(get, "mesh/pn/%04x/c", addr);
1155     buf = bt_mesh_get_core_settings_item(get);
1156     if (!buf) {
1157         return 0;
1158     }
1159 
1160     err = bt_mesh_provisioner_restore_node_comp_data(addr, buf->data, buf->len);
1161     if (err) {
1162         BT_ERR("Failed to restore node 0x%04x comp data", addr);
1163     } else {
1164         BT_INFO("Restored Node 0x%04x, Composition Data %s", addr, bt_hex(buf->data, buf->len));
1165     }
1166 
1167     bt_mesh_free_buf(buf);
1168     return err;
1169 }
1170 
p_node_set(const char * name)1171 static int p_node_set(const char *name)
1172 {
1173     struct net_buf_simple *buf = NULL;
1174     bool exist = false;
1175     size_t length = 0U;
1176     int i;
1177 
1178     buf = bt_mesh_get_core_settings_item(name);
1179     if (!buf) {
1180         return 0;
1181     }
1182 
1183     length = buf->len;
1184 
1185     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
1186         uint16_t addr = net_buf_simple_pull_le16(buf);
1187         if (!BLE_MESH_ADDR_IS_UNICAST(addr)) {
1188             BT_ERR("Invalid unicast address 0x%04x", addr);
1189             continue;
1190         }
1191 
1192         if (node_info_set(addr, &exist)) {
1193             continue;
1194         }
1195 
1196         if (exist == false) {
1197             continue;
1198         }
1199 
1200         if (node_name_set(addr)) {
1201             continue;
1202         }
1203 
1204         if (node_comp_data_set(addr)) {
1205             continue;
1206         }
1207     }
1208 
1209     bt_mesh_free_buf(buf);
1210     return 0;
1211 }
1212 #endif /* CONFIG_BLE_MESH_PROVISIONER */
1213 
1214 const struct bt_mesh_setting {
1215     const char *name;
1216     int (*func)(const char *name);
1217 } settings[] = {
1218     { "mesh/role",     role_set      }, /* For Node & Provisioner */
1219     { "mesh/net",      net_set       }, /* For Node */
1220     { "mesh/iv",       iv_set        }, /* For Node & Provisioner */
1221     { "mesh/seq",      seq_set       }, /* For Node & Provisioner */
1222     { "mesh/rpl",      rpl_set       }, /* For Node & Provisioner */
1223     { "mesh/netkey",   net_key_set   }, /* For Node */
1224     { "mesh/appkey",   app_key_set   }, /* For Node */
1225     { "mesh/hb_pub",   hb_pub_set    }, /* For Node */
1226     { "mesh/cfg",      cfg_set       }, /* For Node */
1227     { "mesh/sig",      sig_mod_set   }, /* For Node & Provisioner */
1228     { "mesh/vnd",      vnd_mod_set   }, /* For Node & Provisioner */
1229 #if CONFIG_BLE_MESH_LABEL_COUNT > 0
1230     { "mesh/vaddr",    va_set        }, /* For Node */
1231 #endif
1232 #if CONFIG_BLE_MESH_PROVISIONER
1233     { "mesh/p_prov",   p_prov_set    }, /* For Provisioner */
1234     { "mesh/p_netidx", p_net_idx_set }, /* For Provisioner */
1235     { "mesh/p_appidx", p_app_idx_set }, /* For Provisioner */
1236     { "mesh/p_netkey", p_net_key_set }, /* For Provisioner */
1237     { "mesh/p_appkey", p_app_key_set }, /* For Provisioner */
1238     { "mesh/p_node",   p_node_set    }, /* For Provisioner */
1239 #endif
1240 };
1241 
1242 /**
1243  * For Provisioner, the load operation needs the following actions:
1244  * role_set:    Need, restore the device role
1245  * net_set:     Not needed
1246  * iv_set:      Need, restore the last IV Index status
1247  * seq_set:     Need, restore the previous sequence number
1248  * rpl_set:     Need, restore the previous Replay Protection List
1249  * net_key_set: Not needed
1250  * app_key_set: Not needed
1251  * hb_pub_set:  Not needed currently
1252  * cfg_set:     Not needed currently
1253  * sig_mod_set: Need, restore SIG models related info (app, sub, pub)
1254  * vnd_mod_set: Need, restore vendor models related info (app, sub, pub)
1255  * va_set:      Not needed currently
1256  */
settings_core_load(void)1257 int settings_core_load(void)
1258 {
1259     int i;
1260 
1261     BT_DBG("%s", __func__);
1262 
1263     for (i = 0; i < ARRAY_SIZE(settings); i++) {
1264         if ((!strcmp(settings[i].name, "mesh/net") ||
1265             !strcmp(settings[i].name, "mesh/netkey") ||
1266             !strcmp(settings[i].name, "mesh/appkey") ||
1267             !strcmp(settings[i].name, "mesh/hb_pub") ||
1268             !strcmp(settings[i].name, "mesh/cfg") ||
1269             !strcmp(settings[i].name, "mesh/vaddr")) &&
1270             (!IS_ENABLED(CONFIG_BLE_MESH_NODE) || bt_mesh_is_provisioner())) {
1271             BT_DBG("Not restoring %s for Provisioner", settings[i].name);
1272             continue;
1273         }
1274 
1275         if ((!strcmp(settings[i].name, "mesh/p_prov") ||
1276             !strcmp(settings[i].name, "mesh/p_netidx") ||
1277             !strcmp(settings[i].name, "mesh/p_appidx") ||
1278             !strcmp(settings[i].name, "mesh/p_netkey") ||
1279             !strcmp(settings[i].name, "mesh/p_appkey") ||
1280             !strcmp(settings[i].name, "mesh/p_node")) &&
1281             (!IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) || bt_mesh_is_node())) {
1282             BT_DBG("Not restoring %s for Node", settings[i].name);
1283             continue;
1284         }
1285 
1286         settings[i].func(settings[i].name);
1287 
1288         if (!strcmp(settings[i].name, "mesh/role")) {
1289             uint8_t role = bt_mesh_atomic_get(bt_mesh.flags) & BLE_MESH_SETTINGS_ROLE_BIT_MASK;
1290             switch (role) {
1291             case BLE_MESH_SETTINGS_ROLE_NONE:
1292                 BT_INFO("Mesh device just starts up, no restore");
1293                 return 0;
1294             case BLE_MESH_SETTINGS_ROLE_NODE:
1295                 BT_INFO("Restored mesh device role: Node");
1296                 break;
1297             case BLE_MESH_SETTINGS_ROLE_PROV:
1298                 BT_INFO("Restored mesh device role: Provisioner");
1299                 break;
1300             default:
1301                 BT_ERR("Restored mesh device role: Unknown");
1302                 return 0;
1303             }
1304         }
1305     }
1306 
1307     return 0;
1308 }
1309 
subnet_init(struct bt_mesh_subnet * sub)1310 static int subnet_init(struct bt_mesh_subnet *sub)
1311 {
1312     int err = 0;
1313 
1314     err = bt_mesh_net_keys_create(&sub->keys[0], sub->keys[0].net);
1315     if (err) {
1316         BT_ERR("Unable to generate keys for subnet");
1317         return -EIO;
1318     }
1319 
1320     if (sub->kr_phase != BLE_MESH_KR_NORMAL) {
1321         err = bt_mesh_net_keys_create(&sub->keys[1], sub->keys[1].net);
1322         if (err) {
1323             BT_ERR("Unable to generate keys for subnet");
1324             (void)memset(&sub->keys[0], 0, sizeof(sub->keys[0]));
1325             return -EIO;
1326         }
1327     }
1328 
1329     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER)) {
1330         sub->node_id = BLE_MESH_NODE_IDENTITY_STOPPED;
1331     } else {
1332         sub->node_id = BLE_MESH_NODE_IDENTITY_NOT_SUPPORTED;
1333     }
1334 
1335     /* Make sure we have valid beacon data to be sent */
1336     bt_mesh_net_beacon_update(sub);
1337 
1338     return 0;
1339 }
1340 
commit_model(struct bt_mesh_model * model,struct bt_mesh_elem * elem,bool vnd,bool primary,void * user_data)1341 static void commit_model(struct bt_mesh_model *model, struct bt_mesh_elem *elem,
1342                          bool vnd, bool primary, void *user_data)
1343 {
1344     if (model->pub && model->pub->update &&
1345             model->pub->addr != BLE_MESH_ADDR_UNASSIGNED) {
1346         int32_t ms = bt_mesh_model_pub_period_get(model);
1347         if (ms) {
1348             BT_DBG("Starting publish timer (period %u ms)", ms);
1349             k_delayed_work_submit(&model->pub->timer, ms);
1350         }
1351     }
1352 }
1353 
settings_core_commit(void)1354 int settings_core_commit(void)
1355 {
1356     struct bt_mesh_subnet *sub = NULL;
1357     int err = 0;
1358     int i;
1359 
1360 #if defined(CONFIG_BLE_MESH_NODE)
1361     if (bt_mesh_is_node()) {
1362         if (bt_mesh.sub[0].net_idx == BLE_MESH_KEY_UNUSED) {
1363             /* Nothing to do since we're not yet provisioned */
1364             return 0;
1365         }
1366 
1367         BT_INFO("Settings commit, sub[0].net_idx 0x%03x", bt_mesh.sub[0].net_idx);
1368 
1369         if (IS_ENABLED(CONFIG_BLE_MESH_PB_GATT)) {
1370             bt_mesh_proxy_server_prov_disable(true);
1371         }
1372 
1373         for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
1374             sub = &bt_mesh.sub[i];
1375 
1376             if (sub->net_idx == BLE_MESH_KEY_UNUSED) {
1377                 continue;
1378             }
1379 
1380             err = subnet_init(sub);
1381             if (err) {
1382                 BT_ERR("Failed to init subnet 0x%03x", sub->net_idx);
1383             }
1384         }
1385     }
1386 #endif /* CONFIG_BLE_MESH_NODE */
1387 
1388 #if defined(CONFIG_BLE_MESH_PROVISIONER)
1389     if (bt_mesh_is_provisioner()) {
1390         if (bt_mesh.p_sub[0] == NULL ||
1391             bt_mesh.p_sub[0]->net_idx == BLE_MESH_KEY_UNUSED) {
1392             return 0;
1393         }
1394 
1395         BT_INFO("Settings commit, p_sub[0]->net_idx 0x%03x", bt_mesh.p_sub[0]->net_idx);
1396 
1397         for (i = 0; i < ARRAY_SIZE(bt_mesh.p_sub); i++) {
1398             sub = bt_mesh.p_sub[i];
1399 
1400             if (sub == NULL || sub->net_idx == BLE_MESH_KEY_UNUSED) {
1401                 continue;
1402             }
1403 
1404             err = subnet_init(sub);
1405             if (err) {
1406                 BT_ERR("Failed to init subnet 0x%03x", sub->net_idx);
1407             }
1408         }
1409     }
1410 #endif /* CONFIG_BLE_MESH_PROVISIONER */
1411 
1412     if (bt_mesh_is_node() || bt_mesh_is_provisioner()) {
1413         if (bt_mesh.ivu_duration < BLE_MESH_IVU_MIN_HOURS) {
1414             k_delayed_work_submit(&bt_mesh.ivu_timer, BLE_MESH_IVU_TIMEOUT);
1415         }
1416 
1417         bt_mesh_model_foreach(commit_model, NULL);
1418     }
1419 
1420 #if defined(CONFIG_BLE_MESH_NODE)
1421     if (bt_mesh_is_node()) {
1422         struct bt_mesh_hb_pub *hb_pub = NULL;
1423         struct bt_mesh_cfg_srv *cfg = NULL;
1424 
1425         bt_mesh_atomic_set_bit(bt_mesh.flags, BLE_MESH_VALID);
1426 
1427         hb_pub = bt_mesh_hb_pub_get();
1428         if (hb_pub && hb_pub->dst != BLE_MESH_ADDR_UNASSIGNED &&
1429                 hb_pub->count && hb_pub->period) {
1430             BT_DBG("Starting heartbeat publication");
1431             k_work_submit(&hb_pub->timer.work);
1432         }
1433 
1434         cfg = bt_mesh_cfg_get();
1435         if (cfg && stored_cfg.valid) {
1436             cfg->net_transmit = stored_cfg.cfg.net_transmit;
1437             cfg->relay = stored_cfg.cfg.relay;
1438             cfg->relay_retransmit = stored_cfg.cfg.relay_retransmit;
1439             cfg->beacon = stored_cfg.cfg.beacon;
1440             cfg->gatt_proxy = stored_cfg.cfg.gatt_proxy;
1441             cfg->frnd = stored_cfg.cfg.frnd;
1442             cfg->default_ttl = stored_cfg.cfg.default_ttl;
1443         }
1444 
1445         bt_mesh_net_start();
1446     }
1447 #endif /* CONFIG_BLE_MESH_NODE */
1448 
1449     return 0;
1450 }
1451 
1452 /* Pending flags that use K_NO_WAIT as the storage timeout */
1453 #define NO_WAIT_PENDING_BITS (BIT(BLE_MESH_NET_PENDING) |       \
1454                               BIT(BLE_MESH_IV_PENDING) |        \
1455                               BIT(BLE_MESH_SEQ_PENDING))
1456 
1457 /* Pending flags that use CONFIG_BLE_MESH_STORE_TIMEOUT */
1458 #define GENERIC_PENDING_BITS (BIT(BLE_MESH_KEYS_PENDING) |      \
1459                               BIT(BLE_MESH_HB_PUB_PENDING) |    \
1460                               BIT(BLE_MESH_CFG_PENDING) |       \
1461                               BIT(BLE_MESH_MOD_PENDING))
1462 
schedule_store(int flag)1463 static void schedule_store(int flag)
1464 {
1465     int32_t timeout = 0, remaining = 0;
1466 
1467     bt_mesh_atomic_set_bit(bt_mesh.flags, flag);
1468 
1469     /* When Node is not provisioned OR Provisioner is disabled,
1470      * we will directly erase the stored information.
1471      */
1472     if (!bt_mesh_is_provisioned() && !bt_mesh_is_provisioner_en()) {
1473         store_pending(NULL);
1474         return;
1475     }
1476 
1477     if (bt_mesh_atomic_get(bt_mesh.flags) & NO_WAIT_PENDING_BITS) {
1478         timeout = K_NO_WAIT;
1479     } else if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_RPL_PENDING) &&
1480                (!(bt_mesh_atomic_get(bt_mesh.flags) & GENERIC_PENDING_BITS) ||
1481                 (CONFIG_BLE_MESH_RPL_STORE_TIMEOUT < CONFIG_BLE_MESH_STORE_TIMEOUT))) {
1482         timeout = K_SECONDS(CONFIG_BLE_MESH_RPL_STORE_TIMEOUT);
1483     } else {
1484         timeout = K_SECONDS(CONFIG_BLE_MESH_STORE_TIMEOUT);
1485     }
1486 
1487     remaining = k_delayed_work_remaining_get(&pending_store);
1488     if (remaining && remaining < timeout) {
1489         BT_DBG("Not rescheduling due to existing earlier deadline");
1490         return;
1491     }
1492 
1493     BT_INFO("Settings store, waiting %d seconds", timeout / MSEC_PER_SEC);
1494 
1495     if (timeout) {
1496         k_delayed_work_submit(&pending_store, timeout);
1497     } else {
1498         k_work_submit(&pending_store.work);
1499     }
1500 }
1501 
clear_net(void)1502 static void clear_net(void)
1503 {
1504     BT_DBG("Clearing Network");
1505     bt_mesh_erase_core_settings("mesh/net");
1506 }
1507 
store_pending_net(void)1508 static void store_pending_net(void)
1509 {
1510     struct net_val net = {0};
1511 
1512     BT_DBG("Primary address 0x%04x DevKey %s", bt_mesh_primary_addr(),
1513            bt_hex(bt_mesh.dev_key, 16));
1514 
1515     net.primary_addr = bt_mesh_primary_addr();
1516     memcpy(net.dev_key, bt_mesh.dev_key, 16);
1517 
1518     bt_mesh_save_core_settings("mesh/net", (const uint8_t *)&net, sizeof(net));
1519 }
1520 
bt_mesh_store_role(void)1521 void bt_mesh_store_role(void)
1522 {
1523     BT_DBG("Store, device role %lu", bt_mesh_atomic_get(bt_mesh.flags) & BLE_MESH_SETTINGS_ROLE_BIT_MASK);
1524 
1525     bt_mesh_save_core_settings("mesh/role", (const uint8_t *)bt_mesh.flags, sizeof(bt_mesh.flags));
1526 }
1527 
bt_mesh_store_net(void)1528 void bt_mesh_store_net(void)
1529 {
1530     schedule_store(BLE_MESH_NET_PENDING);
1531 }
1532 
store_pending_iv(void)1533 static void store_pending_iv(void)
1534 {
1535     struct iv_val iv = {0};
1536 
1537     iv.iv_index = bt_mesh.iv_index;
1538     iv.iv_update = bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS);
1539     iv.iv_duration = bt_mesh.ivu_duration;
1540 
1541     bt_mesh_save_core_settings("mesh/iv", (const uint8_t *)&iv, sizeof(iv));
1542 }
1543 
bt_mesh_store_iv(bool only_duration)1544 void bt_mesh_store_iv(bool only_duration)
1545 {
1546     schedule_store(BLE_MESH_IV_PENDING);
1547 
1548     if (!only_duration) {
1549         /* Always update Seq whenever IV changes */
1550         schedule_store(BLE_MESH_SEQ_PENDING);
1551     }
1552 }
1553 
clear_iv(void)1554 static void clear_iv(void)
1555 {
1556     BT_DBG("Clearing IV");
1557     bt_mesh_erase_core_settings("mesh/iv");
1558 }
1559 
store_pending_seq(void)1560 static void store_pending_seq(void)
1561 {
1562     struct seq_val seq = {0};
1563 
1564     sys_put_le24(bt_mesh.seq, seq.val);
1565 
1566     bt_mesh_save_core_settings("mesh/seq", (const uint8_t *)&seq, sizeof(seq));
1567 }
1568 
bt_mesh_store_seq(void)1569 void bt_mesh_store_seq(void)
1570 {
1571     if (CONFIG_BLE_MESH_SEQ_STORE_RATE &&
1572             (bt_mesh.seq % CONFIG_BLE_MESH_SEQ_STORE_RATE)) {
1573         return;
1574     }
1575 
1576     schedule_store(BLE_MESH_SEQ_PENDING);
1577 }
1578 
bt_mesh_clear_seq(void)1579 void bt_mesh_clear_seq(void)
1580 {
1581     BT_DBG("Clearing Seq");
1582     bt_mesh_erase_core_settings("mesh/seq");
1583 }
1584 
store_rpl(struct bt_mesh_rpl * entry)1585 static void store_rpl(struct bt_mesh_rpl *entry)
1586 {
1587     struct rpl_val rpl = {0};
1588     char name[16] = {'\0'};
1589     int err = 0;
1590 
1591     BT_DBG("src 0x%04x seq 0x%06x old_iv %u", entry->src, entry->seq, entry->old_iv);
1592 
1593     rpl.seq = entry->seq;
1594     rpl.old_iv = entry->old_iv;
1595 
1596     sprintf(name, "mesh/rpl/%04x", entry->src);
1597     err = bt_mesh_save_core_settings(name, (const uint8_t *)&rpl, sizeof(rpl));
1598     if (err) {
1599         BT_ERR("Failed to store RPL entry 0x%04x", entry->src);
1600         return;
1601     }
1602 
1603     err = bt_mesh_add_core_settings_item("mesh/rpl", entry->src);
1604     if (err) {
1605         BT_ERR("Failed to add 0x%04x to mesh/rpl", entry->src);
1606     }
1607 
1608     return;
1609 }
1610 
clear_rpl(void)1611 static void clear_rpl(void)
1612 {
1613     struct net_buf_simple *buf = NULL;
1614     char name[16] = {'\0'};
1615     size_t length = 0U;
1616     uint16_t src = 0U;
1617     int i;
1618 
1619     BT_DBG("%s", __func__);
1620 
1621     buf = bt_mesh_get_core_settings_item("mesh/rpl");
1622     if (!buf) {
1623         bt_mesh_erase_core_settings("mesh/rpl");
1624         return;
1625     }
1626 
1627     length = buf->len;
1628 
1629     for (i = 0; i < length / SETTINGS_ITEM_SIZE; i++) {
1630         src = net_buf_simple_pull_le16(buf);
1631 
1632         if (!BLE_MESH_ADDR_IS_UNICAST(src)) {
1633             BT_ERR("Invalid source address 0x%04x", src);
1634             continue;
1635         }
1636 
1637         sprintf(name, "mesh/rpl/%04x", src);
1638         bt_mesh_erase_core_settings(name);
1639     }
1640 
1641     bt_mesh_erase_core_settings("mesh/rpl");
1642 
1643     bt_mesh_free_buf(buf);
1644     return;
1645 }
1646 
store_pending_rpl(void)1647 static void store_pending_rpl(void)
1648 {
1649     int i;
1650 
1651     BT_DBG("%s", __func__);
1652 
1653     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
1654         struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
1655 
1656         if (rpl->store) {
1657             rpl->store = false;
1658             store_rpl(rpl);
1659         }
1660     }
1661 }
1662 
store_pending_hb_pub(void)1663 static void store_pending_hb_pub(void)
1664 {
1665     struct bt_mesh_hb_pub *hb_pub = bt_mesh_hb_pub_get();
1666     struct hb_pub_val val = {0};
1667 
1668     if (!hb_pub) {
1669         BT_ERR("Invalid heartbeat publication");
1670         return;
1671     }
1672 
1673     val.indefinite = (hb_pub->count = 0xffff);
1674     val.dst = hb_pub->dst;
1675     val.period = hb_pub->period;
1676     val.ttl = hb_pub->ttl;
1677     val.feat = hb_pub->feat;
1678     val.net_idx = hb_pub->net_idx;
1679 
1680     bt_mesh_save_core_settings("mesh/hb_pub", (const uint8_t *)&val, sizeof(val));
1681 }
1682 
clear_hb_pub(void)1683 static void clear_hb_pub(void)
1684 {
1685     BT_DBG("Clear heartbeat publication");
1686     bt_mesh_erase_core_settings("mesh/hb_pub");
1687 }
1688 
store_pending_cfg(void)1689 static void store_pending_cfg(void)
1690 {
1691     struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get();
1692     struct cfg_val val = {0};
1693 
1694     if (!cfg) {
1695         BT_WARN("NULL configuration state");
1696         return;
1697     }
1698 
1699     val.net_transmit = cfg->net_transmit;
1700     val.relay = cfg->relay;
1701     val.relay_retransmit = cfg->relay_retransmit;
1702     val.beacon = cfg->beacon;
1703     val.gatt_proxy = cfg->gatt_proxy;
1704     val.frnd = cfg->frnd;
1705     val.default_ttl = cfg->default_ttl;
1706 
1707     bt_mesh_save_core_settings("mesh/cfg", (const uint8_t *)&val, sizeof(val));
1708 }
1709 
clear_cfg(void)1710 static void clear_cfg(void)
1711 {
1712     BT_DBG("Clearing configuration");
1713     bt_mesh_erase_core_settings("mesh/cfg");
1714 }
1715 
clear_app_key(uint16_t app_idx)1716 static void clear_app_key(uint16_t app_idx)
1717 {
1718     char name[16] = {'\0'};
1719     int err = 0;
1720 
1721     BT_DBG("AppKeyIndex 0x%03x", app_idx);
1722 
1723     sprintf(name, "mesh/ak/%04x", app_idx);
1724     bt_mesh_erase_core_settings(name);
1725 
1726     err = bt_mesh_remove_core_settings_item("mesh/appkey", app_idx);
1727     if (err) {
1728         BT_ERR("Failed to remove 0x%03x from mesh/appkey", app_idx);
1729     }
1730 
1731     return;
1732 }
1733 
clear_net_key(uint16_t net_idx)1734 static void clear_net_key(uint16_t net_idx)
1735 {
1736     char name[16] = {'\0'};
1737     int err = 0;
1738 
1739     BT_DBG("NetKeyIndex 0x%03x", net_idx);
1740 
1741     sprintf(name, "mesh/nk/%04x", net_idx);
1742     bt_mesh_erase_core_settings(name);
1743 
1744     err = bt_mesh_remove_core_settings_item("mesh/netkey", net_idx);
1745     if (err) {
1746         BT_ERR("Failed to remove 0x%03x from mesh/netkey", net_idx);
1747     }
1748 
1749     return;
1750 }
1751 
store_net_key(struct bt_mesh_subnet * sub)1752 static void store_net_key(struct bt_mesh_subnet *sub)
1753 {
1754     struct net_key_val key = {0};
1755     char name[16] = {'\0'};
1756     int err = 0;
1757 
1758     BT_DBG("NetKeyIndex 0x%03x NetKey %s", sub->net_idx,
1759            bt_hex(sub->keys[0].net, 16));
1760 
1761     memcpy(&key.val[0], sub->keys[0].net, 16);
1762     memcpy(&key.val[1], sub->keys[1].net, 16);
1763     key.kr_flag = sub->kr_flag;
1764     key.kr_phase = sub->kr_phase;
1765 
1766     sprintf(name, "mesh/nk/%04x", sub->net_idx);
1767     err = bt_mesh_save_core_settings(name, (const uint8_t *)&key, sizeof(key));
1768     if (err) {
1769         BT_ERR("Failed to store NetKey 0x%03x", sub->net_idx);
1770         return;
1771     }
1772 
1773     err = bt_mesh_add_core_settings_item("mesh/netkey", sub->net_idx);
1774     if (err) {
1775         BT_ERR("Failed to add 0x%03x to mesh/netkey", sub->net_idx);
1776     }
1777 
1778     return;
1779 }
1780 
store_app_key(struct bt_mesh_app_key * app)1781 static void store_app_key(struct bt_mesh_app_key *app)
1782 {
1783     struct app_key_val key = {0};
1784     char name[16] = {'\0'};
1785     int err = 0;
1786 
1787     key.net_idx = app->net_idx;
1788     key.updated = app->updated;
1789     memcpy(key.val[0], app->keys[0].val, 16);
1790     memcpy(key.val[1], app->keys[1].val, 16);
1791 
1792     sprintf(name, "mesh/ak/%04x", app->app_idx);
1793     err = bt_mesh_save_core_settings(name, (const uint8_t *)&key, sizeof(key));
1794     if (err) {
1795         BT_ERR("Failed to store AppKey 0x%03x", app->app_idx);
1796         return;
1797     }
1798 
1799     err = bt_mesh_add_core_settings_item("mesh/appkey", app->app_idx);
1800     if (err) {
1801         BT_ERR("Failed to add 0x%03x to mesh/appkey", app->app_idx);
1802     }
1803 
1804     return;
1805 }
1806 
store_pending_keys(void)1807 static void store_pending_keys(void)
1808 {
1809     int i;
1810 
1811     for (i = 0; i < ARRAY_SIZE(key_updates); i++) {
1812         struct key_update *update = &key_updates[i];
1813 
1814         if (!update->valid) {
1815             continue;
1816         }
1817 
1818         if (update->clear) {
1819             if (update->app_key) {
1820                 clear_app_key(update->key_idx);
1821             } else {
1822                 clear_net_key(update->key_idx);
1823             }
1824         } else {
1825             if (update->app_key) {
1826                 struct bt_mesh_app_key *key = NULL;
1827                 key = bt_mesh_app_key_find(update->key_idx);
1828                 if (key) {
1829                     store_app_key(key);
1830                 } else {
1831                     BT_WARN("AppKeyIndex 0x%03x not found", update->key_idx);
1832                 }
1833             } else {
1834                 struct bt_mesh_subnet *sub = NULL;
1835                 sub = bt_mesh_subnet_get(update->key_idx);
1836                 if (sub) {
1837                     store_net_key(sub);
1838                 } else {
1839                     BT_WARN("NetKeyIndex 0x%03x not found", update->key_idx);
1840                 }
1841             }
1842         }
1843 
1844         update->valid = 0U;
1845     }
1846 }
1847 
store_pending_mod_bind(struct bt_mesh_model * model,bool vnd)1848 static void store_pending_mod_bind(struct bt_mesh_model *model, bool vnd)
1849 {
1850     char name[16] = {'\0'};
1851     uint16_t model_key = 0U;
1852     int err = 0;
1853 
1854     model_key = BLE_MESH_GET_MODEL_KEY(model->elem_idx, model->model_idx);
1855     sprintf(name, "mesh/%s/%04x/b", vnd ? "v" : "s", model_key);
1856 
1857     err = bt_mesh_save_core_settings(name, (const uint8_t *)model->keys, sizeof(model->keys));
1858     if (err) {
1859         BT_ERR("Failed to store %s", name);
1860         return;
1861     }
1862 
1863     err = bt_mesh_add_core_settings_item(vnd ? "mesh/vnd" : "mesh/sig", model_key);
1864     if (err) {
1865         BT_ERR("Failed to add bound key to %s, model_key 0x%04x",
1866             vnd ? "mesh/vnd" : "mesh/sig", model_key);
1867     }
1868 
1869     return;
1870 }
1871 
store_pending_mod_sub(struct bt_mesh_model * model,bool vnd)1872 static void store_pending_mod_sub(struct bt_mesh_model *model, bool vnd)
1873 {
1874     char name[16] = {'\0'};
1875     uint16_t model_key = 0U;
1876     int err = 0;
1877 
1878     model_key = BLE_MESH_GET_MODEL_KEY(model->elem_idx, model->model_idx);
1879     sprintf(name, "mesh/%s/%04x/s", vnd ? "v" : "s", model_key);
1880 
1881     err = bt_mesh_save_core_settings(name, (const uint8_t *)model->groups, sizeof(model->groups));
1882     if (err) {
1883         BT_ERR("Failed to store %s", name);
1884         return;
1885     }
1886 
1887     err = bt_mesh_add_core_settings_item(vnd ? "mesh/vnd" : "mesh/sig", model_key);
1888     if (err) {
1889         BT_ERR("Failed to add subscription to %s, model_key 0x%04x",
1890             vnd ? "mesh/vnd" : "mesh/sig", model_key);
1891     }
1892 
1893     return;
1894 }
1895 
store_pending_mod_pub(struct bt_mesh_model * model,bool vnd)1896 static void store_pending_mod_pub(struct bt_mesh_model *model, bool vnd)
1897 {
1898     struct mod_pub_val pub = {0};
1899     char name[16] = {'\0'};
1900     uint16_t model_key = 0U;
1901     int err = 0;
1902 
1903     if (!model->pub) {
1904         BT_WARN("Model has no publication support");
1905         return;
1906     }
1907 
1908     model_key = BLE_MESH_GET_MODEL_KEY(model->elem_idx, model->model_idx);
1909     sprintf(name, "mesh/%s/%04x/p", vnd ? "v" : "s", model_key);
1910 
1911     pub.addr = model->pub->addr;
1912     pub.key = model->pub->key;
1913     pub.ttl = model->pub->ttl;
1914     pub.retransmit = model->pub->retransmit;
1915     pub.period = model->pub->period;
1916     pub.period_div = model->pub->period_div;
1917     pub.cred = model->pub->cred;
1918 
1919     err = bt_mesh_save_core_settings(name, (const uint8_t *)&pub, sizeof(pub));
1920     if (err) {
1921         BT_ERR("Failed to store %s", name);
1922         return;
1923     }
1924 
1925     err = bt_mesh_add_core_settings_item(vnd ? "mesh/vnd" : "mesh/sig", model_key);
1926     if (err) {
1927         BT_ERR("Failed to add publication to %s, model_key 0x%04x",
1928                vnd ? "mesh/vnd" : "mesh/sig", model_key);
1929     }
1930 
1931     return;
1932 }
1933 
store_pending_mod(struct bt_mesh_model * model,struct bt_mesh_elem * elem,bool vnd,bool primary,void * user_data)1934 static void store_pending_mod(struct bt_mesh_model *model,
1935                               struct bt_mesh_elem *elem, bool vnd,
1936                               bool primary, void *user_data)
1937 {
1938     if (!model->flags) {
1939         return;
1940     }
1941 
1942     if (model->flags & BLE_MESH_MOD_BIND_PENDING) {
1943         model->flags &= ~BLE_MESH_MOD_BIND_PENDING;
1944         store_pending_mod_bind(model, vnd);
1945     }
1946 
1947     if (model->flags & BLE_MESH_MOD_SUB_PENDING) {
1948         model->flags &= ~BLE_MESH_MOD_SUB_PENDING;
1949         store_pending_mod_sub(model, vnd);
1950     }
1951 
1952     if (model->flags & BLE_MESH_MOD_PUB_PENDING) {
1953         model->flags &= ~BLE_MESH_MOD_PUB_PENDING;
1954         store_pending_mod_pub(model, vnd);
1955     }
1956 }
1957 
clear_mod_bind(struct bt_mesh_model * model,bool vnd)1958 static void clear_mod_bind(struct bt_mesh_model *model, bool vnd)
1959 {
1960     char name[16] = {'\0'};
1961     uint16_t model_key = 0U;
1962 
1963     model_key = BLE_MESH_GET_MODEL_KEY(model->elem_idx, model->model_idx);
1964     sprintf(name, "mesh/%s/%04x/b", vnd ? "v" : "s", model_key);
1965 
1966     bt_mesh_erase_core_settings(name);
1967     bt_mesh_remove_core_settings_item(vnd ? "mesh/vnd" : "mesh/sig", model_key);
1968 }
1969 
clear_mod_sub(struct bt_mesh_model * model,bool vnd)1970 static void clear_mod_sub(struct bt_mesh_model *model, bool vnd)
1971 {
1972     char name[16] = {'\0'};
1973     uint16_t model_key = 0U;
1974 
1975     model_key = BLE_MESH_GET_MODEL_KEY(model->elem_idx, model->model_idx);
1976     sprintf(name, "mesh/%s/%04x/s", vnd ? "v" : "s", model_key);
1977 
1978     bt_mesh_erase_core_settings(name);
1979     bt_mesh_remove_core_settings_item(vnd ? "mesh/vnd" : "mesh/sig", model_key);
1980 }
1981 
clear_mod_pub(struct bt_mesh_model * model,bool vnd)1982 static void clear_mod_pub(struct bt_mesh_model *model, bool vnd)
1983 {
1984     char name[16] = {'\0'};
1985     uint16_t model_key = 0U;
1986 
1987     model_key = BLE_MESH_GET_MODEL_KEY(model->elem_idx, model->model_idx);
1988     sprintf(name, "mesh/%s/%04x/p", vnd ? "v" : "s", model_key);
1989 
1990     bt_mesh_erase_core_settings(name);
1991     bt_mesh_remove_core_settings_item(vnd ? "mesh/vnd" : "mesh/sig", model_key);
1992 }
1993 
clear_pending_mod(struct bt_mesh_model * model,struct bt_mesh_elem * elem,bool vnd,bool primary,void * user_data)1994 static void clear_pending_mod(struct bt_mesh_model *model,
1995                               struct bt_mesh_elem *elem, bool vnd,
1996                               bool primary, void *user_data)
1997 {
1998     if (!model->flags) {
1999         return;
2000     }
2001 
2002     if (model->flags & BLE_MESH_MOD_BIND_PENDING) {
2003         model->flags &= ~BLE_MESH_MOD_BIND_PENDING;
2004         clear_mod_bind(model, vnd);
2005     }
2006 
2007     if (model->flags & BLE_MESH_MOD_SUB_PENDING) {
2008         model->flags &= ~BLE_MESH_MOD_SUB_PENDING;
2009         clear_mod_sub(model, vnd);
2010     }
2011 
2012     if (model->flags & BLE_MESH_MOD_PUB_PENDING) {
2013         model->flags &= ~BLE_MESH_MOD_PUB_PENDING;
2014         clear_mod_pub(model, vnd);
2015     }
2016 }
2017 
2018 #define IS_VA_DEL(_label)   ((_label)->ref == 0)
store_pending_va(void)2019 static void store_pending_va(void)
2020 {
2021     struct va_val va = {0};
2022     char name[16] = {'\0'};
2023     struct label *lab = NULL;
2024     uint16_t i = 0U;
2025     int err = 0;
2026 
2027     for (i = 0U; (lab = get_label(i)) != NULL; i++) {
2028         if (!bt_mesh_atomic_test_and_clear_bit(lab->flags,
2029             BLE_MESH_VA_CHANGED)) {
2030             continue;
2031         }
2032 
2033         sprintf(name, "mesh/va/%04x", i);
2034 
2035         if (IS_VA_DEL(lab)) {
2036             err = bt_mesh_erase_core_settings(name);
2037         } else {
2038             va.ref = lab->ref;
2039             va.addr = lab->addr;
2040             memcpy(va.uuid, lab->uuid, 16);
2041             err = bt_mesh_save_core_settings(name, (const uint8_t *)&va, sizeof(va));
2042         }
2043         if (err) {
2044             BT_ERR("Failed to %s virtual address %s",
2045                 IS_VA_DEL(lab) ? "delete" : "store", name);
2046             return;
2047         }
2048 
2049         if (IS_VA_DEL(lab)) {
2050             err = bt_mesh_remove_core_settings_item("mesh/vaddr", i);
2051         } else {
2052             err = bt_mesh_add_core_settings_item("mesh/vaddr", i);
2053         }
2054         if (err) {
2055             BT_ERR("Failed to %s 0x%04x in mesh/vaddr",
2056                 IS_VA_DEL(lab) ? "delete" : "store", i);
2057             return;
2058         }
2059 
2060         BT_DBG("%s virtual address 0x%04x", IS_VA_DEL(lab) ? "Delete" : "Store", i);
2061     }
2062 }
2063 
store_pending(struct k_work * work)2064 static void store_pending(struct k_work *work)
2065 {
2066     BT_DBG("%s", __func__);
2067 
2068     if (bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_RPL_PENDING)) {
2069         if (bt_mesh_is_provisioned() || bt_mesh_is_provisioner_en()) {
2070             store_pending_rpl();
2071         } else {
2072             clear_rpl();
2073         }
2074     }
2075 
2076     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_node() &&
2077         bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_KEYS_PENDING)) {
2078         store_pending_keys();
2079     }
2080 
2081     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_node() &&
2082         bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_NET_PENDING)) {
2083         if (bt_mesh_is_provisioned()) {
2084             store_pending_net();
2085         } else {
2086             clear_net();
2087         }
2088     }
2089 
2090     if (bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_IV_PENDING)) {
2091         if (bt_mesh_is_provisioned() || bt_mesh_is_provisioner_en()) {
2092             store_pending_iv();
2093         } else {
2094             clear_iv();
2095         }
2096     }
2097 
2098     if (bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_SEQ_PENDING)) {
2099         if (bt_mesh_is_provisioned() || bt_mesh_is_provisioner_en()) {
2100             store_pending_seq();
2101         } else {
2102             bt_mesh_clear_seq();
2103         }
2104     }
2105 
2106     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_node() &&
2107         bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_HB_PUB_PENDING)) {
2108         if (bt_mesh_is_provisioned()) {
2109             store_pending_hb_pub();
2110         } else {
2111             clear_hb_pub();
2112         }
2113     }
2114 
2115     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_node() &&
2116         bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_CFG_PENDING)) {
2117         if (bt_mesh_is_provisioned()) {
2118             store_pending_cfg();
2119         } else {
2120             clear_cfg();
2121         }
2122     }
2123 
2124     if (bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_MOD_PENDING)) {
2125         if (bt_mesh_is_provisioned() || bt_mesh_is_provisioner_en()) {
2126             bt_mesh_model_foreach(store_pending_mod, NULL);
2127         } else {
2128             bt_mesh_model_foreach(clear_pending_mod, NULL);
2129             bt_mesh_erase_core_settings("mesh/sig");
2130             bt_mesh_erase_core_settings("mesh/vnd");
2131         }
2132     }
2133 
2134     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_node() &&
2135         bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_VA_PENDING)) {
2136         store_pending_va();
2137     }
2138 }
2139 
bt_mesh_store_rpl(struct bt_mesh_rpl * entry)2140 void bt_mesh_store_rpl(struct bt_mesh_rpl *entry)
2141 {
2142     entry->store = true;
2143     schedule_store(BLE_MESH_RPL_PENDING);
2144 }
2145 
key_update_find(bool app_key,uint16_t key_idx,struct key_update ** free_slot)2146 static struct key_update *key_update_find(bool app_key, uint16_t key_idx,
2147                                           struct key_update **free_slot)
2148 {
2149     struct key_update *match = NULL;
2150     int i;
2151 
2152     *free_slot = NULL;
2153 
2154     for (i = 0; i < ARRAY_SIZE(key_updates); i++) {
2155         struct key_update *update = &key_updates[i];
2156 
2157         if (!update->valid) {
2158             *free_slot = update;
2159             continue;
2160         }
2161 
2162         if (update->app_key != app_key) {
2163             continue;
2164         }
2165 
2166         if (update->key_idx == key_idx) {
2167             match = update;
2168         }
2169     }
2170 
2171     return match;
2172 }
2173 
bt_mesh_store_subnet(struct bt_mesh_subnet * sub)2174 void bt_mesh_store_subnet(struct bt_mesh_subnet *sub)
2175 {
2176     struct key_update *free_slot = NULL;
2177     struct key_update *update = NULL;
2178 
2179     BT_DBG("NetKeyIndex 0x%03x", sub->net_idx);
2180 
2181     update = key_update_find(false, sub->net_idx, &free_slot);
2182     if (update) {
2183         update->clear = 0U;
2184         schedule_store(BLE_MESH_KEYS_PENDING);
2185         return;
2186     }
2187 
2188     if (!free_slot) {
2189         store_net_key(sub);
2190         return;
2191     }
2192 
2193     free_slot->valid = 1U;
2194     free_slot->key_idx = sub->net_idx;
2195     free_slot->app_key = 0U;
2196     free_slot->clear = 0U;
2197 
2198     schedule_store(BLE_MESH_KEYS_PENDING);
2199 }
2200 
bt_mesh_store_app_key(struct bt_mesh_app_key * key)2201 void bt_mesh_store_app_key(struct bt_mesh_app_key *key)
2202 {
2203     struct key_update *free_slot = NULL;
2204     struct key_update *update = NULL;
2205 
2206     BT_DBG("AppKeyIndex 0x%03x", key->app_idx);
2207 
2208     update = key_update_find(true, key->app_idx, &free_slot);
2209     if (update) {
2210         update->clear = 0U;
2211         schedule_store(BLE_MESH_KEYS_PENDING);
2212         return;
2213     }
2214 
2215     if (!free_slot) {
2216         store_app_key(key);
2217         return;
2218     }
2219 
2220     free_slot->valid = 1U;
2221     free_slot->key_idx = key->app_idx;
2222     free_slot->app_key = 1U;
2223     free_slot->clear = 0U;
2224 
2225     schedule_store(BLE_MESH_KEYS_PENDING);
2226 }
2227 
bt_mesh_store_hb_pub(void)2228 void bt_mesh_store_hb_pub(void)
2229 {
2230     schedule_store(BLE_MESH_HB_PUB_PENDING);
2231 }
2232 
bt_mesh_store_cfg(void)2233 void bt_mesh_store_cfg(void)
2234 {
2235     schedule_store(BLE_MESH_CFG_PENDING);
2236 }
2237 
bt_mesh_clear_role(void)2238 void bt_mesh_clear_role(void)
2239 {
2240     BT_DBG("Clear device role");
2241     bt_mesh_erase_core_settings("mesh/role");
2242 }
2243 
bt_mesh_clear_net(void)2244 void bt_mesh_clear_net(void)
2245 {
2246     schedule_store(BLE_MESH_NET_PENDING);
2247     schedule_store(BLE_MESH_IV_PENDING);
2248     schedule_store(BLE_MESH_CFG_PENDING);
2249 }
2250 
bt_mesh_clear_subnet(struct bt_mesh_subnet * sub)2251 void bt_mesh_clear_subnet(struct bt_mesh_subnet *sub)
2252 {
2253     struct key_update *free_slot = NULL;
2254     struct key_update *update = NULL;
2255 
2256     BT_DBG("NetKeyIndex 0x%03x", sub->net_idx);
2257 
2258     update = key_update_find(false, sub->net_idx, &free_slot);
2259     if (update) {
2260         update->clear = 1U;
2261         schedule_store(BLE_MESH_KEYS_PENDING);
2262         return;
2263     }
2264 
2265     if (!free_slot) {
2266         clear_net_key(sub->net_idx);
2267         return;
2268     }
2269 
2270     free_slot->valid = 1U;
2271     free_slot->key_idx = sub->net_idx;
2272     free_slot->app_key = 0U;
2273     free_slot->clear = 1U;
2274 
2275     schedule_store(BLE_MESH_KEYS_PENDING);
2276 }
2277 
bt_mesh_clear_app_key(struct bt_mesh_app_key * key)2278 void bt_mesh_clear_app_key(struct bt_mesh_app_key *key)
2279 {
2280     struct key_update *free_slot = NULL;
2281     struct key_update *update = NULL;
2282 
2283     BT_DBG("AppKeyIndex 0x%03x", key->app_idx);
2284 
2285     update = key_update_find(true, key->app_idx, &free_slot);
2286     if (update) {
2287         update->clear = 1U;
2288         schedule_store(BLE_MESH_KEYS_PENDING);
2289         return;
2290     }
2291 
2292     if (!free_slot) {
2293         clear_app_key(key->app_idx);
2294         return;
2295     }
2296 
2297     free_slot->valid = 1U;
2298     free_slot->key_idx = key->app_idx;
2299     free_slot->app_key = 1U;
2300     free_slot->clear = 1U;
2301 
2302     schedule_store(BLE_MESH_KEYS_PENDING);
2303 }
2304 
bt_mesh_clear_rpl(void)2305 void bt_mesh_clear_rpl(void)
2306 {
2307     schedule_store(BLE_MESH_RPL_PENDING);
2308 }
2309 
bt_mesh_store_mod_bind(struct bt_mesh_model * model)2310 void bt_mesh_store_mod_bind(struct bt_mesh_model *model)
2311 {
2312     model->flags |= BLE_MESH_MOD_BIND_PENDING;
2313     schedule_store(BLE_MESH_MOD_PENDING);
2314 }
2315 
bt_mesh_store_mod_sub(struct bt_mesh_model * model)2316 void bt_mesh_store_mod_sub(struct bt_mesh_model *model)
2317 {
2318     model->flags |= BLE_MESH_MOD_SUB_PENDING;
2319     schedule_store(BLE_MESH_MOD_PENDING);
2320 }
2321 
bt_mesh_store_mod_pub(struct bt_mesh_model * model)2322 void bt_mesh_store_mod_pub(struct bt_mesh_model *model)
2323 {
2324     model->flags |= BLE_MESH_MOD_PUB_PENDING;
2325     schedule_store(BLE_MESH_MOD_PENDING);
2326 }
2327 
bt_mesh_store_label(void)2328 void bt_mesh_store_label(void)
2329 {
2330     schedule_store(BLE_MESH_VA_PENDING);
2331 }
2332 
2333 #if CONFIG_BLE_MESH_PROVISIONER
2334 /**
2335  * key: "mesh/p_prov"   -> write/read to set/get prov_ctx.curr_addr
2336  * key: "mesh/p_netidx" -> write/read to set/get bt_mesh.p_net_idx_next
2337  * key: "mesh/p_appidx" -> write/read to set/get bt_mesh.p_app_idx_next
2338  * key: "mesh/p_netkey" -> write/read to set/get all Provisioner NetKey Index
2339  *      key: "mesh/pnk/xxxx" -> write/read to set/get the "xxxx" NetKey
2340  * key: "mesh/p_appkey" -> write/read to set/get all Provisioner AppKey Index
2341  *      key: "mesh/pak/xxxx" -> write/read to set/get the "xxxx" AppKey
2342  * key: "mesh/p_node"   -> write/read to set/get all self-provisioned nodes info
2343  *      key: "mesh/pn/xxxx/i" -> write/read to set/get the "xxxx" provisioned node info
2344  *      key: "mesh/pn/xxxx/n" -> write/read to set/get the "xxxx" provisioned node name
2345  *      key: "mesh/pn/xxxx/c" -> write/read to set/get the "xxxx" provisioned node composition data
2346  */
bt_mesh_store_prov_info(uint16_t primary_addr,uint16_t alloc_addr)2347 void bt_mesh_store_prov_info(uint16_t primary_addr, uint16_t alloc_addr)
2348 {
2349     struct prov_info val = {0};
2350 
2351     BT_DBG("Primary address 0x%04x, next address allocation 0x%04x", primary_addr, alloc_addr);
2352 
2353     val.primary_addr = primary_addr;
2354     val.alloc_addr = alloc_addr;
2355 
2356     bt_mesh_save_core_settings("mesh/p_prov", (const uint8_t *)&val, sizeof(val));
2357 }
2358 
bt_mesh_clear_prov_info(void)2359 void bt_mesh_clear_prov_info(void)
2360 {
2361     BT_DBG("Clearing prov info");
2362     bt_mesh_erase_core_settings("mesh/p_prov");
2363 }
2364 
store_p_net_key(struct bt_mesh_subnet * sub)2365 static void store_p_net_key(struct bt_mesh_subnet *sub)
2366 {
2367     struct net_key_val key = {0};
2368     char name[16] = {'\0'};
2369     int err = 0;
2370 
2371     memcpy(&key.val[0], sub->keys[0].net, 16);
2372     memcpy(&key.val[1], sub->keys[1].net, 16);
2373     key.kr_flag = sub->kr_flag;
2374     key.kr_phase = sub->kr_phase;
2375 
2376     sprintf(name, "mesh/pnk/%04x", sub->net_idx);
2377     err = bt_mesh_save_core_settings(name, (const uint8_t *)&key, sizeof(key));
2378     if (err) {
2379         BT_ERR("Failed to store NetKey 0x%03x", sub->net_idx);
2380         return;
2381     }
2382 
2383     err = bt_mesh_add_core_settings_item("mesh/p_netkey", sub->net_idx);
2384     if (err) {
2385         BT_ERR("Failed to add 0x%03x to mesh/p_netkey", sub->net_idx);
2386     }
2387 }
2388 
store_p_app_key(struct bt_mesh_app_key * app)2389 static void store_p_app_key(struct bt_mesh_app_key *app)
2390 {
2391     struct app_key_val key = {0};
2392     char name[16] = {'\0'};
2393     int err = 0;
2394 
2395     key.net_idx = app->net_idx;
2396     key.updated = app->updated;
2397     memcpy(key.val[0], app->keys[0].val, 16);
2398     memcpy(key.val[1], app->keys[1].val, 16);
2399 
2400     sprintf(name, "mesh/pak/%04x", app->app_idx);
2401     err = bt_mesh_save_core_settings(name, (const uint8_t *)&key, sizeof(key));
2402     if (err) {
2403         BT_ERR("Failed to store AppKey 0x%03x", app->app_idx);
2404         return;
2405     }
2406 
2407     err = bt_mesh_add_core_settings_item("mesh/p_appkey", app->app_idx);
2408     if (err) {
2409         BT_ERR("Failed to add 0x%03x to mesh/p_appkey", app->app_idx);
2410     }
2411 }
2412 
bt_mesh_store_p_net_idx(void)2413 void bt_mesh_store_p_net_idx(void)
2414 {
2415     BT_DBG("Store, p_net_idx_next 0x%03x", bt_mesh.p_net_idx_next);
2416 
2417     bt_mesh_save_core_settings("mesh/p_netidx",
2418         (const uint8_t *)&bt_mesh.p_net_idx_next, sizeof(bt_mesh.p_net_idx_next));
2419 }
2420 
bt_mesh_clear_p_net_idx(void)2421 void bt_mesh_clear_p_net_idx(void)
2422 {
2423     BT_DBG("Clearing NetKey Index");
2424     bt_mesh_erase_core_settings("mesh/p_netidx");
2425 }
2426 
bt_mesh_store_p_app_idx(void)2427 void bt_mesh_store_p_app_idx(void)
2428 {
2429     BT_DBG("Store, p_app_idx_next 0x%03x", bt_mesh.p_app_idx_next);
2430 
2431     bt_mesh_save_core_settings("mesh/p_appidx",
2432         (const uint8_t *)&bt_mesh.p_app_idx_next, sizeof(bt_mesh.p_app_idx_next));
2433 }
2434 
bt_mesh_clear_p_app_idx(void)2435 void bt_mesh_clear_p_app_idx(void)
2436 {
2437     BT_DBG("Clearing AppKey Index");
2438     bt_mesh_erase_core_settings("mesh/p_appidx");
2439 }
2440 
bt_mesh_store_p_subnet(struct bt_mesh_subnet * sub)2441 void bt_mesh_store_p_subnet(struct bt_mesh_subnet *sub)
2442 {
2443     if (sub == NULL) {
2444         BT_ERR("Invalid subnet");
2445         return;
2446     }
2447 
2448     BT_DBG("NetKeyIndex 0x%03x NetKey %s", sub->net_idx,
2449         bt_hex(sub->keys[0].net, 16));
2450 
2451     store_p_net_key(sub);
2452 }
2453 
bt_mesh_store_p_app_key(struct bt_mesh_app_key * key)2454 void bt_mesh_store_p_app_key(struct bt_mesh_app_key *key)
2455 {
2456     if (key == NULL) {
2457         BT_ERR("Invalid AppKey");
2458         return;
2459     }
2460 
2461     BT_DBG("AppKeyIndex 0x%03x AppKey %s", key->app_idx,
2462         bt_hex(key->keys[0].val, 16));
2463 
2464     store_p_app_key(key);
2465 }
2466 
bt_mesh_clear_p_subnet(uint16_t net_idx)2467 void bt_mesh_clear_p_subnet(uint16_t net_idx)
2468 {
2469     char name[16] = {'\0'};
2470     int err = 0;
2471 
2472     BT_DBG("NetKeyIndex 0x%03x", net_idx);
2473 
2474     sprintf(name, "mesh/pnk/%04x", net_idx);
2475     bt_mesh_erase_core_settings(name);
2476 
2477     err = bt_mesh_remove_core_settings_item("mesh/p_netkey", net_idx);
2478     if (err) {
2479         BT_ERR("Failed to remove 0x%04x from mesh/p_netkey", net_idx);
2480     }
2481 }
2482 
bt_mesh_clear_p_app_key(uint16_t app_idx)2483 void bt_mesh_clear_p_app_key(uint16_t app_idx)
2484 {
2485     char name[16] = {'\0'};
2486     int err = 0;
2487 
2488     BT_DBG("AppKeyIndex 0x%03x", app_idx);
2489 
2490     sprintf(name, "mesh/pak/%04x", app_idx);
2491     bt_mesh_erase_core_settings(name);
2492 
2493     err = bt_mesh_remove_core_settings_item("mesh/p_appkey", app_idx);
2494     if (err) {
2495         BT_ERR("Failed to remove 0x%04x from mesh/p_appkey", app_idx);
2496     }
2497 }
2498 
bt_mesh_clear_rpl_single(uint16_t src)2499 void bt_mesh_clear_rpl_single(uint16_t src)
2500 {
2501     char name[16] = {'\0'};
2502     int err = 0;
2503 
2504     if (!BLE_MESH_ADDR_IS_UNICAST(src)) {
2505         BT_ERR("Invalid src 0x%04x", src);
2506         return;
2507     }
2508 
2509     sprintf(name, "mesh/rpl/%04x", src);
2510     bt_mesh_erase_core_settings(name);
2511 
2512     err = bt_mesh_remove_core_settings_item("mesh/rpl", src);
2513     if (err) {
2514         BT_ERR("Failed to remove 0x%04x from mesh/rpl", src);
2515     }
2516 }
2517 
bt_mesh_store_node_info(struct bt_mesh_node * node)2518 void bt_mesh_store_node_info(struct bt_mesh_node *node)
2519 {
2520     struct node_info val = {0};
2521     char name[16] = {'\0'};
2522     int err = 0;
2523 
2524     if (node == NULL) {
2525         BT_ERR("Invalid node info");
2526         return;
2527     }
2528 
2529     memcpy(val.addr, node->addr, BLE_MESH_ADDR_LEN);
2530     val.addr_type = node->addr_type;
2531     memcpy(val.dev_uuid, node->dev_uuid, 16);
2532     val.oob_info = node->oob_info;
2533     val.unicast_addr = node->unicast_addr;
2534     val.element_num = node->element_num;
2535     val.net_idx = node->net_idx;
2536     val.flags = node->flags;
2537     val.iv_index = node->iv_index;
2538     memcpy(val.dev_key, node->dev_key, 16);
2539 
2540     sprintf(name, "mesh/pn/%04x/i", node->unicast_addr);
2541     err = bt_mesh_save_core_settings(name, (const uint8_t *)&val, sizeof(val));
2542     if (err) {
2543         BT_ERR("Failed to store node 0x%04x info", node->unicast_addr);
2544         return;
2545     }
2546 
2547     err = bt_mesh_add_core_settings_item("mesh/p_node", node->unicast_addr);
2548     if (err) {
2549         BT_ERR("Failed to add node 0x%04x info", node->unicast_addr);
2550     }
2551 }
2552 
clear_node(uint16_t addr)2553 static void clear_node(uint16_t addr)
2554 {
2555     char name[16] = {'\0'};
2556     int err = 0;
2557 
2558     /* Clear node information */
2559     sprintf(name, "mesh/pn/%04x/i", addr);
2560     bt_mesh_erase_core_settings(name);
2561 
2562     /* Clear node name */
2563     sprintf(name, "mesh/pn/%04x/n", addr);
2564     bt_mesh_erase_core_settings(name);
2565 
2566     /* Clear node composition data */
2567     sprintf(name, "mesh/pn/%04x/c", addr);
2568     bt_mesh_erase_core_settings(name);
2569 
2570     err = bt_mesh_remove_core_settings_item("mesh/p_node", addr);
2571     if (err) {
2572         BT_ERR("Failed to remove node 0x%04x", addr);
2573     }
2574 }
2575 
bt_mesh_clear_node_info(uint16_t unicast_addr)2576 void bt_mesh_clear_node_info(uint16_t unicast_addr)
2577 {
2578     if (!BLE_MESH_ADDR_IS_UNICAST(unicast_addr)) {
2579         BT_ERR("Invalid unicast address 0x%04x", unicast_addr);
2580         return;
2581     }
2582 
2583     BT_DBG("Unicast address 0x%04x", unicast_addr);
2584 
2585     clear_node(unicast_addr);
2586 }
2587 
bt_mesh_store_node_name(struct bt_mesh_node * node)2588 void bt_mesh_store_node_name(struct bt_mesh_node *node)
2589 {
2590     char node_name[BLE_MESH_NODE_NAME_SIZE + 1] = {0};
2591     char name[16] = {'\0'};
2592     int err = 0;
2593 
2594     if (node == NULL) {
2595         BT_ERR("Invalid node info");
2596         return;
2597     }
2598 
2599     strncpy(node_name, node->name, BLE_MESH_NODE_NAME_SIZE + 1);
2600 
2601     sprintf(name, "mesh/pn/%04x/n", node->unicast_addr);
2602     err = bt_mesh_save_core_settings(name, (const uint8_t *)node_name, BLE_MESH_NODE_NAME_SIZE);
2603     if (err) {
2604         BT_ERR("Failed to store node 0x%04x name", node->unicast_addr);
2605     }
2606 }
2607 
bt_mesh_store_node_comp_data(struct bt_mesh_node * node)2608 void bt_mesh_store_node_comp_data(struct bt_mesh_node *node)
2609 {
2610     char name[16] = {'\0'};
2611     int err = 0;
2612 
2613     if (!node || !node->comp_data || node->comp_length == 0U) {
2614         BT_ERR("Invalid node info");
2615         return;
2616     }
2617 
2618     sprintf(name, "mesh/pn/%04x/c", node->unicast_addr);
2619     err = bt_mesh_save_core_settings(name, (const uint8_t *)node->comp_data, node->comp_length);
2620     if (err) {
2621         BT_ERR("Failed to store node 0x%04x comp data", node->unicast_addr);
2622     }
2623 }
2624 #endif /* CONFIG_BLE_MESH_PROVISIONER */
2625 
settings_core_init(void)2626 int settings_core_init(void)
2627 {
2628     k_delayed_work_init(&pending_store, store_pending);
2629     return 0;
2630 }
2631 
bt_mesh_settings_init(void)2632 int bt_mesh_settings_init(void)
2633 {
2634     bt_mesh_settings_mutex_new();
2635     bt_mesh_settings_init_foreach();
2636     return 0;
2637 }
2638 
2639 #if CONFIG_BLE_MESH_DEINIT
settings_core_deinit(void)2640 int settings_core_deinit(void)
2641 {
2642     k_delayed_work_free(&pending_store);
2643     return 0;
2644 }
2645 
settings_core_erase(void)2646 int settings_core_erase(void)
2647 {
2648     /* Erase here must not use the pending_store timer.
2649      * This is used for erasing the information which
2650      * could not be erased during the previous deinit
2651      * operations.
2652      */
2653     bt_mesh_clear_net();
2654     bt_mesh_clear_seq();
2655     bt_mesh_clear_role();
2656     return 0;
2657 }
2658 
bt_mesh_settings_deinit(bool erase)2659 int bt_mesh_settings_deinit(bool erase)
2660 {
2661     bt_mesh_settings_deinit_foreach(erase);
2662     bt_mesh_settings_mutex_free();
2663     return 0;
2664 }
2665 #endif /* CONFIG_BLE_MESH_DEINIT */
2666 
bt_mesh_settings_reset(bool erase)2667 void bt_mesh_settings_reset(bool erase)
2668 {
2669     k_delayed_work_cancel(&pending_store);
2670     if (erase) {
2671         bt_mesh_clear_net();
2672         bt_mesh_clear_seq();
2673         bt_mesh_clear_role();
2674     }
2675 }
2676 
2677 #endif /* CONFIG_BLE_MESH_SETTINGS */
2678