xref: /btstack/src/mesh/mesh.c (revision 380f8b85c88fc113944cec6ae73fc4e7888c7f99)
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 Network Keys
379 static uint32_t mesh_network_key_tag_for_internal_index(uint16_t internal_index){
380     return ((uint32_t) 'M' << 24) | ((uint32_t) 'N' << 16) | ((uint32_t) internal_index);
381 }
382 
383 void mesh_store_network_key(mesh_network_key_t * network_key){
384     mesh_persistent_net_key_t data;
385     printf("Store NetKey: internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
386     printf_hexdump(network_key->net_key, 16);
387     uint32_t tag = mesh_network_key_tag_for_internal_index(network_key->internal_index);
388     data.netkey_index = network_key->netkey_index;
389     memcpy(data.net_key, network_key->net_key, 16);
390     memcpy(data.identity_key, network_key->identity_key, 16);
391     memcpy(data.beacon_key, network_key->beacon_key, 16);
392     memcpy(data.network_id, network_key->network_id, 8);
393     data.nid = network_key->nid;
394     data.version = network_key->version;
395     memcpy(data.encryption_key, network_key->encryption_key, 16);
396     memcpy(data.privacy_key, network_key->privacy_key, 16);
397     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_net_key_t));
398 }
399 
400 void mesh_delete_network_key(uint16_t internal_index){
401     uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
402     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
403 }
404 
405 
406 void mesh_load_network_keys(void){
407     printf("Load Network Keys\n");
408     uint16_t internal_index;
409     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
410         mesh_persistent_net_key_t data;
411         uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
412         int netkey_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
413         if (netkey_len != sizeof(mesh_persistent_net_key_t)) continue;
414 
415         mesh_network_key_t * network_key = btstack_memory_mesh_network_key_get();
416         if (network_key == NULL) return;
417 
418         network_key->netkey_index = data.netkey_index;
419         memcpy(network_key->net_key, data.net_key, 16);
420         memcpy(network_key->identity_key, data.identity_key, 16);
421         memcpy(network_key->beacon_key, data.beacon_key, 16);
422         memcpy(network_key->network_id, data.network_id, 8);
423         network_key->nid = data.nid;
424         network_key->version = data.version;
425         memcpy(network_key->encryption_key, data.encryption_key, 16);
426         memcpy(network_key->privacy_key, data.privacy_key, 16);
427 
428 #ifdef ENABLE_GATT_BEARER
429         // setup advertisement with network id
430         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);
431 #endif
432 
433         mesh_network_key_add(network_key);
434 
435         mesh_subnet_setup_for_netkey_index(network_key->netkey_index);
436 
437         printf("- internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
438         printf_hexdump(network_key->net_key, 16);
439     }
440 }
441 
442 void mesh_delete_network_keys(void){
443     printf("Delete Network Keys\n");
444 
445     uint16_t internal_index;
446     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
447         mesh_delete_network_key(internal_index);
448     }
449 }
450 
451 // Mesh App Keys
452 
453 static uint32_t mesh_transport_key_tag_for_internal_index(uint16_t internal_index){
454     return ((uint32_t) 'M' << 24) | ((uint32_t) 'A' << 16) | ((uint32_t) internal_index);
455 }
456 
457 void mesh_store_app_key(mesh_transport_key_t * app_key){
458     mesh_persistent_app_key_t data;
459     printf("Store AppKey: internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", app_key->internal_index, app_key->appkey_index, app_key->aid);
460     printf_hexdump(app_key->key, 16);
461     uint32_t tag = mesh_transport_key_tag_for_internal_index(app_key->internal_index);
462     data.netkey_index = app_key->netkey_index;
463     data.appkey_index = app_key->appkey_index;
464     data.aid = app_key->aid;
465     data.version = app_key->version;
466     memcpy(data.key, app_key->key, 16);
467     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
468 }
469 
470 void mesh_delete_app_key(uint16_t internal_index){
471     uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
472     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
473 }
474 
475 void mesh_load_app_keys(void){
476     printf("Load App Keys\n");
477     uint16_t internal_index;
478     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
479         mesh_persistent_app_key_t data;
480         uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
481         int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
482         if (app_key_len == 0) continue;
483 
484         mesh_transport_key_t * key = btstack_memory_mesh_transport_key_get();
485         if (key == NULL) return;
486 
487         key->internal_index = internal_index;
488         key->appkey_index = data.appkey_index;
489         key->netkey_index = data.netkey_index;
490         key->aid          = data.aid;
491         key->akf          = 1;
492         key->version      = data.version;
493         memcpy(key->key, data.key, 16);
494         mesh_transport_key_add(key);
495         printf("- internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", key->internal_index, key->appkey_index, key->aid);
496         printf_hexdump(key->key, 16);
497     }
498 }
499 
500 void mesh_delete_app_keys(void){
501     printf("Delete App Keys\n");
502 
503     uint16_t internal_index;
504     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
505         mesh_delete_app_key(internal_index);
506     }
507 }
508 
509 
510 // Model to Appkey List
511 
512 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
513     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
514 }
515 
516 static void mesh_load_appkey_list(mesh_model_t * model){
517     uint32_t tag = mesh_model_tag_for_index(model->mid);
518     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
519 }
520 
521 static void mesh_store_appkey_list(mesh_model_t * model){
522     uint32_t tag = mesh_model_tag_for_index(model->mid);
523     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
524 }
525 
526 static void mesh_delete_appkey_list(mesh_model_t * model){
527     uint32_t tag = mesh_model_tag_for_index(model->mid);
528     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
529 }
530 
531 void mesh_load_appkey_lists(void){
532     printf("Load Appkey Lists\n");
533     // iterate over elements and models
534     mesh_element_iterator_t element_it;
535     mesh_element_iterator_init(&element_it);
536     while (mesh_element_iterator_has_next(&element_it)){
537         mesh_element_t * element = mesh_element_iterator_next(&element_it);
538         mesh_model_iterator_t model_it;
539         mesh_model_iterator_init(&model_it, element);
540         while (mesh_model_iterator_has_next(&model_it)){
541             mesh_model_t * model = mesh_model_iterator_next(&model_it);
542             mesh_load_appkey_list(model);
543         }
544     }
545 }
546 
547 void mesh_delete_appkey_lists(void){
548     printf("Delete Appkey Lists\n");
549     // iterate over elements and models
550     mesh_element_iterator_t element_it;
551     mesh_element_iterator_init(&element_it);
552     while (mesh_element_iterator_has_next(&element_it)){
553         mesh_element_t * element = mesh_element_iterator_next(&element_it);
554         mesh_model_iterator_t model_it;
555         mesh_model_iterator_init(&model_it, element);
556         while (mesh_model_iterator_has_next(&model_it)){
557             mesh_model_t * model = mesh_model_iterator_next(&model_it);
558             mesh_delete_appkey_list(model);
559         }
560     }
561 }
562 
563 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
564     uint16_t i;
565     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
566         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
567     }
568     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
569         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
570             mesh_model->appkey_indices[i] = appkey_index;
571             mesh_store_appkey_list(mesh_model);
572             return MESH_FOUNDATION_STATUS_SUCCESS;
573         }
574     }
575     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
576 }
577 
578 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
579     uint16_t i;
580     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
581         if (mesh_model->appkey_indices[i] == appkey_index) {
582             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
583             mesh_store_appkey_list(mesh_model);
584         }
585     }
586 }
587 
588 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
589     uint16_t i;
590     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
591         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
592     }
593     return 0;
594 }
595 
596 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
597     mesh_network_key_remove(network_key);
598     mesh_delete_network_key(network_key->internal_index);
599     btstack_memory_mesh_network_key_free(network_key);
600 }
601 
602 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
603     mesh_transport_key_remove(transport_key);
604     mesh_delete_app_key(transport_key->appkey_index);
605     btstack_memory_mesh_transport_key_free(transport_key);
606 }
607 
608 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
609     // delete old netkey index
610     mesh_access_netkey_finalize(subnet->old_key);
611     subnet->old_key = subnet->new_key;
612     subnet->new_key = NULL;
613 
614     // delete old appkeys, if any
615     mesh_transport_key_iterator_t it;
616     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
617     while (mesh_transport_key_iterator_has_more(&it)){
618         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
619         if (transport_key->old_key == 0) continue;
620         mesh_access_appkey_finalize(transport_key);
621     }
622 }
623 
624 // Mesh IV Index
625 static uint32_t mesh_tag_for_iv_index_and_seq_number(void){
626     return ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S');
627 }
628 
629 void mesh_store_iv_index_after_provisioning(uint32_t iv_index){
630     iv_index_and_sequence_number_t data;
631     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
632     data.iv_index   = iv_index;
633     data.seq_number = 0;
634     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
635 
636     sequence_number_last_stored = data.seq_number;
637     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
638 }
639 
640 void mesh_store_iv_index_and_sequence_number(void){
641     iv_index_and_sequence_number_t data;
642     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
643     data.iv_index   = mesh_get_iv_index();
644     data.seq_number = mesh_sequence_number_peek();
645     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
646 
647     sequence_number_last_stored = data.seq_number;
648     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
649 }
650 
651 int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
652     iv_index_and_sequence_number_t data;
653     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
654     uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
655     if (len == sizeof(iv_index_and_sequence_number_t)){
656         *iv_index = data.iv_index;
657         *sequence_number = data.seq_number;
658         return 1;
659     }
660     return 0;
661 }
662 
663 // higher layer
664 static void mesh_persist_iv_index_and_sequence_number(void){
665     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
666         mesh_store_iv_index_and_sequence_number();
667     }
668 }
669 
670 
671 static void mesh_node_setup_default_models(void){
672     // configure Config Server
673     mesh_configuration_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER);
674     mesh_configuration_server_model.model_data       = &mesh_configuration_server_model_context;
675     mesh_configuration_server_model.operations       = mesh_configuration_server_get_operations();
676     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_configuration_server_model);
677 
678     // Config Health Server
679     mesh_health_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_HEALTH_SERVER);
680     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_health_server_model);
681 }
682 
683 void mesh_init(void){
684 
685     // register for HCI events
686     hci_event_callback_registration.callback = &hci_packet_handler;
687     hci_add_event_handler(&hci_event_callback_registration);
688 
689     // ADV Bearer also used for GATT Proxy Advertisements and PB-GATT
690     adv_bearer_init();
691 
692 #ifdef ENABLE_MESH_GATT_BEARER
693     // Setup GATT bearer
694     gatt_bearer_init();
695 #endif
696 
697 #ifdef ENABLE_MESH_ADV_BEARER
698     // Setup Unprovisioned Device Beacon
699     beacon_init();
700 #endif
701 
702     provisioning_device_init();
703 
704     // Node Configuration
705     mesh_node_init();
706 
707     // Network layer
708     mesh_network_init();
709 
710     // Transport layers (lower + upper))
711     mesh_lower_transport_init();
712     mesh_upper_transport_init();
713 
714     // Access layer
715     mesh_access_init();
716 
717     // Add mandatory models: Config Server and Health Server
718     mesh_node_setup_default_models();
719 
720     // register for seq number updates
721     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number);
722 }
723 
724 /**
725  * Register for Mesh Provisioning Device events
726  * @param packet_handler
727  */
728 void mesh_register_provisioning_device_packet_handler(btstack_packet_handler_t packet_handler){
729     provisioning_device_packet_handler = packet_handler;
730     provisioning_device_register_packet_handler(&mesh_provisioning_message_handler);
731 }
732