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