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