xref: /btstack/src/mesh/mesh.c (revision d4c397cd4aaafdd64ec003296c815486cb1cb567)
1 /*
2  * Copyright (C) 2019 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "mesh.c"
39 
40 #include <string.h>
41 #include <stdio.h>
42 
43 #include "mesh/mesh.h"
44 
45 #include "btstack_util.h"
46 #include "btstack_config.h"
47 #include "btstack_event.h"
48 #include "btstack_tlv.h"
49 #include "btstack_memory.h"
50 #include "btstack_debug.h"
51 
52 #include "mesh/adv_bearer.h"
53 #include "mesh/beacon.h"
54 #include "mesh/gatt_bearer.h"
55 #include "mesh/mesh_access.h"
56 #include "mesh/mesh_configuration_server.h"
57 #include "mesh/mesh_foundation.h"
58 #include "mesh/mesh_generic_model.h"
59 #include "mesh/mesh_generic_server.h"
60 #include "mesh/mesh_iv_index_seq_number.h"
61 #include "mesh/mesh_lower_transport.h"
62 #include "mesh/mesh_peer.h"
63 #include "mesh/mesh_proxy.h"
64 #include "mesh/mesh_upper_transport.h"
65 #include "mesh/mesh_virtual_addresses.h"
66 #include "mesh/pb_adv.h"
67 #include "mesh/pb_gatt.h"
68 #include "mesh/provisioning.h"
69 #include "mesh/provisioning_device.h"
70 
71 // Persistent storage structures
72 
73 typedef struct {
74     uint16_t  hash;
75     uint8_t   label_uuid[16];
76 } mesh_persistent_virtual_address_t;
77 
78 typedef struct {
79     uint16_t netkey_index;
80 
81     uint8_t  version;
82 
83     // net_key from provisioner or Config Model Client
84     uint8_t net_key[16];
85 
86     // derived data
87 
88     // k1
89     uint8_t identity_key[16];
90     uint8_t beacon_key[16];
91 
92     // k3
93     uint8_t network_id[8];
94 
95     // k2
96     uint8_t nid;
97     uint8_t encryption_key[16];
98     uint8_t privacy_key[16];
99 } mesh_persistent_net_key_t;
100 
101 typedef struct {
102     uint16_t netkey_index;
103     uint16_t appkey_index;
104     uint8_t  aid;
105     uint8_t  version;
106     uint8_t  key[16];
107 } mesh_persistent_app_key_t;
108 
109 typedef struct {
110     uint8_t gatt_proxy;
111     uint8_t beacon;
112     uint8_t default_ttl;
113     uint8_t network_transmit;
114     uint8_t relay;
115     uint8_t relay_retransmit;
116     uint8_t friend;
117 } mesh_persistent_foundation_t;
118 
119 typedef struct {
120     uint32_t iv_index;
121     uint32_t seq_number;
122 } iv_index_and_sequence_number_t;
123 
124 static btstack_packet_handler_t provisioning_device_packet_handler;
125 static btstack_packet_callback_registration_t hci_event_callback_registration;
126 static int provisioned;
127 
128 // Mandatory Confiuration Server
129 static mesh_model_t                 mesh_configuration_server_model;
130 
131 // Mandatory Health Server
132 static mesh_model_t                 mesh_health_server_model;
133 static mesh_configuration_server_model_context_t mesh_configuration_server_model_context;
134 
135 // Random UUID on start
136 static btstack_crypto_random_t mesh_access_crypto_random;
137 static uint8_t random_device_uuid[16];
138 
139 // TLV
140 static const btstack_tlv_t * btstack_tlv_singleton_impl;
141 static void *                btstack_tlv_singleton_context;
142 
143 // IV Index persistence
144 static uint32_t sequence_number_last_stored;
145 static uint32_t sequence_number_storage_trigger;
146 
147 
148 void mesh_access_setup_from_provisioning_data(const mesh_provisioning_data_t * provisioning_data){
149 
150     // set iv_index and iv index update active
151     int iv_index_update_active = (provisioning_data->flags & 2) >> 1;
152     mesh_iv_index_recovered(iv_index_update_active, provisioning_data->iv_index);
153 
154     // set unicast address
155     mesh_node_primary_element_address_set(provisioning_data->unicast_address);
156 
157     // set device_key
158     mesh_transport_set_device_key(provisioning_data->device_key);
159 
160     if (provisioning_data->network_key){
161 
162         // setup primary network with provisioned netkey
163         mesh_network_key_add(provisioning_data->network_key);
164 
165         // setup primary network
166         mesh_subnet_setup_for_netkey_index(provisioning_data->network_key->netkey_index);
167 
168         // start sending Secure Network Beacons
169         mesh_subnet_t * provisioned_subnet = mesh_subnet_get_by_netkey_index(provisioning_data->network_key->netkey_index);
170         beacon_secure_network_start(provisioned_subnet);
171     }
172 
173     // Mesh Proxy
174 #ifdef ENABLE_MESH_PROXY_SERVER
175     // Setup Proxy
176     mesh_proxy_init(provisioning_data->unicast_address);
177     mesh_proxy_start_advertising_with_network_id();
178 #endif
179 }
180 
181 static void mesh_access_setup_unprovisioned_device(void * arg){
182     // set random value
183     if (arg == NULL){
184         mesh_node_set_device_uuid(random_device_uuid);
185     }
186 
187 #ifdef ENABLE_MESH_PB_ADV
188     // PB-ADV
189     beacon_unprovisioned_device_start(mesh_node_get_device_uuid(), 0);
190 #endif
191 #ifdef ENABLE_MESH_PB_GATT
192     mesh_proxy_start_advertising_unprovisioned_device();
193 #endif
194 }
195 
196 void mesh_access_setup_without_provisiong_data(void){
197     const uint8_t * device_uuid = mesh_node_get_device_uuid();
198     if (device_uuid){
199         mesh_access_setup_unprovisioned_device((void *)device_uuid);
200     } else{
201         btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_unprovisioned_device, NULL);
202     }
203 }
204 
205 static void mesh_provisioning_message_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
206     mesh_provisioning_data_t provisioning_data;
207 
208     switch(packet[0]){
209         case HCI_EVENT_MESH_META:
210             switch(packet[2]){
211                 case MESH_SUBEVENT_PB_PROV_COMPLETE:
212                     // get provisioning data
213                     provisioning_device_data_get(&provisioning_data);
214 
215                     // and store in TLV
216                     mesh_node_store_provisioning_data(&provisioning_data);
217 
218                     // setup node after provisioned
219                     mesh_access_setup_from_provisioning_data(&provisioning_data);
220 
221                     // start advertising with node id after provisioning
222                     mesh_proxy_set_advertising_with_node_id(provisioning_data.network_key->netkey_index, MESH_NODE_IDENTITY_STATE_ADVERTISING_RUNNING);
223 
224                     provisioned = 1;
225                     break;
226                 default:
227                     break;
228             }
229             break;
230         default:
231             break;
232     }
233     if (provisioning_device_packet_handler == NULL) return;
234 
235     // forward
236     (*provisioning_device_packet_handler)(packet_type, channel, packet, size);
237 }
238 
239 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
240     UNUSED(channel);
241     UNUSED(size);
242 
243     switch (packet_type) {
244         case HCI_EVENT_PACKET:
245             switch (hci_event_packet_get_type(packet)) {
246                 case BTSTACK_EVENT_STATE:
247                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
248                     // get TLV instance
249                     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
250 
251                     // startup from provisioning data stored in TLV
252                     provisioned = mesh_node_startup_from_tlv();
253                     break;
254 
255                 case HCI_EVENT_DISCONNECTION_COMPLETE:
256                     // enable PB_GATT
257                     if (provisioned == 0){
258                         mesh_proxy_start_advertising_unprovisioned_device();
259                     } else {
260 #ifdef ENABLE_MESH_PROXY_SERVER
261                         mesh_proxy_start_advertising_with_network_id();
262 #endif
263                     }
264                     break;
265 
266                 case HCI_EVENT_LE_META:
267                     if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
268                     // disable PB_GATT
269                     mesh_proxy_stop_advertising_unprovisioned_device();
270                     break;
271                 default:
272                     break;
273             }
274             break;
275     }
276 }
277 
278 // Foundation state
279 static const uint32_t mesh_foundation_state_tag = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16)  | ((uint32_t) 'N' << 8) | ((uint32_t) 'D' << 8);
280 
281 void mesh_foundation_state_load(void){
282     mesh_persistent_foundation_t data;
283 
284     int foundation_state_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
285     if (foundation_state_len != sizeof(data)) return;
286 
287     mesh_foundation_gatt_proxy_set(data.gatt_proxy);
288     mesh_foundation_beacon_set(data.gatt_proxy);
289     mesh_foundation_default_ttl_set(data.default_ttl);
290     mesh_foundation_friend_set(data.friend);
291     mesh_foundation_network_transmit_set(data.network_transmit);
292     mesh_foundation_relay_set(data.relay);
293     mesh_foundation_relay_retransmit_set(data.relay_retransmit);
294 }
295 
296 void mesh_foundation_state_store(void){
297     mesh_persistent_foundation_t data;
298     data.gatt_proxy       = mesh_foundation_gatt_proxy_get();
299     data.gatt_proxy       = mesh_foundation_beacon_get();
300     data.default_ttl      = mesh_foundation_default_ttl_get();
301     data.friend           = mesh_foundation_friend_get();
302     data.network_transmit = mesh_foundation_network_transmit_get();
303     data.relay            = mesh_foundation_relay_get();
304     data.relay_retransmit = mesh_foundation_relay_retransmit_get();
305     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
306 }
307 
308 // Mesh Virtual Address Management
309 static uint32_t mesh_virtual_address_tag_for_pseudo_dst(uint16_t pseudo_dst){
310     return ((uint32_t) 'M' << 24) | ((uint32_t) 'V' << 16) | ((uint32_t) pseudo_dst);
311 }
312 
313 static void mesh_store_virtual_address(uint16_t pseudo_dest, uint16_t hash, const uint8_t * label_uuid){
314     mesh_persistent_virtual_address_t data;
315     uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dest);
316     data.hash = hash;
317     memcpy(data.label_uuid, label_uuid, 16);
318     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
319 }
320 
321 static void mesh_delete_virtual_address(uint16_t pseudo_dest){
322     uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dest);
323     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
324 }
325 
326 void mesh_load_virtual_addresses(void){
327     uint16_t pseudo_dst;
328     for (pseudo_dst = 0x8000; pseudo_dst < (0x8000 + MAX_NR_MESH_VIRTUAL_ADDRESSES); pseudo_dst++){
329         mesh_virtual_address_tag_for_pseudo_dst(pseudo_dst);
330         mesh_persistent_virtual_address_t data;
331         uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dst);
332         int virtual_address_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
333         if (virtual_address_len == 0) return;
334 
335         mesh_virtual_address_t * virtual_address = btstack_memory_mesh_virtual_address_get();
336         if (virtual_address == NULL) return;
337 
338         virtual_address->pseudo_dst = pseudo_dst;
339         virtual_address->hash = data.hash;
340         memcpy(virtual_address->label_uuid, data.label_uuid, 16);
341         mesh_virtual_address_add(virtual_address);
342     }
343 }
344 
345 void mesh_delete_virtual_addresses(void){
346     uint16_t pseudo_dest;
347     for (pseudo_dest = 0x8000; pseudo_dest < (0x8000 + MAX_NR_MESH_VIRTUAL_ADDRESSES); pseudo_dest++){
348         mesh_delete_virtual_address(pseudo_dest);
349     }
350 }
351 
352 void mesh_virtual_address_decrease_refcount(mesh_virtual_address_t * virtual_address){
353     if (virtual_address == NULL){
354         log_error("virtual_address == NULL");
355     }
356     // decrease refcount
357     virtual_address->ref_count--;
358     // Free virtual address if ref count reaches zero
359     if (virtual_address->ref_count > 0) return;
360     // delete from TLV
361     mesh_delete_virtual_address(virtual_address->pseudo_dst);
362     // remove from list
363     mesh_virtual_address_remove(virtual_address);
364     // free memory
365     btstack_memory_mesh_virtual_address_free(virtual_address);
366 }
367 
368 void mesh_virtual_address_increase_refcount(mesh_virtual_address_t * virtual_address){
369     if (virtual_address == NULL){
370         log_error("virtual_address == NULL");
371     }
372     virtual_address->ref_count++;
373     if (virtual_address->ref_count > 1) return;
374     // store in TLV
375     mesh_store_virtual_address(virtual_address->pseudo_dst, virtual_address->hash, virtual_address->label_uuid);
376 }
377 
378 // Mesh Subscriptions
379 static uint32_t mesh_model_subscription_tag_for_index(uint16_t internal_model_id){
380     return ((uint32_t) 'M' << 24) | ((uint32_t) 'S' << 16) | ((uint32_t) internal_model_id);
381 }
382 
383 static void mesh_model_load_subscriptions(mesh_model_t * mesh_model){
384     uint32_t tag = mesh_model_subscription_tag_for_index(mesh_model->mid);
385     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &mesh_model->subscriptions, sizeof(mesh_model->subscriptions));
386     // update ref count
387 
388     // increase ref counts for virtual subscriptions
389     uint16_t i;
390     for (i = 0; i<MAX_NR_MESH_SUBSCRIPTION_PER_MODEL ; i++){
391         uint16_t src = mesh_model->subscriptions[i];
392         if (mesh_network_address_virtual(src)){
393             mesh_virtual_address_t * virtual_address = mesh_virtual_address_for_pseudo_dst(src);
394             mesh_virtual_address_increase_refcount(virtual_address);
395         }
396     }
397 }
398 
399 void mesh_model_store_subscriptions(mesh_model_t * model){
400     uint32_t tag = mesh_model_subscription_tag_for_index(model->mid);
401     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->subscriptions, sizeof(model->subscriptions));
402 }
403 
404 static void mesh_model_delete_subscriptions(mesh_model_t * model){
405     uint32_t tag = mesh_model_subscription_tag_for_index(model->mid);
406     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
407 }
408 
409 void mesh_load_subscriptions(void){
410     printf("Load Model Subscription Lists\n");
411     // iterate over elements and models
412     mesh_element_iterator_t element_it;
413     mesh_element_iterator_init(&element_it);
414     while (mesh_element_iterator_has_next(&element_it)){
415         mesh_element_t * element = mesh_element_iterator_next(&element_it);
416         mesh_model_iterator_t model_it;
417         mesh_model_iterator_init(&model_it, element);
418         while (mesh_model_iterator_has_next(&model_it)){
419             mesh_model_t * model = mesh_model_iterator_next(&model_it);
420             mesh_model_load_subscriptions(model);
421         }
422     }
423 }
424 
425 void mesh_delete_subscriptions(void){
426     printf("Delete Model Subscription Lists\n");
427     // iterate over elements and models
428     mesh_element_iterator_t element_it;
429     mesh_element_iterator_init(&element_it);
430     while (mesh_element_iterator_has_next(&element_it)){
431         mesh_element_t * element = mesh_element_iterator_next(&element_it);
432         mesh_model_iterator_t model_it;
433         mesh_model_iterator_init(&model_it, element);
434         while (mesh_model_iterator_has_next(&model_it)){
435             mesh_model_t * model = mesh_model_iterator_next(&model_it);
436             mesh_model_delete_subscriptions(model);
437         }
438     }
439 }
440 
441 // Model Publication
442 
443 static uint32_t mesh_model_publication_tag_for_index(uint16_t internal_model_id){
444     return ((uint32_t) 'M' << 24) | ((uint32_t) 'P' << 16) | ((uint32_t) internal_model_id);
445 }
446 
447 static void mesh_model_load_publication(mesh_model_t * mesh_model){
448     if (mesh_model->publication_model == NULL) return;
449 
450     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
451     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &mesh_model->publication_model, sizeof(mesh_publication_model_t));
452 
453     // increase ref counts for current virtual publicataion address
454     uint16_t src = mesh_model->publication_model->address;
455     if (mesh_network_address_virtual(src)){
456         mesh_virtual_address_t * virtual_address = mesh_virtual_address_for_pseudo_dst(src);
457         mesh_virtual_address_increase_refcount(virtual_address);
458     }
459 
460     mesh_model_publication_start(mesh_model);
461 }
462 
463 void mesh_model_store_publication(mesh_model_t * mesh_model){
464     if (mesh_model->publication_model == NULL) return;
465     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
466     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &mesh_model->subscriptions, sizeof(mesh_publication_model_t));
467 }
468 
469 static void mesh_model_delete_publication(mesh_model_t * mesh_model){
470     if (mesh_model->publication_model == NULL) return;
471     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
472     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
473 }
474 
475 void mesh_load_publications(void){
476     printf("Load Model Publications\n");
477     // iterate over elements and models
478     mesh_element_iterator_t element_it;
479     mesh_element_iterator_init(&element_it);
480     while (mesh_element_iterator_has_next(&element_it)){
481         mesh_element_t * element = mesh_element_iterator_next(&element_it);
482         mesh_model_iterator_t model_it;
483         mesh_model_iterator_init(&model_it, element);
484         while (mesh_model_iterator_has_next(&model_it)){
485             mesh_model_t * model = mesh_model_iterator_next(&model_it);
486             mesh_model_load_publication(model);
487         }
488     }
489 }
490 
491 void mesh_delete_publications(void){
492     printf("Delete Model Publications\n");
493     // iterate over elements and models
494     mesh_element_iterator_t element_it;
495     mesh_element_iterator_init(&element_it);
496     while (mesh_element_iterator_has_next(&element_it)){
497         mesh_element_t * element = mesh_element_iterator_next(&element_it);
498         mesh_model_iterator_t model_it;
499         mesh_model_iterator_init(&model_it, element);
500         while (mesh_model_iterator_has_next(&model_it)){
501             mesh_model_t * model = mesh_model_iterator_next(&model_it);
502             mesh_model_delete_publication(model);
503         }
504     }
505 }
506 
507 // Mesh Network Keys
508 static uint32_t mesh_network_key_tag_for_internal_index(uint16_t internal_index){
509     return ((uint32_t) 'M' << 24) | ((uint32_t) 'N' << 16) | ((uint32_t) internal_index);
510 }
511 
512 void mesh_store_network_key(mesh_network_key_t * network_key){
513     mesh_persistent_net_key_t data;
514     printf("Store NetKey: internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
515     printf_hexdump(network_key->net_key, 16);
516     uint32_t tag = mesh_network_key_tag_for_internal_index(network_key->internal_index);
517     data.netkey_index = network_key->netkey_index;
518     memcpy(data.net_key, network_key->net_key, 16);
519     memcpy(data.identity_key, network_key->identity_key, 16);
520     memcpy(data.beacon_key, network_key->beacon_key, 16);
521     memcpy(data.network_id, network_key->network_id, 8);
522     data.nid = network_key->nid;
523     data.version = network_key->version;
524     memcpy(data.encryption_key, network_key->encryption_key, 16);
525     memcpy(data.privacy_key, network_key->privacy_key, 16);
526     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_net_key_t));
527 }
528 
529 void mesh_delete_network_key(uint16_t internal_index){
530     uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
531     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
532 }
533 
534 
535 void mesh_load_network_keys(void){
536     printf("Load Network Keys\n");
537     uint16_t internal_index;
538     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
539         mesh_persistent_net_key_t data;
540         uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
541         int netkey_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
542         if (netkey_len != sizeof(mesh_persistent_net_key_t)) continue;
543 
544         mesh_network_key_t * network_key = btstack_memory_mesh_network_key_get();
545         if (network_key == NULL) return;
546 
547         network_key->netkey_index = data.netkey_index;
548         memcpy(network_key->net_key, data.net_key, 16);
549         memcpy(network_key->identity_key, data.identity_key, 16);
550         memcpy(network_key->beacon_key, data.beacon_key, 16);
551         memcpy(network_key->network_id, data.network_id, 8);
552         network_key->nid = data.nid;
553         network_key->version = data.version;
554         memcpy(network_key->encryption_key, data.encryption_key, 16);
555         memcpy(network_key->privacy_key, data.privacy_key, 16);
556 
557 #ifdef ENABLE_GATT_BEARER
558         // setup advertisement with network id
559         network_key->advertisement_with_network_id.adv_length = mesh_proxy_setup_advertising_with_network_id(network_key->advertisement_with_network_id.adv_data, network_key->network_id);
560 #endif
561 
562         mesh_network_key_add(network_key);
563 
564         mesh_subnet_setup_for_netkey_index(network_key->netkey_index);
565 
566         printf("- internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
567         printf_hexdump(network_key->net_key, 16);
568     }
569 }
570 
571 void mesh_delete_network_keys(void){
572     printf("Delete Network Keys\n");
573 
574     uint16_t internal_index;
575     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
576         mesh_delete_network_key(internal_index);
577     }
578 }
579 
580 // Mesh App Keys
581 
582 static uint32_t mesh_transport_key_tag_for_internal_index(uint16_t internal_index){
583     return ((uint32_t) 'M' << 24) | ((uint32_t) 'A' << 16) | ((uint32_t) internal_index);
584 }
585 
586 void mesh_store_app_key(mesh_transport_key_t * app_key){
587     mesh_persistent_app_key_t data;
588     printf("Store AppKey: internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", app_key->internal_index, app_key->appkey_index, app_key->aid);
589     printf_hexdump(app_key->key, 16);
590     uint32_t tag = mesh_transport_key_tag_for_internal_index(app_key->internal_index);
591     data.netkey_index = app_key->netkey_index;
592     data.appkey_index = app_key->appkey_index;
593     data.aid = app_key->aid;
594     data.version = app_key->version;
595     memcpy(data.key, app_key->key, 16);
596     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
597 }
598 
599 void mesh_delete_app_key(uint16_t internal_index){
600     uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
601     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
602 }
603 
604 void mesh_load_app_keys(void){
605     printf("Load App Keys\n");
606     uint16_t internal_index;
607     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
608         mesh_persistent_app_key_t data;
609         uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
610         int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
611         if (app_key_len == 0) continue;
612 
613         mesh_transport_key_t * key = btstack_memory_mesh_transport_key_get();
614         if (key == NULL) return;
615 
616         key->internal_index = internal_index;
617         key->appkey_index = data.appkey_index;
618         key->netkey_index = data.netkey_index;
619         key->aid          = data.aid;
620         key->akf          = 1;
621         key->version      = data.version;
622         memcpy(key->key, data.key, 16);
623         mesh_transport_key_add(key);
624         printf("- internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", key->internal_index, key->appkey_index, key->aid);
625         printf_hexdump(key->key, 16);
626     }
627 }
628 
629 void mesh_delete_app_keys(void){
630     printf("Delete App Keys\n");
631 
632     uint16_t internal_index;
633     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
634         mesh_delete_app_key(internal_index);
635     }
636 }
637 
638 
639 // Model to Appkey List
640 
641 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
642     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
643 }
644 
645 static void mesh_load_appkey_list(mesh_model_t * model){
646     uint32_t tag = mesh_model_tag_for_index(model->mid);
647     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
648 }
649 
650 static void mesh_store_appkey_list(mesh_model_t * model){
651     uint32_t tag = mesh_model_tag_for_index(model->mid);
652     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
653 }
654 
655 static void mesh_delete_appkey_list(mesh_model_t * model){
656     uint32_t tag = mesh_model_tag_for_index(model->mid);
657     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
658 }
659 
660 void mesh_load_appkey_lists(void){
661     printf("Load Appkey Lists\n");
662     // iterate over elements and models
663     mesh_element_iterator_t element_it;
664     mesh_element_iterator_init(&element_it);
665     while (mesh_element_iterator_has_next(&element_it)){
666         mesh_element_t * element = mesh_element_iterator_next(&element_it);
667         mesh_model_iterator_t model_it;
668         mesh_model_iterator_init(&model_it, element);
669         while (mesh_model_iterator_has_next(&model_it)){
670             mesh_model_t * model = mesh_model_iterator_next(&model_it);
671             mesh_load_appkey_list(model);
672         }
673     }
674 }
675 
676 void mesh_delete_appkey_lists(void){
677     printf("Delete Appkey Lists\n");
678     // iterate over elements and models
679     mesh_element_iterator_t element_it;
680     mesh_element_iterator_init(&element_it);
681     while (mesh_element_iterator_has_next(&element_it)){
682         mesh_element_t * element = mesh_element_iterator_next(&element_it);
683         mesh_model_iterator_t model_it;
684         mesh_model_iterator_init(&model_it, element);
685         while (mesh_model_iterator_has_next(&model_it)){
686             mesh_model_t * model = mesh_model_iterator_next(&model_it);
687             mesh_delete_appkey_list(model);
688         }
689     }
690 }
691 
692 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
693     uint16_t i;
694     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
695         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
696     }
697     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
698         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
699             mesh_model->appkey_indices[i] = appkey_index;
700             mesh_store_appkey_list(mesh_model);
701             return MESH_FOUNDATION_STATUS_SUCCESS;
702         }
703     }
704     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
705 }
706 
707 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
708     uint16_t i;
709     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
710         if (mesh_model->appkey_indices[i] == appkey_index) {
711             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
712             mesh_store_appkey_list(mesh_model);
713         }
714     }
715 }
716 
717 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
718     uint16_t i;
719     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
720         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
721     }
722     return 0;
723 }
724 
725 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
726     mesh_network_key_remove(network_key);
727     mesh_delete_network_key(network_key->internal_index);
728     btstack_memory_mesh_network_key_free(network_key);
729 }
730 
731 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
732     mesh_transport_key_remove(transport_key);
733     mesh_delete_app_key(transport_key->appkey_index);
734     btstack_memory_mesh_transport_key_free(transport_key);
735 }
736 
737 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
738     // delete old netkey index
739     mesh_access_netkey_finalize(subnet->old_key);
740     subnet->old_key = subnet->new_key;
741     subnet->new_key = NULL;
742 
743     // delete old appkeys, if any
744     mesh_transport_key_iterator_t it;
745     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
746     while (mesh_transport_key_iterator_has_more(&it)){
747         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
748         if (transport_key->old_key == 0) continue;
749         mesh_access_appkey_finalize(transport_key);
750     }
751 }
752 
753 // Mesh IV Index
754 static uint32_t mesh_tag_for_iv_index_and_seq_number(void){
755     return ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S');
756 }
757 
758 void mesh_store_iv_index_after_provisioning(uint32_t iv_index){
759     iv_index_and_sequence_number_t data;
760     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
761     data.iv_index   = iv_index;
762     data.seq_number = 0;
763     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
764 
765     sequence_number_last_stored = data.seq_number;
766     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
767 }
768 
769 void mesh_store_iv_index_and_sequence_number(void){
770     iv_index_and_sequence_number_t data;
771     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
772     data.iv_index   = mesh_get_iv_index();
773     data.seq_number = mesh_sequence_number_peek();
774     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
775 
776     sequence_number_last_stored = data.seq_number;
777     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
778 }
779 
780 int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
781     iv_index_and_sequence_number_t data;
782     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
783     uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
784     if (len == sizeof(iv_index_and_sequence_number_t)){
785         *iv_index = data.iv_index;
786         *sequence_number = data.seq_number;
787         return 1;
788     }
789     return 0;
790 }
791 
792 // higher layer
793 static void mesh_persist_iv_index_and_sequence_number(void){
794     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
795         mesh_store_iv_index_and_sequence_number();
796     }
797 }
798 
799 
800 static void mesh_node_setup_default_models(void){
801     // configure Config Server
802     mesh_configuration_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER);
803     mesh_configuration_server_model.model_data       = &mesh_configuration_server_model_context;
804     mesh_configuration_server_model.operations       = mesh_configuration_server_get_operations();
805     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_configuration_server_model);
806 
807     // Config Health Server
808     mesh_health_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_HEALTH_SERVER);
809     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_health_server_model);
810 }
811 
812 void mesh_init(void){
813 
814     // register for HCI events
815     hci_event_callback_registration.callback = &hci_packet_handler;
816     hci_add_event_handler(&hci_event_callback_registration);
817 
818     // ADV Bearer also used for GATT Proxy Advertisements and PB-GATT
819     adv_bearer_init();
820 
821 #ifdef ENABLE_MESH_GATT_BEARER
822     // Setup GATT bearer
823     gatt_bearer_init();
824 #endif
825 
826 #ifdef ENABLE_MESH_ADV_BEARER
827     // Setup Unprovisioned Device Beacon
828     beacon_init();
829 #endif
830 
831     provisioning_device_init();
832 
833     // Node Configuration
834     mesh_node_init();
835 
836     // Network layer
837     mesh_network_init();
838 
839     // Transport layers (lower + upper))
840     mesh_lower_transport_init();
841     mesh_upper_transport_init();
842 
843     // Access layer
844     mesh_access_init();
845 
846     // Add mandatory models: Config Server and Health Server
847     mesh_node_setup_default_models();
848 
849     // register for seq number updates
850     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number);
851 }
852 
853 /**
854  * Register for Mesh Provisioning Device events
855  * @param packet_handler
856  */
857 void mesh_register_provisioning_device_packet_handler(btstack_packet_handler_t packet_handler){
858     provisioning_device_packet_handler = packet_handler;
859     provisioning_device_register_packet_handler(&mesh_provisioning_message_handler);
860 }
861