xref: /btstack/src/mesh/mesh.c (revision c9921182ab4b1f83e3e5c671446dca5ffdf45b90)
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_health_server.h"
58 #include "mesh/mesh_foundation.h"
59 #include "mesh/mesh_generic_model.h"
60 #include "mesh/mesh_generic_on_off_server.h"
61 #include "mesh/mesh_iv_index_seq_number.h"
62 #include "mesh/mesh_lower_transport.h"
63 #include "mesh/mesh_peer.h"
64 #include "mesh/mesh_proxy.h"
65 #include "mesh/mesh_upper_transport.h"
66 #include "mesh/mesh_virtual_addresses.h"
67 #include "mesh/pb_adv.h"
68 #include "mesh/pb_gatt.h"
69 #include "mesh/provisioning.h"
70 #include "mesh/provisioning_device.h"
71 #include "mesh/provisioning_provisioner.h"
72 
73 static void mesh_node_store_provisioning_data(mesh_provisioning_data_t * provisioning_data);
74 static int mesh_node_startup_from_tlv(void);
75 
76 // Persistent storage structures
77 
78 typedef struct {
79     uint16_t  hash;
80     uint8_t   label_uuid[16];
81 } mesh_persistent_virtual_address_t;
82 
83 typedef struct {
84     uint16_t netkey_index;
85 
86     uint8_t  version;
87 
88     // net_key from provisioner or Config Model Client
89     uint8_t net_key[16];
90 
91     // derived data
92 
93     // k1
94     uint8_t identity_key[16];
95     uint8_t beacon_key[16];
96 
97     // k3
98     uint8_t network_id[8];
99 
100     // k2
101     uint8_t nid;
102     uint8_t encryption_key[16];
103     uint8_t privacy_key[16];
104 } mesh_persistent_net_key_t;
105 
106 typedef struct {
107     uint16_t netkey_index;
108     uint16_t appkey_index;
109     uint8_t  aid;
110     uint8_t  version;
111     uint8_t  key[16];
112 } mesh_persistent_app_key_t;
113 
114 typedef struct {
115     uint8_t gatt_proxy;
116     uint8_t beacon;
117     uint8_t default_ttl;
118     uint8_t network_transmit;
119     uint8_t relay;
120     uint8_t relay_retransmit;
121     uint8_t friend;
122 } mesh_persistent_foundation_t;
123 
124 typedef struct {
125     uint16_t publish_address;
126     uint16_t appkey_index;
127     uint8_t  friendship_credential_flag;
128     uint8_t  publish_period;
129     uint8_t  publish_ttl;
130     uint8_t  publish_retransmit;
131 } mesh_persistent_publication_t;
132 
133 typedef struct {
134     uint32_t iv_index;
135     uint32_t seq_number;
136 } iv_index_and_sequence_number_t;
137 
138 static btstack_packet_handler_t provisioning_device_packet_handler;
139 static btstack_packet_callback_registration_t hci_event_callback_registration;
140 static int provisioned;
141 
142 // Mandatory Confiuration Server
143 static mesh_model_t                 mesh_configuration_server_model;
144 static mesh_configuration_server_model_context_t mesh_configuration_server_model_context;
145 
146 // Mandatory Health Server
147 static mesh_publication_model_t     mesh_health_server_publication;
148 static mesh_model_t                 mesh_health_server_model;
149 static mesh_health_state_t  mesh_health_server_model_context;
150 
151 // Random UUID on start
152 static btstack_crypto_random_t mesh_access_crypto_random;
153 static uint8_t random_device_uuid[16];
154 
155 // TLV
156 static const btstack_tlv_t * btstack_tlv_singleton_impl;
157 static void *                btstack_tlv_singleton_context;
158 
159 // IV Index persistence
160 static uint32_t sequence_number_last_stored;
161 static uint32_t sequence_number_storage_trigger;
162 
163 // Attention Timer
164 static uint8_t                attention_timer_timeout_s;
165 static btstack_timer_source_t attention_timer_timer;
166 
167 // used to log all keys to packet log for log viewer
168 // mesh-appkey-0xxx: 1234567890abcdef1234567890abcdef
169 static void mesh_log_key(const char * prefix, uint16_t id, const uint8_t * key){
170     char line[60];
171     strcpy(line, prefix);
172     uint16_t pos = strlen(line);
173     if (id != 0xffff){
174         line[pos++] = '-';
175         line[pos++] = '0';
176         line[pos++] = char_for_nibble((id >> 8) & 0x0f);
177         line[pos++] = char_for_nibble((id >> 4) & 0x0f);
178         line[pos++] = char_for_nibble( id       & 0x0f);
179     }
180     line[pos++] = ':';
181     line[pos++] = ' ';
182     uint16_t i;
183     for (i=0;i<16;i++){
184         line[pos++] = char_for_nibble((key[i] >> 4) & 0x0f);
185         line[pos++] = char_for_nibble( key[i]       & 0x0f);
186     }
187     line[pos++] = 0;
188     hci_dump_log(HCI_DUMP_LOG_LEVEL_INFO, "%s", line);
189 }
190 
191 static void mesh_setup_from_provisioning_data(const mesh_provisioning_data_t * provisioning_data){
192 
193     // set iv_index and iv index update active
194     int iv_index_update_active = (provisioning_data->flags & 2) >> 1;
195     mesh_iv_index_recovered(iv_index_update_active, provisioning_data->iv_index);
196 
197     // set unicast address
198     mesh_node_primary_element_address_set(provisioning_data->unicast_address);
199 
200     // set device_key
201     mesh_transport_set_device_key(provisioning_data->device_key);
202 
203     if (provisioning_data->network_key){
204 
205         // setup primary network with provisioned netkey
206         mesh_network_key_add(provisioning_data->network_key);
207 
208         // setup primary network
209         mesh_subnet_setup_for_netkey_index(provisioning_data->network_key->netkey_index);
210 
211         // start sending Secure Network Beacons
212         mesh_subnet_t * provisioned_subnet = mesh_subnet_get_by_netkey_index(provisioning_data->network_key->netkey_index);
213         beacon_secure_network_start(provisioned_subnet);
214     }
215 
216     // Mesh Proxy
217 #ifdef ENABLE_MESH_PROXY_SERVER
218     // Setup Proxy
219     mesh_proxy_init(provisioning_data->unicast_address);
220     mesh_proxy_start_advertising_with_network_id();
221 #endif
222 }
223 
224 // Attention Timer state
225 static void mesh_emit_attention_timer_event(uint8_t timer_s){
226     if (!provisioning_device_packet_handler) return;
227     uint8_t event[4] = { HCI_EVENT_MESH_META, 4, MESH_SUBEVENT_ATTENTION_TIMER};
228     event[3] = timer_s;
229     provisioning_device_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
230 }
231 
232 static void mesh_attention_timer_handler(btstack_timer_source_t * ts){
233     UNUSED(ts);
234     attention_timer_timeout_s--;
235     mesh_emit_attention_timer_event(attention_timer_timeout_s);
236     if (attention_timer_timeout_s == 0) return;
237 
238     btstack_run_loop_set_timer(&attention_timer_timer, 1000);
239     btstack_run_loop_add_timer(&attention_timer_timer);
240 }
241 
242 void mesh_attention_timer_set(uint8_t timer_s){
243     // stop old timer if running
244     if (attention_timer_timeout_s){
245         btstack_run_loop_remove_timer(&attention_timer_timer);
246     }
247 
248     attention_timer_timeout_s = timer_s;
249     mesh_emit_attention_timer_event(attention_timer_timeout_s);
250 
251     if (attention_timer_timeout_s){
252         btstack_run_loop_set_timer_handler(&attention_timer_timer, &mesh_attention_timer_handler);
253         btstack_run_loop_set_timer(&attention_timer_timer, 1000);
254         btstack_run_loop_add_timer(&attention_timer_timer);
255     }
256 }
257 
258 uint8_t mesh_attention_timer_get(void){
259     return attention_timer_timeout_s;
260 }
261 
262 static void mesh_provisioning_message_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
263     mesh_provisioning_data_t provisioning_data;
264     switch(packet[0]){
265         case HCI_EVENT_MESH_META:
266             switch(packet[2]){
267                 case MESH_SUBEVENT_PB_PROV_ATTENTION_TIMER:
268                     mesh_attention_timer_set(mesh_subevent_pb_prov_attention_timer_get_attention_time(packet));
269                     break;
270                 case MESH_SUBEVENT_PB_PROV_COMPLETE:
271                     // get provisioning data
272                     provisioning_device_data_get(&provisioning_data);
273 
274                     // and store in TLV
275                     mesh_node_store_provisioning_data(&provisioning_data);
276 
277                     // setup node after provisioned
278                     mesh_setup_from_provisioning_data(&provisioning_data);
279 
280 #ifdef ENABLE_MESH_PROXY_SERVER
281                     // start advertising with node id after provisioning
282                     mesh_proxy_set_advertising_with_node_id(provisioning_data.network_key->netkey_index, MESH_NODE_IDENTITY_STATE_ADVERTISING_RUNNING);
283 #endif
284 
285                     provisioned = 1;
286                     break;
287                 default:
288                     break;
289             }
290             break;
291         default:
292             break;
293     }
294     if (provisioning_device_packet_handler == NULL) return;
295 
296     // forward
297     (*provisioning_device_packet_handler)(packet_type, channel, packet, size);
298 }
299 
300 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
301     UNUSED(channel);
302     UNUSED(size);
303 
304     switch (packet_type) {
305         case HCI_EVENT_PACKET:
306             switch (hci_event_packet_get_type(packet)) {
307                 case BTSTACK_EVENT_STATE:
308                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
309                     // get TLV instance
310                     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
311 
312                     // startup from static provisioning data stored in TLV
313                     provisioned = mesh_node_startup_from_tlv();
314                     break;
315 
316 #ifdef ENABLE_MESH_PROXY_SERVER
317                 case HCI_EVENT_DISCONNECTION_COMPLETE:
318                     // enable PB_GATT
319                     if (provisioned == 0){
320                         mesh_proxy_start_advertising_unprovisioned_device();
321                     } else {
322                         mesh_proxy_start_advertising_with_network_id();
323                     }
324                     break;
325 
326                 case HCI_EVENT_LE_META:
327                     if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
328                     // disable PB_GATT
329                     mesh_proxy_stop_advertising_unprovisioned_device();
330                     break;
331 #endif
332                 default:
333                     break;
334             }
335             break;
336     }
337 }
338 
339 static void report_store_error(int result, const char * type){
340     if (result != 0){
341         log_error("Store %s data failed", type);
342     }
343 }
344 
345 // Foundation state
346 static const uint32_t mesh_foundation_state_tag = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16)  | ((uint32_t) 'N' << 8) | ((uint32_t) 'D' << 8);
347 
348 void mesh_foundation_state_load(void){
349     mesh_persistent_foundation_t data;
350 
351     int foundation_state_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
352     if (foundation_state_len != sizeof(data)) return;
353 
354     mesh_foundation_gatt_proxy_set(data.gatt_proxy);
355     mesh_foundation_beacon_set(data.beacon);
356     mesh_foundation_default_ttl_set(data.default_ttl);
357     mesh_foundation_friend_set(data.friend);
358     mesh_foundation_network_transmit_set(data.network_transmit);
359     mesh_foundation_relay_set(data.relay);
360     mesh_foundation_relay_retransmit_set(data.relay_retransmit);
361 }
362 
363 void mesh_foundation_state_store(void){
364     mesh_persistent_foundation_t data;
365     data.gatt_proxy       = mesh_foundation_gatt_proxy_get();
366     data.beacon           = mesh_foundation_beacon_get();
367     data.default_ttl      = mesh_foundation_default_ttl_get();
368     data.friend           = mesh_foundation_friend_get();
369     data.network_transmit = mesh_foundation_network_transmit_get();
370     data.relay            = mesh_foundation_relay_get();
371     data.relay_retransmit = mesh_foundation_relay_retransmit_get();
372     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
373     report_store_error(result, "foundation");
374 }
375 
376 // Mesh Virtual Address Management
377 static uint32_t mesh_virtual_address_tag_for_pseudo_dst(uint16_t pseudo_dst){
378     return ((uint32_t) 'M' << 24) | ((uint32_t) 'V' << 16) | ((uint32_t) pseudo_dst);
379 }
380 
381 static void mesh_store_virtual_address(uint16_t pseudo_dest, uint16_t hash, const uint8_t * label_uuid){
382     mesh_persistent_virtual_address_t data;
383     uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dest);
384     data.hash = hash;
385     (void)memcpy(data.label_uuid, label_uuid, 16);
386     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
387     report_store_error(result, "virtual address");
388 }
389 
390 static void mesh_delete_virtual_address(uint16_t pseudo_dest){
391     uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dest);
392     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
393 }
394 
395 void mesh_load_virtual_addresses(void){
396     uint16_t pseudo_dst;
397     for (pseudo_dst = 0x8000; pseudo_dst < (0x8000 + MAX_NR_MESH_VIRTUAL_ADDRESSES); pseudo_dst++){
398         mesh_virtual_address_tag_for_pseudo_dst(pseudo_dst);
399         mesh_persistent_virtual_address_t data;
400         uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dst);
401         int virtual_address_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
402         if (virtual_address_len == 0) continue;
403 
404         mesh_virtual_address_t * virtual_address = btstack_memory_mesh_virtual_address_get();
405         if (virtual_address == NULL) return;
406 
407         virtual_address->pseudo_dst = pseudo_dst;
408         virtual_address->hash = data.hash;
409         (void)memcpy(virtual_address->label_uuid, data.label_uuid, 16);
410         mesh_virtual_address_add(virtual_address);
411     }
412 }
413 
414 void mesh_delete_virtual_addresses(void){
415     uint16_t pseudo_dest;
416     for (pseudo_dest = 0x8000; pseudo_dest < (0x8000 + MAX_NR_MESH_VIRTUAL_ADDRESSES); pseudo_dest++){
417         mesh_delete_virtual_address(pseudo_dest);
418     }
419 }
420 
421 void mesh_virtual_address_decrease_refcount(mesh_virtual_address_t * virtual_address){
422     if (virtual_address == NULL){
423         log_error("virtual_address == NULL");
424     }
425     // decrease refcount
426     virtual_address->ref_count--;
427     // Free virtual address if ref count reaches zero
428     if (virtual_address->ref_count > 0) return;
429     // delete from TLV
430     mesh_delete_virtual_address(virtual_address->pseudo_dst);
431     // remove from list
432     mesh_virtual_address_remove(virtual_address);
433     // free memory
434     btstack_memory_mesh_virtual_address_free(virtual_address);
435 }
436 
437 void mesh_virtual_address_increase_refcount(mesh_virtual_address_t * virtual_address){
438     if (virtual_address == NULL){
439         log_error("virtual_address == NULL");
440     }
441     virtual_address->ref_count++;
442     if (virtual_address->ref_count > 1) return;
443     // store in TLV
444     mesh_store_virtual_address(virtual_address->pseudo_dst, virtual_address->hash, virtual_address->label_uuid);
445 }
446 
447 // Mesh Subscriptions
448 static uint32_t mesh_model_subscription_tag_for_index(uint16_t internal_model_id){
449     return ((uint32_t) 'M' << 24) | ((uint32_t) 'S' << 16) | ((uint32_t) internal_model_id);
450 }
451 
452 static void mesh_model_load_subscriptions(mesh_model_t * mesh_model){
453     uint32_t tag = mesh_model_subscription_tag_for_index(mesh_model->mid);
454     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &mesh_model->subscriptions, sizeof(mesh_model->subscriptions));
455     // update ref count
456 
457     // increase ref counts for virtual subscriptions
458     uint16_t i;
459     for (i = 0; i<MAX_NR_MESH_SUBSCRIPTION_PER_MODEL ; i++){
460         uint16_t src = mesh_model->subscriptions[i];
461         if (mesh_network_address_virtual(src)){
462             mesh_virtual_address_t * virtual_address = mesh_virtual_address_for_pseudo_dst(src);
463             mesh_virtual_address_increase_refcount(virtual_address);
464         }
465     }
466 }
467 
468 void mesh_model_store_subscriptions(mesh_model_t * model){
469     uint32_t tag = mesh_model_subscription_tag_for_index(model->mid);
470     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->subscriptions, sizeof(model->subscriptions));
471     report_store_error(result, "subscription");
472 }
473 
474 static void mesh_model_delete_subscriptions(mesh_model_t * model){
475     uint32_t tag = mesh_model_subscription_tag_for_index(model->mid);
476     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
477 }
478 
479 void mesh_load_subscriptions(void){
480     printf("Load Model Subscription Lists\n");
481     // iterate over elements and models
482     mesh_element_iterator_t element_it;
483     mesh_element_iterator_init(&element_it);
484     while (mesh_element_iterator_has_next(&element_it)){
485         mesh_element_t * element = mesh_element_iterator_next(&element_it);
486         mesh_model_iterator_t model_it;
487         mesh_model_iterator_init(&model_it, element);
488         while (mesh_model_iterator_has_next(&model_it)){
489             mesh_model_t * model = mesh_model_iterator_next(&model_it);
490             mesh_model_load_subscriptions(model);
491         }
492     }
493 }
494 
495 void mesh_delete_subscriptions(void){
496     printf("Delete Model Subscription Lists\n");
497     // iterate over elements and models
498     mesh_element_iterator_t element_it;
499     mesh_element_iterator_init(&element_it);
500     while (mesh_element_iterator_has_next(&element_it)){
501         mesh_element_t * element = mesh_element_iterator_next(&element_it);
502         mesh_model_iterator_t model_it;
503         mesh_model_iterator_init(&model_it, element);
504         while (mesh_model_iterator_has_next(&model_it)){
505             mesh_model_t * model = mesh_model_iterator_next(&model_it);
506             mesh_model_delete_subscriptions(model);
507         }
508     }
509 }
510 
511 // Model Publication
512 
513 static uint32_t mesh_model_publication_tag_for_index(uint16_t internal_model_id){
514     return ((uint32_t) 'M' << 24) | ((uint32_t) 'P' << 16) | ((uint32_t) internal_model_id);
515 }
516 
517 static void mesh_model_load_publication(mesh_model_t * mesh_model){
518     mesh_publication_model_t * publication = mesh_model->publication_model;
519     if (publication == NULL) return;
520 
521     mesh_persistent_publication_t data;
522     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
523     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_publication_t));
524 
525     publication->address                    = data.publish_address;
526     publication->appkey_index               = data.appkey_index;
527     publication->friendship_credential_flag = data.friendship_credential_flag;
528     publication->ttl                        = data.publish_ttl;
529     publication->period                     = data.publish_period;
530     publication->retransmit                 = data.publish_retransmit;
531 
532     // increase ref counts for current virtual publicataion address
533     uint16_t src = publication->address;
534     if (mesh_network_address_virtual(src)){
535         mesh_virtual_address_t * virtual_address = mesh_virtual_address_for_pseudo_dst(src);
536         if (virtual_address){
537             mesh_virtual_address_increase_refcount(virtual_address);
538         }
539     }
540 
541     mesh_model_publication_start(mesh_model);
542 }
543 
544 void mesh_model_store_publication(mesh_model_t * mesh_model){
545     mesh_publication_model_t * publication = mesh_model->publication_model;
546     if (publication == NULL) return;
547 
548     mesh_persistent_publication_t data;
549     data.publish_address            = publication->address;
550     data.appkey_index               = publication->appkey_index;
551     data.friendship_credential_flag = publication->friendship_credential_flag;
552     data.publish_ttl                = publication->ttl;
553     data.publish_period             = publication->period;
554     data.publish_retransmit         = publication->retransmit;
555     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
556     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_publication_t));
557     report_store_error(result, "publication");
558 }
559 
560 static void mesh_model_delete_publication(mesh_model_t * mesh_model){
561     if (mesh_model->publication_model == NULL) return;
562     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
563     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
564 }
565 
566 void mesh_load_publications(void){
567     printf("Load Model Publications\n");
568     // iterate over elements and models
569     mesh_element_iterator_t element_it;
570     mesh_element_iterator_init(&element_it);
571     while (mesh_element_iterator_has_next(&element_it)){
572         mesh_element_t * element = mesh_element_iterator_next(&element_it);
573         mesh_model_iterator_t model_it;
574         mesh_model_iterator_init(&model_it, element);
575         while (mesh_model_iterator_has_next(&model_it)){
576             mesh_model_t * model = mesh_model_iterator_next(&model_it);
577             mesh_model_load_publication(model);
578         }
579     }
580 }
581 
582 void mesh_delete_publications(void){
583     printf("Delete Model Publications\n");
584     // iterate over elements and models
585     mesh_element_iterator_t element_it;
586     mesh_element_iterator_init(&element_it);
587     while (mesh_element_iterator_has_next(&element_it)){
588         mesh_element_t * element = mesh_element_iterator_next(&element_it);
589         mesh_model_iterator_t model_it;
590         mesh_model_iterator_init(&model_it, element);
591         while (mesh_model_iterator_has_next(&model_it)){
592             mesh_model_t * model = mesh_model_iterator_next(&model_it);
593             mesh_model_delete_publication(model);
594         }
595     }
596 }
597 
598 // Mesh Network Keys
599 static uint32_t mesh_network_key_tag_for_internal_index(uint16_t internal_index){
600     return ((uint32_t) 'M' << 24) | ((uint32_t) 'N' << 16) | ((uint32_t) internal_index);
601 }
602 
603 void mesh_store_network_key(mesh_network_key_t * network_key){
604     mesh_persistent_net_key_t data;
605     printf("Store NetKey: internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
606     printf_hexdump(network_key->net_key, 16);
607     uint32_t tag = mesh_network_key_tag_for_internal_index(network_key->internal_index);
608     data.netkey_index = network_key->netkey_index;
609     (void)memcpy(data.net_key, network_key->net_key, 16);
610     (void)memcpy(data.identity_key, network_key->identity_key, 16);
611     (void)memcpy(data.beacon_key, network_key->beacon_key, 16);
612     (void)memcpy(data.network_id, network_key->network_id, 8);
613     data.nid = network_key->nid;
614     data.version = network_key->version;
615     (void)memcpy(data.encryption_key, network_key->encryption_key, 16);
616     (void)memcpy(data.privacy_key, network_key->privacy_key, 16);
617     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_net_key_t));
618     report_store_error(result, "network key");
619 }
620 
621 void mesh_delete_network_key(uint16_t internal_index){
622     uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
623     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
624 }
625 
626 void mesh_load_network_keys(void){
627     printf("Load Network Keys\n");
628     uint16_t internal_index;
629     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
630         mesh_persistent_net_key_t data;
631         uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
632         int netkey_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
633         if (netkey_len != sizeof(mesh_persistent_net_key_t)) continue;
634 
635         mesh_network_key_t * network_key = btstack_memory_mesh_network_key_get();
636         if (network_key == NULL) return;
637 
638         network_key->internal_index = internal_index;
639         network_key->netkey_index = data.netkey_index;
640         (void)memcpy(network_key->net_key, data.net_key, 16);
641         (void)memcpy(network_key->identity_key, data.identity_key, 16);
642         (void)memcpy(network_key->beacon_key, data.beacon_key, 16);
643         (void)memcpy(network_key->network_id, data.network_id, 8);
644         network_key->nid = data.nid;
645         network_key->version = data.version;
646         (void)memcpy(network_key->encryption_key, data.encryption_key, 16);
647         (void)memcpy(network_key->privacy_key, data.privacy_key, 16);
648 
649 #ifdef ENABLE_GATT_BEARER
650         // setup advertisement with network id
651         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);
652 #endif
653 
654         mesh_network_key_add(network_key);
655 
656         mesh_subnet_setup_for_netkey_index(network_key->netkey_index);
657 
658         printf("- internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
659         printf_hexdump(network_key->net_key, 16);
660 
661         // dump into packet log
662         mesh_log_key("mesh-netkey",  network_key->netkey_index, network_key->net_key);
663     }
664 }
665 
666 void mesh_delete_network_keys(void){
667     printf("Delete Network Keys\n");
668 
669     uint16_t internal_index;
670     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
671         mesh_delete_network_key(internal_index);
672     }
673 }
674 
675 // Mesh App Keys
676 
677 static uint32_t mesh_transport_key_tag_for_internal_index(uint16_t internal_index){
678     return ((uint32_t) 'M' << 24) | ((uint32_t) 'A' << 16) | ((uint32_t) internal_index);
679 }
680 
681 void mesh_store_app_key(mesh_transport_key_t * app_key){
682     mesh_persistent_app_key_t data;
683     printf("Store AppKey: internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", app_key->internal_index, app_key->appkey_index, app_key->aid);
684     printf_hexdump(app_key->key, 16);
685     uint32_t tag = mesh_transport_key_tag_for_internal_index(app_key->internal_index);
686     data.netkey_index = app_key->netkey_index;
687     data.appkey_index = app_key->appkey_index;
688     data.aid = app_key->aid;
689     data.version = app_key->version;
690     (void)memcpy(data.key, app_key->key, 16);
691     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
692     report_store_error(result, "app key");
693 }
694 
695 void mesh_delete_app_key(uint16_t internal_index){
696     uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
697     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
698 }
699 
700 void mesh_load_app_keys(void){
701     printf("Load App Keys\n");
702     uint16_t internal_index;
703     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
704         mesh_persistent_app_key_t data;
705         uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
706         int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
707         if (app_key_len == 0) continue;
708 
709         mesh_transport_key_t * key = btstack_memory_mesh_transport_key_get();
710         if (key == NULL) return;
711 
712         key->internal_index = internal_index;
713         key->appkey_index = data.appkey_index;
714         key->netkey_index = data.netkey_index;
715         key->aid          = data.aid;
716         key->akf          = 1;
717         key->version      = data.version;
718         (void)memcpy(key->key, data.key, 16);
719         mesh_transport_key_add(key);
720         printf("- internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", key->internal_index, key->appkey_index, key->aid);
721         printf_hexdump(key->key, 16);
722 
723         // dump into packet log
724         mesh_log_key("mesh-appkey",  key->appkey_index, key->key);
725     }
726 }
727 
728 void mesh_delete_app_keys(void){
729     printf("Delete App Keys\n");
730 
731     uint16_t internal_index;
732     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
733         mesh_delete_app_key(internal_index);
734     }
735 }
736 
737 
738 // Model to Appkey List
739 
740 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
741     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
742 }
743 
744 static void mesh_load_appkey_list(mesh_model_t * model){
745     uint32_t tag = mesh_model_tag_for_index(model->mid);
746     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
747 }
748 
749 static void mesh_store_appkey_list(mesh_model_t * model){
750     uint32_t tag = mesh_model_tag_for_index(model->mid);
751     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
752     report_store_error(result, "appkey list");
753 }
754 
755 static void mesh_delete_appkey_list(mesh_model_t * model){
756     uint32_t tag = mesh_model_tag_for_index(model->mid);
757     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
758 }
759 
760 void mesh_load_appkey_lists(void){
761     printf("Load Appkey Lists\n");
762     // iterate over elements and models
763     mesh_element_iterator_t element_it;
764     mesh_element_iterator_init(&element_it);
765     while (mesh_element_iterator_has_next(&element_it)){
766         mesh_element_t * element = mesh_element_iterator_next(&element_it);
767         mesh_model_iterator_t model_it;
768         mesh_model_iterator_init(&model_it, element);
769         while (mesh_model_iterator_has_next(&model_it)){
770             mesh_model_t * model = mesh_model_iterator_next(&model_it);
771             mesh_load_appkey_list(model);
772         }
773     }
774 }
775 
776 void mesh_delete_appkey_lists(void){
777     printf("Delete Appkey Lists\n");
778     // iterate over elements and models
779     mesh_element_iterator_t element_it;
780     mesh_element_iterator_init(&element_it);
781     while (mesh_element_iterator_has_next(&element_it)){
782         mesh_element_t * element = mesh_element_iterator_next(&element_it);
783         mesh_model_iterator_t model_it;
784         mesh_model_iterator_init(&model_it, element);
785         while (mesh_model_iterator_has_next(&model_it)){
786             mesh_model_t * model = mesh_model_iterator_next(&model_it);
787             mesh_delete_appkey_list(model);
788         }
789     }
790 }
791 
792 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
793     uint16_t i;
794     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
795         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
796     }
797     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
798         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
799             mesh_model->appkey_indices[i] = appkey_index;
800             mesh_store_appkey_list(mesh_model);
801             return MESH_FOUNDATION_STATUS_SUCCESS;
802         }
803     }
804     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
805 }
806 
807 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
808     uint16_t i;
809     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
810         if (mesh_model->appkey_indices[i] == appkey_index) {
811             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
812             mesh_store_appkey_list(mesh_model);
813         }
814     }
815 }
816 
817 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
818     uint16_t i;
819     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
820         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
821     }
822     return 0;
823 }
824 
825 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
826     mesh_network_key_remove(network_key);
827     mesh_delete_network_key(network_key->internal_index);
828     btstack_memory_mesh_network_key_free(network_key);
829 }
830 
831 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
832     mesh_transport_key_remove(transport_key);
833     mesh_delete_app_key(transport_key->appkey_index);
834     btstack_memory_mesh_transport_key_free(transport_key);
835 }
836 
837 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
838     // delete old netkey index
839     mesh_access_netkey_finalize(subnet->old_key);
840     subnet->old_key = subnet->new_key;
841     subnet->new_key = NULL;
842 
843     // delete old appkeys, if any
844     mesh_transport_key_iterator_t it;
845     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
846     while (mesh_transport_key_iterator_has_more(&it)){
847         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
848         if (transport_key->old_key == 0) continue;
849         mesh_access_appkey_finalize(transport_key);
850     }
851 }
852 
853 // Mesh IV Index
854 static const uint32_t mesh_tag_for_iv_index_and_seq_number = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S');
855 
856 static int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
857     iv_index_and_sequence_number_t data;
858     uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_tag_for_iv_index_and_seq_number, (uint8_t *) &data, sizeof(data));
859     if (len == sizeof(iv_index_and_sequence_number_t)){
860         *iv_index = data.iv_index;
861         *sequence_number = data.seq_number;
862         return 1;
863     }
864     return 0;
865 }
866 
867 static void mesh_store_iv_index_and_sequence_number(uint32_t iv_index, uint32_t sequence_number){
868     iv_index_and_sequence_number_t data;
869     data.iv_index   = iv_index;
870     data.seq_number = sequence_number;
871     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_tag_for_iv_index_and_seq_number, (uint8_t *) &data, sizeof(data));
872     report_store_error(result, "index and sequence number");
873 
874     sequence_number_last_stored = data.seq_number;
875     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
876 }
877 
878 static void mesh_persist_iv_index_and_sequence_number(void){
879     mesh_store_iv_index_and_sequence_number(mesh_get_iv_index(), mesh_sequence_number_peek());
880 }
881 
882 
883 // higher layer - only store if sequence number is higher than trigger
884 static void mesh_persist_iv_index_and_sequence_number_if_needed(void){
885     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
886         mesh_persist_iv_index_and_sequence_number();
887     }
888 }
889 
890 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
891     UNUSED(channel);
892     UNUSED(size);
893 
894     if (packet_type != MESH_BEACON_PACKET) return;
895 
896     // lookup subnet and netkey by network id
897     uint8_t * beacon_network_id = &packet[2];
898     mesh_subnet_iterator_t it;
899     mesh_subnet_iterator_init(&it);
900     mesh_subnet_t * subnet = NULL;
901     uint8_t new_key = 0;
902     while (mesh_subnet_iterator_has_more(&it)){
903         mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it);
904         if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) {
905             subnet = item;
906         }
907         if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) {
908             subnet = item;
909             new_key = 1;
910         }
911         break;
912     }
913     if (subnet == NULL) return;
914 
915     uint8_t flags = packet[1];
916 
917     // Key refresh via secure network beacons that are authenticated with new netkey
918     if (new_key){
919         // either first or second phase (in phase 0, new key is not set)
920         int key_refresh_flag = flags & 1;
921         if (key_refresh_flag){
922             //  transition to phase 3 from either phase 1 or 2
923             switch (subnet->key_refresh){
924                 case MESH_KEY_REFRESH_FIRST_PHASE:
925                 case MESH_KEY_REFRESH_SECOND_PHASE:
926                     mesh_access_key_refresh_revoke_keys(subnet);
927                     subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
928                     break;
929                 default:
930                     break;
931             }
932         } else {
933             //  transition to phase 2 from either phase 1
934             switch (subnet->key_refresh){
935                 case MESH_KEY_REFRESH_FIRST_PHASE:
936                     // -- update state
937                     subnet->key_refresh = MESH_KEY_REFRESH_SECOND_PHASE;
938                     break;
939                 default:
940                     break;
941             }
942         }
943     }
944 
945     // IV Update
946 
947     int     beacon_iv_update_active = flags & 2;
948     int     local_iv_update_active = mesh_iv_update_active();
949     uint32_t beacon_iv_index = big_endian_read_32(packet, 10);
950     uint32_t local_iv_index = mesh_get_iv_index();
951 
952     int32_t iv_index_delta = (int32_t)(beacon_iv_index - local_iv_index);
953 
954     // "If a node in Normal Operation receives a Secure Network beacon with an IV index less than the last known IV Index or greater than
955     //  the last known IV Index + 42, the Secure Network beacon shall be ignored."
956     if (iv_index_delta < 0 || iv_index_delta > 42){
957         return;
958     }
959 
960     // "If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and
961     //  the IV Update Flag set to 0, the node may update its IV without going to the IV Update in Progress state, or it may initiate
962     //  an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending
963     //  on the time since last IV update and the likelihood that the node has missed the Secure Network beacons with the IV update Flag set to 1.""
964     if (local_iv_update_active == 0 && beacon_iv_update_active == 0 && iv_index_delta == 1){
965         // instant iv update
966         mesh_set_iv_index( beacon_iv_index );
967         // store updated iv index
968         mesh_persist_iv_index_and_sequence_number();
969         return;
970     }
971 
972     // "If this node is a member of a primary subnet and receives a Secure Network beacon on a secondary subnet with an IV Index greater than
973     //  the last known IV Index of the primary subnet, the Secure Network beacon shall be ignored."
974     int member_of_primary_subnet = mesh_subnet_get_by_netkey_index(0) != NULL;
975     int beacon_on_secondary_subnet = subnet->netkey_index != 0;
976     if (member_of_primary_subnet && beacon_on_secondary_subnet && iv_index_delta > 0){
977         return;
978     }
979 
980     // "If a node in Normal Operation receives a Secure Network beacon with an IV index greater than the last known IV Index + 1..."
981     // "... it may initiate an IV Index Recovery procedure, see Section 3.10.6."
982     if (local_iv_update_active == 0 && iv_index_delta > 1){
983         // "Upon receiving and successfully authenticating a Secure Network beacon for a primary subnet... "
984         int beacon_on_primary_subnet = subnet->netkey_index == 0;
985         if (!beacon_on_primary_subnet) return;
986         // "... whose IV Index is 1 or more higher than the current known IV Index, the node shall "
987         // " set its current IV Index and its current IV Update procedure state from the values in this Secure Network beacon."
988         mesh_iv_index_recovered(beacon_iv_update_active, beacon_iv_index);
989         // store updated iv index if in normal mode
990         if (beacon_iv_update_active == 0){
991             mesh_persist_iv_index_and_sequence_number();
992         }
993         return;
994     }
995 
996     if (local_iv_update_active == 0){
997         if (beacon_iv_update_active){
998             mesh_trigger_iv_update();
999         }
1000     } else {
1001         if (beacon_iv_update_active == 0){
1002             // " At the point of transition, the node shall reset the sequence number to 0x000000."
1003             mesh_sequence_number_set(0);
1004             mesh_iv_update_completed();
1005             // store updated iv index
1006             mesh_persist_iv_index_and_sequence_number();
1007         }
1008     }
1009 }
1010 
1011 static const uint32_t mesh_tag_for_prov_data = ((uint32_t) 'P' << 24) | ((uint32_t) 'R' << 16) | ((uint32_t) 'O' <<  8) | (uint32_t)'V';
1012 
1013 typedef struct {
1014     uint16_t unicast_address;
1015     uint8_t  flags;
1016     uint8_t  device_key[16];
1017 
1018 } mesh_persistent_provisioning_data_t;
1019 
1020 static void mesh_node_store_provisioning_data(mesh_provisioning_data_t * provisioning_data){
1021 
1022     // fill persistent prov data
1023     mesh_persistent_provisioning_data_t persistent_provisioning_data;
1024 
1025     persistent_provisioning_data.unicast_address = provisioning_data->unicast_address;
1026     persistent_provisioning_data.flags = provisioning_data->flags;
1027     (void)memcpy(persistent_provisioning_data.device_key,
1028                  provisioning_data->device_key, 16);
1029 
1030     // store in tlv
1031     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
1032     int result = btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_tag_for_prov_data, (uint8_t *) &persistent_provisioning_data, sizeof(mesh_persistent_provisioning_data_t));
1033     report_store_error(result, "provisioning");
1034 
1035     // store IV Index and sequence number
1036     mesh_store_iv_index_and_sequence_number(provisioning_data->iv_index, 0);
1037 
1038     // store primary network key
1039     mesh_store_network_key(provisioning_data->network_key);
1040 }
1041 
1042 static void mesh_access_setup_unprovisioned_device(const uint8_t * device_uuid){
1043 #ifdef ENABLE_MESH_PB_ADV
1044     // PB-ADV
1045     beacon_unprovisioned_device_start(device_uuid, 0);
1046 #else
1047     UNUSED(device_uuid);;
1048 #endif
1049 #ifdef ENABLE_MESH_PB_GATT
1050     mesh_proxy_start_advertising_unprovisioned_device();
1051 #endif
1052 }
1053 
1054 static void mesh_access_setup_without_provisiong_data_random(void * arg){
1055     UNUSED(arg);
1056     // set random value
1057     mesh_node_set_device_uuid(random_device_uuid);
1058     mesh_access_setup_unprovisioned_device(random_device_uuid);
1059 }
1060 
1061 void mesh_node_reset(void){
1062     // PROV
1063     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, mesh_tag_for_prov_data);
1064     // everything else
1065     mesh_delete_network_keys();
1066     mesh_delete_app_keys();
1067     mesh_delete_appkey_lists();
1068     mesh_delete_virtual_addresses();
1069     mesh_delete_subscriptions();
1070     mesh_delete_publications();
1071     // also reset iv index + sequence number
1072     mesh_set_iv_index(0);
1073     mesh_sequence_number_set(0);
1074     // start advertising as unprovisioned device
1075     mesh_access_setup_unprovisioned_device(mesh_node_get_device_uuid());
1076 }
1077 
1078 static void mesh_access_setup_with_provisiong_data_random(void * arg){
1079     UNUSED(arg);
1080     // set random value
1081     mesh_node_set_device_uuid(random_device_uuid);
1082 }
1083 
1084 static int mesh_node_startup_from_tlv(void){
1085 
1086     mesh_persistent_provisioning_data_t persistent_provisioning_data;
1087     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
1088 
1089     // load provisioning data
1090     uint32_t prov_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_tag_for_prov_data, (uint8_t *) &persistent_provisioning_data, sizeof(mesh_persistent_provisioning_data_t));
1091     printf("Provisioning data available: %u\n", prov_len ? 1 : 0);
1092     int prov_data_valid = prov_len == sizeof(mesh_persistent_provisioning_data_t);
1093     if (prov_data_valid){
1094 
1095         // copy into mesh_provisioning_data
1096         mesh_provisioning_data_t provisioning_data;
1097         (void)memcpy(provisioning_data.device_key,
1098                      persistent_provisioning_data.device_key, 16);
1099         provisioning_data.unicast_address = persistent_provisioning_data.unicast_address;
1100         provisioning_data.flags = persistent_provisioning_data.flags;
1101         provisioning_data.network_key = NULL;
1102         printf("Provisioning Data: Flags %x, unicast_address %04x\n", persistent_provisioning_data.flags, provisioning_data.unicast_address);
1103 
1104         // try load iv index and sequence number
1105         uint32_t iv_index        = 0;
1106         uint32_t sequence_number = 0;
1107         (void) mesh_load_iv_index_and_sequence_number(&iv_index, &sequence_number);
1108 
1109         // bump sequence number to account for interval updates
1110         sequence_number += MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
1111         mesh_store_iv_index_and_sequence_number(iv_index, sequence_number);
1112 
1113         mesh_set_iv_index(iv_index);
1114         mesh_sequence_number_set(sequence_number);
1115         provisioning_data.iv_index = iv_index;
1116         printf("IV Index: %08x, Sequence Number %08x\n", (int) iv_index, (int) sequence_number);
1117 
1118         // setup iv update, node address, device key ...
1119         mesh_setup_from_provisioning_data(&provisioning_data);
1120 
1121         // load network keys
1122         mesh_load_network_keys();
1123 
1124         // load app keys
1125         mesh_load_app_keys();
1126 
1127         // load foundation state
1128         mesh_foundation_state_load();
1129 
1130         // load model to appkey bindings
1131         mesh_load_appkey_lists();
1132 
1133         // load virtual addresses
1134         mesh_load_virtual_addresses();
1135 
1136         // load model subscriptions
1137         mesh_load_subscriptions();
1138 
1139         // load model publications
1140         mesh_load_publications();
1141 
1142 #if defined(ENABLE_MESH_ADV_BEARER) || defined(ENABLE_MESH_PB_ADV)
1143         // start sending Secure Network Beacon
1144         mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(0);
1145         if (subnet){
1146             beacon_secure_network_start(subnet);
1147         }
1148 #endif
1149         // create random uuid if not already set
1150         if (mesh_node_get_device_uuid() == NULL){
1151             btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_with_provisiong_data_random, NULL);
1152         }
1153 
1154         // dump into packet log
1155         hci_dump_log(HCI_DUMP_LOG_LEVEL_INFO, "mesh-iv-index: %08x",  iv_index);
1156         mesh_log_key("mesh-devkey",  0xffff, persistent_provisioning_data.device_key);
1157 
1158     } else {
1159 
1160         const uint8_t * device_uuid = mesh_node_get_device_uuid();
1161         if (device_uuid){
1162             mesh_access_setup_unprovisioned_device(device_uuid);
1163         } else{
1164             btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_without_provisiong_data_random, NULL);
1165         }
1166 
1167     }
1168 
1169     return prov_data_valid;
1170 }
1171 
1172 static void mesh_control_message_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
1173     UNUSED(callback_type);
1174     UNUSED(status);
1175 
1176     // get opcode
1177     uint8_t opcode = mesh_pdu_control_opcode(pdu);
1178     printf("MESH Control Message, Opcode: 0x%02x + ", opcode);
1179     printf_hexdump(mesh_pdu_data(pdu), mesh_pdu_len(pdu));
1180 
1181     uint8_t init_ttl;
1182     uint8_t hops = 0;
1183     uint16_t features = 0;
1184     switch(opcode){
1185         case 0x0a:
1186             // read params
1187             init_ttl = (*mesh_pdu_data(pdu)) & 0x7fu;
1188             features = big_endian_read_16(mesh_pdu_data(pdu), 1);
1189             // calculates hops
1190             hops     = init_ttl - mesh_pdu_ttl(pdu) + 1;
1191             // process heartbeat info
1192             mesh_configuration_server_process_heartbeat(&mesh_configuration_server_model, mesh_pdu_src(pdu), mesh_pdu_dst(pdu), hops, features);
1193             break;
1194         default:
1195             break;
1196     }
1197     mesh_upper_transport_message_processed_by_higher_layer(pdu);
1198 }
1199 
1200 static void mesh_node_setup_default_models(void){
1201     // configure Config Server
1202     mesh_configuration_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER);
1203     mesh_configuration_server_model.model_data       = &mesh_configuration_server_model_context;
1204     mesh_configuration_server_model.operations       = mesh_configuration_server_get_operations();
1205     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_configuration_server_model);
1206 
1207     // Config Health Server
1208     mesh_health_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_HEALTH_SERVER);
1209     mesh_health_server_model.model_data       = &mesh_health_server_model_context;
1210     mesh_health_server_model.operations       = mesh_health_server_get_operations();
1211     mesh_health_server_model.publication_model = &mesh_health_server_publication;
1212     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_health_server_model);
1213     mesh_health_server_set_publication_model(&mesh_health_server_model, &mesh_health_server_publication);
1214 }
1215 
1216 void mesh_init(void){
1217 
1218     // register for HCI events
1219     hci_event_callback_registration.callback = &hci_packet_handler;
1220     hci_add_event_handler(&hci_event_callback_registration);
1221 
1222     // ADV Bearer also used for GATT Proxy Advertisements and PB-GATT
1223     adv_bearer_init();
1224 
1225 #ifdef ENABLE_MESH_GATT_BEARER
1226     // Setup GATT bearer
1227     gatt_bearer_init();
1228 #endif
1229 
1230 #ifdef ENABLE_MESH_ADV_BEARER
1231     // Setup Unprovisioned Device Beacon
1232     beacon_init();
1233 #endif
1234 
1235     provisioning_device_init();
1236     provisioning_device_register_packet_handler(&mesh_provisioning_message_handler);
1237 
1238 #ifdef ENABLE_MESH_PROVISIONER
1239     provisioning_provisioner_init();
1240     provisioning_provisioner_register_packet_handler(&mesh_provisioning_message_handler);
1241 #endif
1242 
1243     // Node Configuration
1244     mesh_node_init();
1245 
1246     // Network layer
1247     mesh_network_init();
1248 
1249     // Transport layers (lower + upper))
1250     mesh_lower_transport_init();
1251     mesh_upper_transport_init();
1252 
1253     // Access layer
1254     mesh_access_init();
1255 
1256     // Add mandatory models: Config Server and Health Server
1257     mesh_node_setup_default_models();
1258 
1259     // register for secure network beacons
1260     beacon_register_for_secure_network_beacons(&mesh_access_secure_network_beacon_handler);
1261 
1262     // register for seq number updates
1263     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number_if_needed);
1264 
1265     // register for control messages
1266     mesh_upper_transport_register_control_message_handler(&mesh_control_message_handler);
1267 }
1268 
1269 /**
1270  * Register for Mesh Provisioning Device events
1271  * @param packet_handler
1272  */
1273 void mesh_register_provisioning_device_packet_handler(btstack_packet_handler_t packet_handler){
1274     provisioning_device_packet_handler = packet_handler;
1275 }
1276