xref: /btstack/src/mesh/mesh_network.c (revision 077fecbb6ed539507f37505ebd8a5b00e01c55e9)
1 /*
2  * Copyright (C) 2018 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 BLUEKITCHEN
24  * GMBH 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_network.c"
39 
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "btstack_debug.h"
45 #include "btstack_event.h"
46 #include "btstack_memory.h"
47 #include "btstack_util.h"
48 
49 #include "mesh/beacon.h"
50 #include "mesh/mesh_foundation.h"
51 #include "mesh/mesh_iv_index_seq_number.h"
52 #include "mesh/mesh_keys.h"
53 #include "mesh/mesh_node.h"
54 #include "mesh/provisioning.h"
55 #include "mesh/provisioning_device.h"
56 
57 #ifdef ENABLE_MESH_ADV_BEARER
58 #include "mesh/adv_bearer.h"
59 #endif
60 
61 #ifdef ENABLE_MESH_GATT_BEARER
62 #include "mesh/gatt_bearer.h"
63 #endif
64 
65 // configuration
66 #define MESH_NETWORK_CACHE_SIZE 2
67 
68 // debug config
69 #define LOG_NETWORK
70 
71 static void mesh_network_dump_network_pdus(const char * name, btstack_linked_list_t * list);
72 
73 // structs
74 
75 // globals
76 
77 static void (*mesh_network_higher_layer_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu);
78 static void (*mesh_network_proxy_message_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu);
79 
80 #ifdef ENABLE_MESH_GATT_BEARER
81 static hci_con_handle_t gatt_bearer_con_handle;
82 #endif
83 
84 // shared send/receive crypto
85 static int mesh_crypto_active;
86 
87 // crypto requests
88 static union {
89     btstack_crypto_ccm_t         ccm;
90     btstack_crypto_aes128_t      aes128;
91 } mesh_network_crypto_request;
92 
93 static const mesh_network_key_t *  current_network_key;
94 
95 // PECB calculation
96 static uint8_t encryption_block[16];
97 static uint8_t obfuscation_block[16];
98 
99 // Subnets
100 static btstack_linked_list_t subnets;
101 
102 // Network Nonce
103 static uint8_t network_nonce[13];
104 
105 // INCOMING //
106 
107 // unprocessed network pdu - added by mesh_network_pdus_received_message
108 static btstack_linked_list_t        network_pdus_received;
109 
110 // in validation
111 static mesh_network_pdu_t *         incoming_pdu_raw;
112 static mesh_network_pdu_t *         incoming_pdu_decoded;
113 static mesh_network_key_iterator_t  validation_network_key_it;
114 
115 // OUTGOING //
116 
117 // Network PDUs queued by mesh_network_send
118 static btstack_linked_list_t network_pdus_queued;
119 
120 // Network PDU about to get send via all bearers when encrypted
121 static mesh_network_pdu_t * outgoing_pdu;
122 
123 // Network PDUs ready to send via GATT Bearer
124 static btstack_linked_list_t network_pdus_outgoing_gatt;
125 
126 #ifdef ENABLE_MESH_GATT_BEARER
127 static mesh_network_pdu_t * gatt_bearer_network_pdu;
128 #endif
129 
130 // Network PDUs ready to send via ADV Bearer
131 static btstack_linked_list_t network_pdus_outgoing_adv;
132 
133 #ifdef ENABLE_MESH_ADV_BEARER
134 static mesh_network_pdu_t * adv_bearer_network_pdu;
135 #endif
136 
137 
138 // mesh network cache - we use 32-bit 'hashes'
139 static uint32_t mesh_network_cache[MESH_NETWORK_CACHE_SIZE];
140 static int      mesh_network_cache_index;
141 
142 // register for freed network pdu
143 void (*mesh_network_free_pdu_callback)(void);
144 
145 // prototypes
146 
147 static void mesh_network_run(void);
148 static void process_network_pdu_validate(void);
149 
150 // network caching
151 static uint32_t mesh_network_cache_hash(mesh_network_pdu_t * network_pdu){
152     // - The SEQ field is a 24-bit integer that when combined with the IV Index,
153     // shall be a unique value for each new Network PDU originated by this node (=> SRC)
154     // - IV updates only rarely
155     // => 16 bit SRC, 1 bit IVI, 15 bit SEQ
156     uint8_t  ivi = network_pdu->data[0] >> 7;
157     uint16_t seq = big_endian_read_16(network_pdu->data, 3);
158     uint16_t src = big_endian_read_16(network_pdu->data, 5);
159     return (src << 16) | (ivi << 15) | (seq & 0x7fff);
160 }
161 
162 static int mesh_network_cache_find(uint32_t hash){
163     int i;
164     for (i = 0; i < MESH_NETWORK_CACHE_SIZE; i++) {
165         if (mesh_network_cache[i] == hash) {
166             return 1;
167         }
168     }
169     return 0;
170 }
171 
172 static void mesh_network_cache_add(uint32_t hash){
173     mesh_network_cache[mesh_network_cache_index++] = hash;
174     if (mesh_network_cache_index >= MESH_NETWORK_CACHE_SIZE){
175         mesh_network_cache_index = 0;
176     }
177 }
178 
179 // common helper
180 int mesh_network_address_unicast(uint16_t addr){
181     return addr != MESH_ADDRESS_UNSASSIGNED && (addr < 0x8000);
182 }
183 
184 int mesh_network_address_virtual(uint16_t addr){
185     return (addr & 0xC000) == 0x8000;   // 0b10xx xxxx xxxx xxxx
186 }
187 
188 int mesh_network_address_group(uint16_t addr){
189     return (addr & 0xC000) == 0xC000;   // 0b11xx xxxx xxxx xxxx
190 }
191 
192 int mesh_network_address_all_proxies(uint16_t addr){
193     return addr == MESH_ADDRESS_ALL_PROXIES;
194 }
195 
196 int mesh_network_address_all_nodes(uint16_t addr){
197     return addr == MESH_ADDRESS_ALL_NODES;
198 }
199 
200 int mesh_network_address_all_friends(uint16_t addr){
201     return addr == MESH_ADDRESS_ALL_FRIENDS;
202 }
203 
204 int mesh_network_address_all_relays(uint16_t addr){
205     return addr == MESH_ADDRESS_ALL_RELAYS;
206 }
207 
208 int mesh_network_addresses_valid(uint8_t ctl, uint16_t src, uint16_t dst){
209     // printf("CTL: %u\n", ctl);
210     // printf("SRC: %04x\n", src);
211     // printf("DST: %04x\n", dst);
212     if (src == 0){
213         // printf("SRC Unassigned Addr -> ignore\n");
214         return 0;
215     }
216     if ((src & 0xC000) == 0x8000){
217         // printf("SRC Virtual Addr -> ignore\n");
218         return 0;
219     }
220     if ((src & 0xC000) == 0xC000){
221         // printf("SRC Group Addr -> ignore\n");
222         return 0;
223     }
224     if (dst == 0){
225         // printf("DST Unassigned Addr -> ignore\n");
226         return 0;
227     }
228     if ( ((dst & 0xC000) == 0x8000) && (ctl == 1)){
229         // printf("DST Virtual Addr in CONTROL -> ignore\n");
230         return 0;
231     }
232     if ( (0xFF00 <= dst) && (dst <= 0xfffb) && (ctl == 0) ){
233         // printf("DST RFU Group Addr in MESSAGE -> ignore\n");
234         return 0;
235     }
236     // printf("SRC + DST Addr valid\n");
237     return 1;
238 }
239 
240 static void mesh_network_create_nonce(uint8_t * nonce, const mesh_network_pdu_t * pdu, uint32_t iv_index){
241     unsigned int pos = 0;
242     nonce[pos++] = 0x0;      // Network Nonce
243     (void)memcpy(&nonce[pos], &pdu->data[1], 6);
244     pos += 6;
245     big_endian_store_16(nonce, pos, 0);
246     pos += 2;
247     big_endian_store_32(nonce, pos, iv_index);
248 }
249 
250 static void mesh_proxy_create_nonce(uint8_t * nonce, const mesh_network_pdu_t * pdu, uint32_t iv_index){
251     unsigned int pos = 0;
252     nonce[pos++] = 0x3;      // Proxy Nonce
253     nonce[pos++] = 0;
254     (void)memcpy(&nonce[pos], &pdu->data[2], 5);
255     pos += 5;
256     big_endian_store_16(nonce, pos, 0);
257     pos += 2;
258     big_endian_store_32(nonce, pos, iv_index);
259 }
260 
261 // NID/IVI | obfuscated (CTL/TTL, SEQ (24), SRC (16) ), encrypted ( DST(16), TransportPDU), MIC(32 or 64)
262 
263 static void mesh_network_send_complete(mesh_network_pdu_t * network_pdu){
264     if (network_pdu->flags & MESH_NETWORK_PDU_FLAGS_RELAY){
265 #ifdef LOG_NETWORK
266         printf("TX-F-NetworkPDU (%p): relay -> free packet\n", network_pdu);
267 #endif
268         mesh_network_pdu_free(network_pdu);
269     } else {
270 #ifdef LOG_NETWORK
271         printf("TX-F-NetworkPDU (%p): notify lower transport\n", network_pdu);
272 #endif
273         // notify higher layer
274         (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
275     }
276 }
277 
278 // new
279 static void mesh_network_send_c(void *arg){
280     UNUSED(arg);
281 
282     // obfuscate
283     unsigned int i;
284     for (i=0;i<6;i++){
285         outgoing_pdu->data[1+i] ^= obfuscation_block[i];
286     }
287 
288 #ifdef LOG_NETWORK
289     printf("TX-C-NetworkPDU (%p): ", outgoing_pdu);
290     printf_hexdump(outgoing_pdu->data, outgoing_pdu->len);
291 #endif
292 
293     // crypto done
294     mesh_crypto_active = 0;
295 
296     // done
297     mesh_network_pdu_t * network_pdu = outgoing_pdu;
298     outgoing_pdu = NULL;
299 
300     if ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION) != 0){
301         // encryption requested by mesh_network_encrypt_proxy_configuration_message
302         (*mesh_network_proxy_message_handler)(MESH_NETWORK_PDU_ENCRYPTED, network_pdu);
303         return;
304     }
305 
306 #ifdef LOG_NETWORK
307     printf("TX-D-NetworkPDU (%p): ", network_pdu);
308     printf_hexdump(network_pdu->data, network_pdu->len);
309 #endif
310 
311     // add to queue
312     btstack_linked_list_add_tail(&network_pdus_outgoing_gatt, (btstack_linked_item_t *) network_pdu);
313 
314     // go
315     mesh_network_run();
316 }
317 
318 static void mesh_network_send_b(void *arg){
319     UNUSED(arg);
320 
321     uint32_t iv_index = mesh_get_iv_index_for_tx();
322 
323     // store NetMIC
324     uint8_t net_mic[8];
325     btstack_crypto_ccm_get_authentication_value(&mesh_network_crypto_request.ccm, net_mic);
326 
327     // store MIC
328     uint8_t net_mic_len = outgoing_pdu->data[1] & 0x80 ? 8 : 4;
329     (void)memcpy(&outgoing_pdu->data[outgoing_pdu->len], net_mic, net_mic_len);
330     outgoing_pdu->len += net_mic_len;
331 
332     btstack_assert(outgoing_pdu->len <= 29);
333 
334 #ifdef LOG_NETWORK
335     printf("TX-B-NetworkPDU (%p): ", outgoing_pdu);
336     printf_hexdump(outgoing_pdu->data, outgoing_pdu->len);
337 #endif
338 
339     // calc PECB
340     memset(encryption_block, 0, 5);
341     big_endian_store_32(encryption_block, 5, iv_index);
342     (void)memcpy(&encryption_block[9], &outgoing_pdu->data[7], 7);
343     btstack_crypto_aes128_encrypt(&mesh_network_crypto_request.aes128, current_network_key->privacy_key, encryption_block, obfuscation_block, &mesh_network_send_c, NULL);
344 }
345 
346 static void mesh_network_send_a(void){
347 
348     mesh_crypto_active = 1;
349 
350     uint32_t iv_index = mesh_get_iv_index_for_tx();
351 
352     // lookup subnet by netkey_index
353     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(outgoing_pdu->netkey_index);
354     if (!subnet) {
355         mesh_crypto_active = 0;
356         mesh_network_pdu_t * network_pdu = outgoing_pdu;
357         outgoing_pdu = NULL;
358         // notify upper layer
359         mesh_network_send_complete(network_pdu);
360         // run again
361         mesh_network_run();
362         return;
363     }
364 
365     // get network key to use for sending
366     current_network_key = mesh_subnet_get_outgoing_network_key(subnet);
367 
368 #ifdef LOG_NETWORK
369     printf("TX-A-NetworkPDU (%p): ", outgoing_pdu);
370     printf_hexdump(outgoing_pdu->data, outgoing_pdu->len);
371 #endif
372 
373     // get network nonce
374     if (outgoing_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
375         mesh_proxy_create_nonce(network_nonce, outgoing_pdu, iv_index);
376 #ifdef LOG_NETWORK
377         printf("TX-ProxyNonce:  ");
378         printf_hexdump(network_nonce, 13);
379 #endif
380     } else {
381         mesh_network_create_nonce(network_nonce, outgoing_pdu, iv_index);
382 #ifdef LOG_NETWORK
383         printf("TX-NetworkNonce:  ");
384         printf_hexdump(network_nonce, 13);
385 #endif
386     }
387 
388 #ifdef LOG_NETWORK
389    printf("TX-EncryptionKey: ");
390     printf_hexdump(current_network_key->encryption_key, 16);
391 #endif
392 
393     // start ccm
394     uint8_t cypher_len  = outgoing_pdu->len - 7;
395     uint8_t net_mic_len = outgoing_pdu->data[1] & 0x80 ? 8 : 4;
396     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
397     btstack_crypto_ccm_encrypt_block(&mesh_network_crypto_request.ccm, cypher_len, &outgoing_pdu->data[7], &outgoing_pdu->data[7], &mesh_network_send_b, NULL);
398 }
399 
400 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
401 static void mesh_network_relay_message(mesh_network_pdu_t * network_pdu){
402 
403     uint8_t ctl_ttl      = network_pdu->data[1];
404     uint8_t ctl_in_bit_7 = ctl_ttl & 0x80;
405     uint8_t ttl          = ctl_ttl & 0x7f;
406 
407     // prepare pdu for resending
408     network_pdu->data[1] = ctl_in_bit_7 | (ttl - 1);
409     network_pdu->flags |= MESH_NETWORK_PDU_FLAGS_RELAY;
410 
411 #ifdef LOG_NETWORK
412     printf("TX-Relay-NetworkPDU (%p): ", network_pdu);
413     printf_hexdump(network_pdu->data, network_pdu->len);
414     printf("^^ into network_pdus_queued\n");
415 #endif
416 
417     uint8_t net_mic_len = ctl_in_bit_7 ? 8 : 4;
418     btstack_assert((network_pdu->len + net_mic_len) <= 29);
419     UNUSED(net_mic_len);
420 
421     // queue up
422     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
423 }
424 #endif
425 
426 void mesh_network_message_processed_by_higher_layer(mesh_network_pdu_t * network_pdu){
427 
428 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
429 
430     // check if address does not matches elements on our node and TTL >= 2
431     uint16_t src     = mesh_network_src(network_pdu);
432     uint8_t  ttl     = mesh_network_ttl(network_pdu);
433 
434     uint16_t mesh_network_primary_address = mesh_node_get_primary_element_address();
435 
436     if (((src < mesh_network_primary_address) || (src > (mesh_network_primary_address + mesh_node_element_count()))) && (ttl >= 2)){
437 
438         if ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0){
439 
440             // message received via ADV bearer are relayed:
441 
442 #ifdef ENABLE_MESH_RELAY
443             if (mesh_foundation_relay_get() != 0){
444                 // - to ADV bearer, if Relay supported and enabledx
445                 mesh_network_relay_message(network_pdu);
446                 mesh_network_run();
447                 return;
448             }
449 #endif
450 
451 #ifdef ENABLE_MESH_PROXY_SERVER
452             if (mesh_foundation_gatt_proxy_get() != 0){
453                 // - to GATT bearer, if Proxy supported and enabled
454                 mesh_network_relay_message(network_pdu);
455                 mesh_network_run();
456                 return;
457             }
458 #endif
459 
460         } else {
461 
462             // messages received via GATT bearer are relayed:
463 
464 #ifdef ENABLE_MESH_PROXY_SERVER
465             if (mesh_foundation_gatt_proxy_get() != 0){
466                 // - to ADV bearer, if Proxy supported and enabled
467                 mesh_network_relay_message(network_pdu);
468                 mesh_network_run();
469                 return;
470             }
471 #endif
472 
473         }
474     }
475 #endif
476 
477     // otherwise, we're done
478     btstack_memory_mesh_network_pdu_free(network_pdu);
479 }
480 
481 static void process_network_pdu_done(void){
482     btstack_memory_mesh_network_pdu_free(incoming_pdu_raw);
483     incoming_pdu_raw = NULL;
484     mesh_crypto_active = 0;
485 
486     mesh_network_run();
487 }
488 
489 static void process_network_pdu_validate_d(void * arg){
490     UNUSED(arg);
491     // mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
492 
493     uint8_t ctl_ttl     = incoming_pdu_decoded->data[1];
494     uint8_t ctl         = ctl_ttl >> 7;
495     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
496 
497     // store NetMIC
498     uint8_t net_mic[8];
499     btstack_crypto_ccm_get_authentication_value(&mesh_network_crypto_request.ccm, net_mic);
500 #ifdef LOG_NETWORK
501     printf("RX-NetMIC (%p): ", incoming_pdu_decoded);
502     printf_hexdump(net_mic, net_mic_len);
503 #endif
504     // store in decoded pdu
505     (void)memcpy(&incoming_pdu_decoded->data[incoming_pdu_decoded->len - net_mic_len],
506                  net_mic, net_mic_len);
507 
508 #ifdef LOG_NETWORK
509     uint8_t cypher_len  = incoming_pdu_decoded->len - 9 - net_mic_len;
510     printf("RX-Decrypted DST/TransportPDU (%p): ", incoming_pdu_decoded);
511     printf_hexdump(&incoming_pdu_decoded->data[7], 2 + cypher_len);
512 
513     printf("RX-Decrypted: ");
514     printf_hexdump(incoming_pdu_decoded->data, incoming_pdu_decoded->len);
515 #endif
516 
517     // validate network mic
518     if (memcmp(net_mic, &incoming_pdu_raw->data[incoming_pdu_decoded->len-net_mic_len], net_mic_len) != 0){
519         // fail
520         printf("RX-NetMIC mismatch, try next key (%p)\n", incoming_pdu_decoded);
521         process_network_pdu_validate();
522         return;
523     }
524 
525     // remove NetMIC from payload
526     incoming_pdu_decoded->len -= net_mic_len;
527 
528 #ifdef LOG_NETWORK
529     // match
530     printf("RX-NetMIC matches (%p)\n", incoming_pdu_decoded);
531     printf("RX-TTL (%p): 0x%02x\n", incoming_pdu_decoded, incoming_pdu_decoded->data[1] & 0x7f);
532 #endif
533 
534     // set netkey_index
535     incoming_pdu_decoded->netkey_index = current_network_key->netkey_index;
536 
537     if (incoming_pdu_decoded->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
538 
539         mesh_network_pdu_t * decoded_pdu = incoming_pdu_decoded;
540         incoming_pdu_decoded = NULL;
541 
542         // no additional checks for proxy messages
543         (*mesh_network_proxy_message_handler)(MESH_NETWORK_PDU_RECEIVED, decoded_pdu);
544 
545     } else {
546 
547         // validate src/dest addresses
548         uint16_t src = big_endian_read_16(incoming_pdu_decoded->data, 5);
549         uint16_t dst = big_endian_read_16(incoming_pdu_decoded->data, 7);
550         int valid = mesh_network_addresses_valid(ctl, src, dst);
551         if (!valid){
552 #ifdef LOG_NETWORK
553             printf("RX Address invalid (%p)\n", incoming_pdu_decoded);
554 #endif
555             btstack_memory_mesh_network_pdu_free(incoming_pdu_decoded);
556             incoming_pdu_decoded = NULL;
557             process_network_pdu_done();
558             return;
559         }
560 
561         // check cache
562         uint32_t hash = mesh_network_cache_hash(incoming_pdu_decoded);
563 #ifdef LOG_NETWORK
564         printf("RX-Hash (%p): %08x\n", incoming_pdu_decoded, hash);
565 #endif
566         if (mesh_network_cache_find(hash)){
567             // found in cache, drop
568 #ifdef LOG_NETWORK
569             printf("Found in cache -> drop packet (%p)\n", incoming_pdu_decoded);
570 #endif
571             btstack_memory_mesh_network_pdu_free(incoming_pdu_decoded);
572             incoming_pdu_decoded = NULL;
573             process_network_pdu_done();
574             return;
575         }
576 
577         // store in network cache
578         mesh_network_cache_add(hash);
579 
580 #ifdef LOG_NETWORK
581             printf("RX-Validated (%p) - forward to lower transport\n", incoming_pdu_decoded);
582 #endif
583 
584         // forward to lower transport layer. message is freed by call to mesh_network_message_processed_by_upper_layer
585         mesh_network_pdu_t * decoded_pdu = incoming_pdu_decoded;
586         incoming_pdu_decoded = NULL;
587         (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_RECEIVED, decoded_pdu);
588     }
589 
590     // done
591     process_network_pdu_done();
592 }
593 
594 static uint32_t iv_index_for_pdu(const mesh_network_pdu_t * network_pdu){
595     // get IV Index and IVI
596     uint32_t iv_index = mesh_get_iv_index();
597     int ivi = network_pdu->data[0] >> 7;
598 
599     // if least significant bit differs, use previous IV Index
600     if ((iv_index & 1 ) ^ ivi){
601         iv_index--;
602 #ifdef LOG_NETWORK
603         printf("RX-IV: IVI indicates previous IV index, using 0x%08x\n", iv_index);
604 #endif
605     }
606     return iv_index;
607 }
608 
609 static void process_network_pdu_validate_b(void * arg){
610     UNUSED(arg);
611 
612 #ifdef LOG_NETWORK
613     printf("RX-PECB: ");
614     printf_hexdump(obfuscation_block, 6);
615 #endif
616 
617     // de-obfuscate
618     unsigned int i;
619     for (i=0;i<6;i++){
620         incoming_pdu_decoded->data[1+i] = incoming_pdu_raw->data[1+i] ^ obfuscation_block[i];
621     }
622 
623     uint32_t iv_index = iv_index_for_pdu(incoming_pdu_raw);
624 
625     if (incoming_pdu_decoded->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
626         // create network nonce
627         mesh_proxy_create_nonce(network_nonce, incoming_pdu_decoded, iv_index);
628 #ifdef LOG_NETWORK
629         printf("RX-Proxy Nonce: ");
630         printf_hexdump(network_nonce, 13);
631 #endif
632     } else {
633         // create network nonce
634         mesh_network_create_nonce(network_nonce, incoming_pdu_decoded, iv_index);
635 #ifdef LOG_NETWORK
636         printf("RX-Network Nonce: ");
637         printf_hexdump(network_nonce, 13);
638 #endif
639     }
640 
641     //
642     uint8_t ctl_ttl     = incoming_pdu_decoded->data[1];
643     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
644     uint8_t cypher_len  = incoming_pdu_decoded->len - 7 - net_mic_len;
645 
646 #ifdef LOG_NETWORK
647     printf("RX-Cyper len %u, mic len %u\n", cypher_len, net_mic_len);
648 
649     printf("RX-Encryption Key: ");
650     printf_hexdump(current_network_key->encryption_key, 16);
651 
652 #endif
653 
654     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
655     btstack_crypto_ccm_decrypt_block(&mesh_network_crypto_request.ccm, cypher_len, &incoming_pdu_raw->data[7], &incoming_pdu_decoded->data[7], &process_network_pdu_validate_d, incoming_pdu_decoded);
656 }
657 
658 static void process_network_pdu_validate(void){
659     if (!mesh_network_key_nid_iterator_has_more(&validation_network_key_it)){
660         printf("No valid network key found\n");
661         btstack_memory_mesh_network_pdu_free(incoming_pdu_decoded);
662         incoming_pdu_decoded = NULL;
663         process_network_pdu_done();
664         return;
665     }
666 
667     current_network_key = mesh_network_key_nid_iterator_get_next(&validation_network_key_it);
668 
669     // calc PECB
670     uint32_t iv_index = iv_index_for_pdu(incoming_pdu_raw);
671     memset(encryption_block, 0, 5);
672     big_endian_store_32(encryption_block, 5, iv_index);
673     (void)memcpy(&encryption_block[9], &incoming_pdu_raw->data[7], 7);
674     btstack_crypto_aes128_encrypt(&mesh_network_crypto_request.aes128, current_network_key->privacy_key, encryption_block, obfuscation_block, &process_network_pdu_validate_b, NULL);
675 }
676 
677 
678 static void process_network_pdu(void){
679     //
680     uint8_t nid_ivi = incoming_pdu_raw->data[0];
681 
682     // setup pdu object
683     incoming_pdu_decoded->data[0] = nid_ivi;
684     incoming_pdu_decoded->len     = incoming_pdu_raw->len;
685     incoming_pdu_decoded->flags   = incoming_pdu_raw->flags;
686 
687     // init provisioning data iterator
688     uint8_t nid = nid_ivi & 0x7f;
689     // uint8_t iv_index = network_pdu_data[0] >> 7;
690     mesh_network_key_nid_iterator_init(&validation_network_key_it, nid);
691 
692     process_network_pdu_validate();
693 }
694 
695 // returns true if done
696 static bool mesh_network_run_gatt(void){
697     if (btstack_linked_list_empty(&network_pdus_outgoing_gatt)){
698         return true;
699     }
700 
701 #ifdef ENABLE_MESH_GATT_BEARER
702     if (gatt_bearer_network_pdu != NULL){
703         return true;
704     }
705 
706     // move to 'gatt bearer queue'
707     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_gatt);
708 
709 #ifdef LOG_NETWORK
710     printf("network run 1: pop %p from network_pdus_outgoing_gatt\n", network_pdu);
711 #endif
712     // request to send via gatt if:
713     // proxy active and connected
714     // packet wasn't received via gatt bearer
715     int send_via_gatt = ((mesh_foundation_gatt_proxy_get() != 0) &&
716                         (gatt_bearer_con_handle != HCI_CON_HANDLE_INVALID) &&
717                         ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0));
718     if (send_via_gatt){
719 
720 #ifdef LOG_NETWORK
721         printf("network run 2: set %p as gatt_bearer_network_pdu\n", network_pdu);
722 #endif
723         gatt_bearer_network_pdu = network_pdu;
724         gatt_bearer_request_can_send_now_for_network_pdu();
725 
726     } else {
727 
728 #ifdef LOG_NETWORK
729         printf("network run 3: push %p to network_pdus_outgoing_adv\n", network_pdu);
730 #endif
731         btstack_linked_list_add_tail(&network_pdus_outgoing_adv, (btstack_linked_item_t *) network_pdu);
732 
733 #ifdef LOG_NETWORK
734         mesh_network_dump_network_pdus("network_pdus_outgoing_adv (1)", &network_pdus_outgoing_adv);
735 #endif
736     }
737 #else
738     // directly move to 'outgoing adv bearer queue'
739     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_gatt);
740     btstack_linked_list_add_tail(&network_pdus_outgoing_adv, (btstack_linked_item_t *) network_pdu);
741 #endif
742     return false;
743 }
744 
745 // returns true if done
746 static bool mesh_network_run_adv(void){
747 
748     if (btstack_linked_list_empty(&network_pdus_outgoing_adv)){
749         return true;
750     }
751 
752 #ifdef ENABLE_MESH_ADV_BEARER
753     if (adv_bearer_network_pdu != NULL){
754         return true;
755     }
756 
757     // move to 'adv bearer queue'
758     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_adv);
759 
760 #ifdef LOG_NETWORK
761     printf("network run 4: pop %p from network_pdus_outgoing_adv\n", network_pdu);
762     mesh_network_dump_network_pdus("network_pdus_outgoing_adv (3)", &network_pdus_outgoing_adv);
763     printf("network run 5: %p -> flags 0x%02x, gatt_proxy %u, relay %u\n", network_pdu, network_pdu->flags, mesh_foundation_gatt_proxy_get(), mesh_foundation_relay_get());
764 #endif
765 
766     // send via adv if:
767     // packet was received via gatt bearer and proxy active, or,
768     // packet originated locally (== not relayed), or,
769     // packet was received via ADV bearer and relay is active, or,
770     int send_via_adv = (((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) != 0) && (mesh_foundation_gatt_proxy_get() == 1)) ||
771                        (((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0) && (mesh_foundation_relay_get() == 1)) ||
772                         ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_RELAY) == 0);
773 
774     if (send_via_adv){
775 #ifdef LOG_NETWORK
776         printf("network run 6: set %p as to adv_bearer_network_pdu\n", network_pdu);
777 #endif
778         adv_bearer_network_pdu = network_pdu;
779         adv_bearer_request_can_send_now_for_network_pdu();
780     } else {
781 #ifdef LOG_NETWORK
782         printf("network run 7: skip sending %p via adv bearer\n", network_pdu);
783         #endif
784         // directly notify upper layer
785         mesh_network_send_complete(network_pdu);
786     }
787 #else
788     // done
789     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_adv);
790     // directly notify upper layer
791     mesh_network_send_complete(network_pdu);
792 #endif
793     return false;
794 }
795 
796 // returns true if done
797 static bool mesh_network_run_received(void){
798     if (mesh_crypto_active) {
799         return true;
800     }
801 
802     if (btstack_linked_list_empty(&network_pdus_received)) {
803         return true;
804     }
805 
806     incoming_pdu_decoded = mesh_network_pdu_get();
807     if (incoming_pdu_decoded == NULL) return true;
808 
809     // get encoded network pdu and start processing
810     mesh_crypto_active = 1;
811     incoming_pdu_raw = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_received);
812     process_network_pdu();
813     return true;
814 }
815 
816 // returns true if done
817 static bool mesh_network_run_queued(void){
818     if (mesh_crypto_active) {
819         return true;
820     }
821 
822     if (btstack_linked_list_empty(&network_pdus_queued)){
823         return true;
824     }
825 
826     // get queued network pdu and start processing
827     outgoing_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_queued);
828 
829 #ifdef LOG_NETWORK
830     printf("network run 5: pop %p from network_pdus_queued\n", outgoing_pdu);
831     mesh_network_dump_network_pdus("network_pdus_queued (2)", &network_pdus_queued);
832 #endif
833     mesh_network_send_a();
834     return true;
835 }
836 
837 static void mesh_network_run(void){
838     while (true){
839         bool done = true;
840         done &= mesh_network_run_gatt();
841         done &= mesh_network_run_adv();
842         done &= mesh_network_run_received();
843         done &= mesh_network_run_queued();
844         if (done) break;
845     }
846 }
847 
848 #ifdef ENABLE_MESH_ADV_BEARER
849 static void mesh_adv_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
850     UNUSED(channel);
851     mesh_network_pdu_t * network_pdu;
852     uint8_t  transmission_count;
853     uint16_t transmission_interval;
854     uint8_t  transmit_config;
855 
856     switch (packet_type){
857         case MESH_NETWORK_PACKET:
858             // check len. minimal transport PDU len = 1, 32 bit NetMIC -> 13 bytes
859             if (size < 13) break;
860 
861 #ifdef LOG_NETWORK
862             printf("received network pdu from adv (len %u): ", size);
863             printf_hexdump(packet, size);
864 #endif
865             mesh_network_received_message(packet, size, 0);
866             break;
867 
868         case HCI_EVENT_PACKET:
869             if (hci_event_packet_get_type(packet) != HCI_EVENT_MESH_META) break;
870 
871             switch(hci_event_mesh_meta_get_subevent_code(packet)){
872                 case MESH_SUBEVENT_CAN_SEND_NOW:
873                     if (adv_bearer_network_pdu == NULL) break;
874 
875                     // Get Transmission config depending on relay flag
876                     if (adv_bearer_network_pdu->flags & MESH_NETWORK_PDU_FLAGS_RELAY){
877                         transmit_config = mesh_foundation_relay_get();
878                     } else {
879                         transmit_config = mesh_foundation_network_transmit_get();
880                     }
881                     transmission_count     = (transmit_config & 0x07) + 1;
882                     transmission_interval = (transmit_config >> 3) * 10;
883 
884 #ifdef LOG_NETWORK
885                     printf("TX-E-NetworkPDU (%p) count %u, interval %u ms: ", adv_bearer_network_pdu, transmission_count, transmission_interval);
886                     printf_hexdump(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len);
887 #endif
888 
889                     adv_bearer_send_network_pdu(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len, transmission_count, transmission_interval);
890                     network_pdu = adv_bearer_network_pdu;
891                     adv_bearer_network_pdu = NULL;
892 
893                     // notify upper layer
894                     mesh_network_send_complete(network_pdu);
895 
896                     // check if more to send
897                     mesh_network_run();
898                     break;
899                 default:
900                     break;
901             }
902             break;
903         default:
904             break;
905     }
906 }
907 #endif
908 
909 #ifdef ENABLE_MESH_GATT_BEARER
910 static void mesh_network_gatt_bearer_outgoing_complete(void){
911 
912     if (gatt_bearer_network_pdu == NULL) return;
913 
914     // forward to adv bearer
915     btstack_linked_list_add_tail(&network_pdus_outgoing_adv, (btstack_linked_item_t*) gatt_bearer_network_pdu);
916     gatt_bearer_network_pdu = NULL;
917 
918     mesh_network_run();
919     return;
920 }
921 
922 static void mesh_network_gatt_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
923     UNUSED(channel);
924     switch (packet_type){
925         case MESH_PROXY_DATA_PACKET:
926             if (mesh_foundation_gatt_proxy_get() == 0) break;
927 #ifdef LOG_NETWORK
928             printf("received network pdu from gatt (len %u): ", size);
929             printf_hexdump(packet, size);
930 #endif
931             mesh_network_received_message(packet, size, MESH_NETWORK_PDU_FLAGS_GATT_BEARER);
932             break;
933         case HCI_EVENT_PACKET:
934             switch (hci_event_packet_get_type(packet)){
935                 case HCI_EVENT_MESH_META:
936                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
937                         case MESH_SUBEVENT_PROXY_CONNECTED:
938                             gatt_bearer_con_handle = mesh_subevent_proxy_connected_get_con_handle(packet);
939                             break;
940                         case MESH_SUBEVENT_PROXY_DISCONNECTED:
941                             gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
942                             mesh_network_gatt_bearer_outgoing_complete();
943                             break;
944                         case MESH_SUBEVENT_CAN_SEND_NOW:
945                             if (gatt_bearer_network_pdu == NULL) break;
946 #ifdef LOG_NETWORK
947                             printf("G-TX-E-NetworkPDU (%p): ", gatt_bearer_network_pdu);
948                             printf_hexdump(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
949 #endif
950                             gatt_bearer_send_network_pdu(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
951                             break;
952 
953                         case MESH_SUBEVENT_MESSAGE_SENT:
954                             mesh_network_gatt_bearer_outgoing_complete();
955                             break;
956                         default:
957                             break;
958                     }
959                     break;
960                 default:
961                     break;
962             }
963             break;
964         default:
965             break;
966     }
967 }
968 #endif
969 
970 #ifdef ENABLE_MESH_GATT_BEARER
971 static void mesh_netework_gatt_bearer_handle_proxy_configuration(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
972     UNUSED(channel);
973     switch (packet_type){
974         case MESH_PROXY_DATA_PACKET:
975             mesh_network_process_proxy_configuration_message(packet, size);
976             break;
977         case HCI_EVENT_PACKET:
978             switch (hci_event_packet_get_type(packet)){
979                 case HCI_EVENT_MESH_META:
980                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
981                         case MESH_SUBEVENT_CAN_SEND_NOW:
982                             // forward to higher layer
983                             (*mesh_network_proxy_message_handler)(MESH_NETWORK_CAN_SEND_NOW, NULL);
984                             break;
985                         default:
986                             break;
987                     }
988                     break;
989                 default:
990                     break;
991             }
992             break;
993         default:
994             break;
995     }
996 }
997 #endif
998 
999 void mesh_network_init(void){
1000 #ifdef ENABLE_MESH_ADV_BEARER
1001     adv_bearer_register_for_network_pdu(&mesh_adv_bearer_handle_network_event);
1002 #endif
1003 #ifdef ENABLE_MESH_GATT_BEARER
1004     gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
1005     gatt_bearer_register_for_network_pdu(&mesh_network_gatt_bearer_handle_network_event);
1006     gatt_bearer_register_for_mesh_proxy_configuration(&mesh_netework_gatt_bearer_handle_proxy_configuration);
1007 #endif
1008 }
1009 
1010 void mesh_network_set_higher_layer_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
1011     mesh_network_higher_layer_handler = packet_handler;
1012 }
1013 
1014 void mesh_network_set_proxy_message_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
1015     mesh_network_proxy_message_handler = packet_handler;
1016 }
1017 
1018 void mesh_network_received_message(const uint8_t * pdu_data, uint8_t pdu_len, uint8_t flags){
1019     // verify len
1020     if (pdu_len > 29) return;
1021 
1022     // allocate network_pdu
1023     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
1024     if (!network_pdu) return;
1025 
1026     // store data
1027     (void)memcpy(network_pdu->data, pdu_data, pdu_len);
1028     network_pdu->len = pdu_len;
1029     network_pdu->flags = flags;
1030 
1031     // add to list and go
1032     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
1033     mesh_network_run();
1034 
1035 }
1036 
1037 void mesh_network_process_proxy_configuration_message(const uint8_t * pdu_data, uint8_t pdu_len){
1038     // verify len
1039     if (pdu_len > 29) return;
1040 
1041     // allocate network_pdu
1042     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
1043     if (!network_pdu) return;
1044 
1045     // store data
1046     (void)memcpy(network_pdu->data, pdu_data, pdu_len);
1047     network_pdu->len = pdu_len;
1048     network_pdu->flags = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION; // Network PDU
1049 
1050     // add to list and go
1051     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
1052     mesh_network_run();
1053 }
1054 
1055 void mesh_network_send_pdu(mesh_network_pdu_t * network_pdu){
1056 #ifdef LOG_NETWORK
1057     printf("TX-NetworkPDU (%p):   ", network_pdu);
1058     printf_hexdump(network_pdu->data, network_pdu->len);
1059     printf("^^ into network_pdus_queued\n");
1060 #endif
1061 
1062     btstack_assert((network_pdu->len + (network_pdu->data[1] & 0x80 ? 8 : 4)) <= 29);
1063     btstack_assert(network_pdu->len >= 9);
1064 
1065     // setup callback
1066     network_pdu->flags    = 0;
1067 
1068     // queue up
1069     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
1070 #ifdef LOG_NETWORK
1071     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1072 #endif
1073 
1074     // go
1075     mesh_network_run();
1076 }
1077 
1078 void mesh_network_encrypt_proxy_configuration_message(mesh_network_pdu_t * network_pdu){
1079     printf("ProxyPDU(unencrypted): ");
1080     printf_hexdump(network_pdu->data, network_pdu->len);
1081 
1082     // setup callback
1083     network_pdu->flags    = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION;
1084 
1085     // queue up
1086     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
1087 
1088     // go
1089     mesh_network_run();
1090 }
1091 
1092 /*
1093  * @brief Setup network pdu header
1094  * @param netkey_index
1095  * @param ctl
1096  * @param ttl
1097  * @param seq
1098  * @param dest
1099  */
1100 void mesh_network_setup_pdu(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint8_t nid, uint8_t ctl, uint8_t ttl, uint32_t seq, uint16_t src, uint16_t dest, const uint8_t * transport_pdu_data, uint8_t transport_pdu_len){
1101     // set netkey_index
1102     network_pdu->netkey_index = netkey_index;
1103     // setup header
1104     network_pdu->len = 0;
1105     network_pdu->data[network_pdu->len++] = (mesh_get_iv_index_for_tx() << 7) |  nid;
1106     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
1107     network_pdu->data[network_pdu->len++] = ctl_ttl;
1108     big_endian_store_24(network_pdu->data, 2, seq);
1109     network_pdu->len += 3;
1110     big_endian_store_16(network_pdu->data, network_pdu->len, src);
1111     network_pdu->len += 2;
1112     big_endian_store_16(network_pdu->data, network_pdu->len, dest);
1113     network_pdu->len += 2;
1114     btstack_assert((network_pdu->len + transport_pdu_len) <= MESH_NETWORK_PAYLOAD_MAX);
1115     (void)memcpy(&network_pdu->data[network_pdu->len], transport_pdu_data,
1116                  transport_pdu_len);
1117     network_pdu->len += transport_pdu_len;
1118     // zero rest of packet
1119     memset(&network_pdu->data[network_pdu->len], 0, MESH_NETWORK_PAYLOAD_MAX - network_pdu->len);
1120 }
1121 
1122 /*
1123  * @brief Setup network pdu header
1124  * @param netkey_index
1125  * @param ctl
1126  * @param ttl
1127  * @param seq
1128  * @param dest
1129  */
1130 void mesh_network_setup_pdu_header(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint8_t nid, uint8_t ctl, uint8_t ttl, uint32_t seq, uint16_t src, uint16_t dest){
1131     // set netkey_index
1132     network_pdu->netkey_index = netkey_index;
1133     // setup header
1134     network_pdu->data[0] = (mesh_get_iv_index_for_tx() << 7) |  nid;
1135     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
1136     network_pdu->data[1] = ctl_ttl;
1137     big_endian_store_24(network_pdu->data, 2, seq);
1138     big_endian_store_16(network_pdu->data, 5, src);
1139     big_endian_store_16(network_pdu->data, 7, dest);
1140 }
1141 
1142 // Network PDU Getter
1143 uint8_t  mesh_network_nid(mesh_network_pdu_t * network_pdu){
1144     return network_pdu->data[0] & 0x7f;
1145 }
1146 uint16_t mesh_network_control(mesh_network_pdu_t * network_pdu){
1147     return network_pdu->data[1] & 0x80;
1148 }
1149 uint8_t mesh_network_ttl(mesh_network_pdu_t * network_pdu){
1150     return network_pdu->data[1] & 0x7f;
1151 }
1152 uint32_t mesh_network_seq(mesh_network_pdu_t * network_pdu){
1153     return big_endian_read_24(network_pdu->data, 2);
1154 }
1155 uint16_t mesh_network_src(mesh_network_pdu_t * network_pdu){
1156     return big_endian_read_16(network_pdu->data, 5);
1157 }
1158 uint16_t mesh_network_dst(mesh_network_pdu_t * network_pdu){
1159     return big_endian_read_16(network_pdu->data, 7);
1160 }
1161 int mesh_network_segmented(mesh_network_pdu_t * network_pdu){
1162     return network_pdu->data[9] & 0x80;
1163 }
1164 uint8_t mesh_network_control_opcode(mesh_network_pdu_t * network_pdu){
1165     return network_pdu->data[9] & 0x7f;
1166 }
1167 uint8_t * mesh_network_pdu_data(mesh_network_pdu_t * network_pdu){
1168     return &network_pdu->data[9];
1169 }
1170 uint8_t   mesh_network_pdu_len(mesh_network_pdu_t * network_pdu){
1171     return network_pdu->len - 9;
1172 }
1173 
1174 void mesh_network_pdu_set_seq(mesh_network_pdu_t * network_pdu, uint32_t seq){
1175     big_endian_store_24(network_pdu->data, 2, seq);
1176 }
1177 
1178 static void mesh_network_dump_network_pdu(mesh_network_pdu_t * network_pdu){
1179     if (network_pdu){
1180         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
1181     }
1182 }
1183 static void mesh_network_dump_network_pdus(const char * name, btstack_linked_list_t * list){
1184     printf("List: %s:\n", name);
1185     btstack_linked_list_iterator_t it;
1186     btstack_linked_list_iterator_init(&it, list);
1187     while (btstack_linked_list_iterator_has_next(&it)){
1188         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
1189         mesh_network_dump_network_pdu(network_pdu);
1190     }
1191 }
1192 static void mesh_network_reset_network_pdus(btstack_linked_list_t * list){
1193     while (!btstack_linked_list_empty(list)){
1194         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
1195         btstack_memory_mesh_network_pdu_free(pdu);
1196     }
1197 }
1198 void mesh_network_dump(void){
1199     mesh_network_dump_network_pdus("network_pdus_received", &network_pdus_received);
1200     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1201     mesh_network_dump_network_pdus("network_pdus_outgoing_gatt", &network_pdus_outgoing_gatt);
1202     mesh_network_dump_network_pdus("network_pdus_outgoing_adv", &network_pdus_outgoing_adv);
1203     printf("outgoing_pdu: \n");
1204     mesh_network_dump_network_pdu(outgoing_pdu);
1205     printf("incoming_pdu_raw: \n");
1206     mesh_network_dump_network_pdu(incoming_pdu_raw);
1207 #ifdef ENABLE_MESH_GATT_BEARER
1208     printf("gatt_bearer_network_pdu: \n");
1209     mesh_network_dump_network_pdu(gatt_bearer_network_pdu);
1210 #endif
1211 #ifdef ENABLE_MESH_ADV_BEARER
1212     printf("adv_bearer_network_pdu: \n");
1213     mesh_network_dump_network_pdu(adv_bearer_network_pdu);
1214 #endif
1215 
1216 }
1217 void mesh_network_reset(void){
1218     mesh_network_reset_network_pdus(&network_pdus_received);
1219     mesh_network_reset_network_pdus(&network_pdus_queued);
1220     mesh_network_reset_network_pdus(&network_pdus_outgoing_gatt);
1221     mesh_network_reset_network_pdus(&network_pdus_outgoing_adv);
1222 
1223     // outgoing network pdus are owned by higher layer, so we don't free:
1224     // - adv_bearer_network_pdu
1225     // - gatt_bearer_network_pdu
1226     // - outoing_pdu
1227     // unless they are SEG ACK messages
1228 #ifdef ENABLE_MESH_ADV_BEARER
1229     if ((adv_bearer_network_pdu != NULL) && (adv_bearer_network_pdu->pdu_header.pdu_type == MESH_PDU_TYPE_SEGMENT_ACKNOWLEDGMENT)){
1230         btstack_memory_mesh_network_pdu_free(adv_bearer_network_pdu);
1231     }
1232     adv_bearer_network_pdu = NULL;
1233 #endif
1234 #ifdef ENABLE_MESH_GATT_BEARER
1235     if ((gatt_bearer_network_pdu != NULL) && (gatt_bearer_network_pdu->pdu_header.pdu_type == MESH_PDU_TYPE_SEGMENT_ACKNOWLEDGMENT)){
1236         btstack_memory_mesh_network_pdu_free(gatt_bearer_network_pdu);
1237     }
1238     gatt_bearer_network_pdu = NULL;
1239 #endif
1240     if ((outgoing_pdu != NULL) && (outgoing_pdu->pdu_header.pdu_type == MESH_PDU_TYPE_SEGMENT_ACKNOWLEDGMENT)){
1241         btstack_memory_mesh_network_pdu_free(outgoing_pdu);
1242     }
1243     outgoing_pdu = NULL;
1244 
1245     if (incoming_pdu_raw){
1246         mesh_network_pdu_free(incoming_pdu_raw);
1247         incoming_pdu_raw = NULL;
1248     }
1249     if (incoming_pdu_decoded){
1250         mesh_network_pdu_free(incoming_pdu_decoded);
1251         incoming_pdu_decoded = NULL;
1252     }
1253     mesh_crypto_active = 0;
1254 }
1255 
1256 // buffer pool
1257 mesh_network_pdu_t * mesh_network_pdu_get(void){
1258     mesh_network_pdu_t * network_pdu = btstack_memory_mesh_network_pdu_get();
1259     if (network_pdu) {
1260         memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
1261         network_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_NETWORK;
1262     }
1263     return network_pdu;
1264 }
1265 
1266 void mesh_network_pdu_free(mesh_network_pdu_t * network_pdu){
1267     btstack_memory_mesh_network_pdu_free(network_pdu);
1268     if (mesh_network_free_pdu_callback!=NULL){
1269         void (*callback)(void) = mesh_network_free_pdu_callback;
1270         mesh_network_free_pdu_callback= NULL;
1271         (*callback)();
1272     }
1273 }
1274 
1275 void mesh_network_notify_on_freed_pdu(void (*callback)(void)){
1276     btstack_assert(mesh_network_free_pdu_callback == NULL);
1277     mesh_network_free_pdu_callback = callback;
1278 }
1279 
1280 
1281 // Mesh Subnet Management
1282 
1283 void mesh_subnet_add(mesh_subnet_t * subnet){
1284     btstack_linked_list_add_tail(&subnets, (btstack_linked_item_t *) subnet);
1285 }
1286 
1287 void mesh_subnet_remove(mesh_subnet_t * subnet){
1288     btstack_linked_list_remove(&subnets, (btstack_linked_item_t *) subnet);
1289 }
1290 
1291 mesh_subnet_t * mesh_subnet_get_by_netkey_index(uint16_t netkey_index){
1292     btstack_linked_list_iterator_t it;
1293     btstack_linked_list_iterator_init(&it, &subnets);
1294     while (btstack_linked_list_iterator_has_next(&it)){
1295         mesh_subnet_t * item = (mesh_subnet_t *) btstack_linked_list_iterator_next(&it);
1296         if (item->netkey_index == netkey_index) return item;
1297     }
1298     return NULL;
1299 }
1300 
1301 int mesh_subnet_list_count(void){
1302     return btstack_linked_list_count(&subnets);
1303 }
1304 
1305 // mesh network key iterator over all keys
1306 void mesh_subnet_iterator_init(mesh_subnet_iterator_t *it){
1307     btstack_linked_list_iterator_init(&it->it, &subnets);
1308 }
1309 
1310 int mesh_subnet_iterator_has_more(mesh_subnet_iterator_t *it){
1311     return btstack_linked_list_iterator_has_next(&it->it);
1312 }
1313 
1314 mesh_subnet_t * mesh_subnet_iterator_get_next(mesh_subnet_iterator_t *it){
1315     return (mesh_subnet_t *) btstack_linked_list_iterator_next(&it->it);
1316 }
1317 
1318 mesh_network_key_t * mesh_subnet_get_outgoing_network_key(mesh_subnet_t * subnet){
1319     switch (subnet->key_refresh){
1320         case MESH_KEY_REFRESH_SECOND_PHASE:
1321             return subnet->new_key;
1322         case MESH_KEY_REFRESH_NOT_ACTIVE:
1323         case MESH_KEY_REFRESH_FIRST_PHASE:
1324         default:
1325             return subnet->old_key;
1326     }
1327 }
1328 
1329 /**
1330  * @brief Setup subnet for given netkey index
1331  */
1332 void mesh_subnet_setup_for_netkey_index(uint16_t netkey_index){
1333     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
1334     if (subnet != NULL) return;
1335 
1336     // find old / new keys
1337     mesh_network_key_t * old_key = NULL;
1338     mesh_network_key_t * new_key = NULL;
1339     mesh_network_key_iterator_t it;
1340     mesh_network_key_iterator_init(&it);
1341     while (mesh_network_key_iterator_has_more(&it)){
1342         mesh_network_key_t * network_key = mesh_network_key_iterator_get_next(&it);
1343         if (network_key->netkey_index != netkey_index) continue;
1344         if (old_key == NULL){
1345             old_key = network_key;
1346             continue;
1347         }
1348         // assign current key depending on key version
1349         if (((int8_t) (network_key->version - new_key->version)) > 0) {
1350             new_key = network_key;
1351         } else {
1352             new_key = old_key;
1353             old_key = network_key;
1354         }
1355     }
1356 
1357     // create subnet for netkey index
1358     subnet = btstack_memory_mesh_subnet_get();
1359     if (subnet == NULL) return;
1360     subnet->netkey_index = netkey_index;
1361     mesh_subnet_add(subnet);
1362 
1363     // set keys
1364     subnet->old_key = old_key;
1365     subnet->new_key = new_key;
1366 
1367     // key refresh
1368     if (new_key == NULL){
1369         // single key -> key refresh not active
1370         subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1371     }
1372     else {
1373         // two keys -> at least phase 1
1374         subnet->key_refresh = MESH_KEY_REFRESH_FIRST_PHASE;
1375     }
1376 }
1377