xref: /btstack/src/mesh/mesh_network.c (revision c9921182ab4b1f83e3e5c671446dca5ffdf45b90)
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 // 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             switch(packet[0]){
870                 case HCI_EVENT_MESH_META:
871                     switch(packet[2]){
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             break;
907     }
908 }
909 #endif
910 
911 #ifdef ENABLE_MESH_GATT_BEARER
912 static void mesh_network_gatt_bearer_outgoing_complete(void){
913 
914     if (gatt_bearer_network_pdu == NULL) return;
915 
916     // forward to adv bearer
917     btstack_linked_list_add_tail(&network_pdus_outgoing_adv, (btstack_linked_item_t*) gatt_bearer_network_pdu);
918     gatt_bearer_network_pdu = NULL;
919 
920     mesh_network_run();
921     return;
922 }
923 
924 static void mesh_network_gatt_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
925     UNUSED(channel);
926     switch (packet_type){
927         case MESH_PROXY_DATA_PACKET:
928             if (mesh_foundation_gatt_proxy_get() == 0) break;
929 #ifdef LOG_NETWORK
930             printf("received network pdu from gatt (len %u): ", size);
931             printf_hexdump(packet, size);
932 #endif
933             mesh_network_received_message(packet, size, MESH_NETWORK_PDU_FLAGS_GATT_BEARER);
934             break;
935         case HCI_EVENT_PACKET:
936             switch (hci_event_packet_get_type(packet)){
937                 case HCI_EVENT_MESH_META:
938                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
939                         case MESH_SUBEVENT_PROXY_CONNECTED:
940                             gatt_bearer_con_handle = mesh_subevent_proxy_connected_get_con_handle(packet);
941                             break;
942                         case MESH_SUBEVENT_PROXY_DISCONNECTED:
943                             gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
944                             mesh_network_gatt_bearer_outgoing_complete();
945                             break;
946                         case MESH_SUBEVENT_CAN_SEND_NOW:
947                             if (gatt_bearer_network_pdu == NULL) break;
948 #ifdef LOG_NETWORK
949                             printf("G-TX-E-NetworkPDU (%p): ", gatt_bearer_network_pdu);
950                             printf_hexdump(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
951 #endif
952                             gatt_bearer_send_network_pdu(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
953                             break;
954 
955                         case MESH_SUBEVENT_MESSAGE_SENT:
956                             mesh_network_gatt_bearer_outgoing_complete();
957                             break;
958                         default:
959                             break;
960                     }
961                     break;
962                 default:
963                     break;
964             }
965             break;
966         default:
967             break;
968     }
969 }
970 #endif
971 
972 #ifdef ENABLE_MESH_GATT_BEARER
973 static void mesh_netework_gatt_bearer_handle_proxy_configuration(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
974     UNUSED(channel);
975     switch (packet_type){
976         case MESH_PROXY_DATA_PACKET:
977             mesh_network_process_proxy_configuration_message(packet, size);
978             break;
979         case HCI_EVENT_PACKET:
980             switch (hci_event_packet_get_type(packet)){
981                 case HCI_EVENT_MESH_META:
982                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
983                         case MESH_SUBEVENT_CAN_SEND_NOW:
984                             // forward to higher layer
985                             (*mesh_network_proxy_message_handler)(MESH_NETWORK_CAN_SEND_NOW, NULL);
986                             break;
987                         default:
988                             break;
989                     }
990                     break;
991                 default:
992                     break;
993             }
994             break;
995         default:
996             break;
997     }
998 }
999 #endif
1000 
1001 void mesh_network_init(void){
1002 #ifdef ENABLE_MESH_ADV_BEARER
1003     adv_bearer_register_for_network_pdu(&mesh_adv_bearer_handle_network_event);
1004 #endif
1005 #ifdef ENABLE_MESH_GATT_BEARER
1006     gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
1007     gatt_bearer_register_for_network_pdu(&mesh_network_gatt_bearer_handle_network_event);
1008     gatt_bearer_register_for_mesh_proxy_configuration(&mesh_netework_gatt_bearer_handle_proxy_configuration);
1009 #endif
1010 }
1011 
1012 void mesh_network_set_higher_layer_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
1013     mesh_network_higher_layer_handler = packet_handler;
1014 }
1015 
1016 void mesh_network_set_proxy_message_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
1017     mesh_network_proxy_message_handler = packet_handler;
1018 }
1019 
1020 void mesh_network_received_message(const uint8_t * pdu_data, uint8_t pdu_len, uint8_t flags){
1021     // verify len
1022     if (pdu_len > 29) return;
1023 
1024     // allocate network_pdu
1025     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
1026     if (!network_pdu) return;
1027 
1028     // store data
1029     (void)memcpy(network_pdu->data, pdu_data, pdu_len);
1030     network_pdu->len = pdu_len;
1031     network_pdu->flags = flags;
1032 
1033     // add to list and go
1034     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
1035     mesh_network_run();
1036 
1037 }
1038 
1039 void mesh_network_process_proxy_configuration_message(const uint8_t * pdu_data, uint8_t pdu_len){
1040     // verify len
1041     if (pdu_len > 29) return;
1042 
1043     // allocate network_pdu
1044     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
1045     if (!network_pdu) return;
1046 
1047     // store data
1048     (void)memcpy(network_pdu->data, pdu_data, pdu_len);
1049     network_pdu->len = pdu_len;
1050     network_pdu->flags = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION; // Network PDU
1051 
1052     // add to list and go
1053     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
1054     mesh_network_run();
1055 }
1056 
1057 void mesh_network_send_pdu(mesh_network_pdu_t * network_pdu){
1058 #ifdef LOG_NETWORK
1059     printf("TX-NetworkPDU (%p):   ", network_pdu);
1060     printf_hexdump(network_pdu->data, network_pdu->len);
1061     printf("^^ into network_pdus_queued\n");
1062 #endif
1063 
1064     btstack_assert((network_pdu->len + (network_pdu->data[1] & 0x80 ? 8 : 4)) <= 29);
1065     btstack_assert(network_pdu->len >= 9);
1066 
1067     // setup callback
1068     network_pdu->flags    = 0;
1069 
1070     // queue up
1071     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
1072 #ifdef LOG_NETWORK
1073     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1074 #endif
1075 
1076     // go
1077     mesh_network_run();
1078 }
1079 
1080 void mesh_network_encrypt_proxy_configuration_message(mesh_network_pdu_t * network_pdu){
1081     printf("ProxyPDU(unencrypted): ");
1082     printf_hexdump(network_pdu->data, network_pdu->len);
1083 
1084     // setup callback
1085     network_pdu->flags    = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION;
1086 
1087     // queue up
1088     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
1089 
1090     // go
1091     mesh_network_run();
1092 }
1093 
1094 /*
1095  * @brief Setup network pdu header
1096  * @param netkey_index
1097  * @param ctl
1098  * @param ttl
1099  * @param seq
1100  * @param dest
1101  */
1102 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){
1103     // set netkey_index
1104     network_pdu->netkey_index = netkey_index;
1105     // setup header
1106     network_pdu->len = 0;
1107     network_pdu->data[network_pdu->len++] = (mesh_get_iv_index_for_tx() << 7) |  nid;
1108     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
1109     network_pdu->data[network_pdu->len++] = ctl_ttl;
1110     big_endian_store_24(network_pdu->data, 2, seq);
1111     network_pdu->len += 3;
1112     big_endian_store_16(network_pdu->data, network_pdu->len, src);
1113     network_pdu->len += 2;
1114     big_endian_store_16(network_pdu->data, network_pdu->len, dest);
1115     network_pdu->len += 2;
1116     btstack_assert((network_pdu->len + transport_pdu_len) <= MESH_NETWORK_PAYLOAD_MAX);
1117     (void)memcpy(&network_pdu->data[network_pdu->len], transport_pdu_data,
1118                  transport_pdu_len);
1119     network_pdu->len += transport_pdu_len;
1120     // zero rest of packet
1121     memset(&network_pdu->data[network_pdu->len], 0, MESH_NETWORK_PAYLOAD_MAX - network_pdu->len);
1122 }
1123 
1124 /*
1125  * @brief Setup network pdu header
1126  * @param netkey_index
1127  * @param ctl
1128  * @param ttl
1129  * @param seq
1130  * @param dest
1131  */
1132 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){
1133     // set netkey_index
1134     network_pdu->netkey_index = netkey_index;
1135     // setup header
1136     network_pdu->data[0] = (mesh_get_iv_index_for_tx() << 7) |  nid;
1137     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
1138     network_pdu->data[1] = ctl_ttl;
1139     big_endian_store_24(network_pdu->data, 2, seq);
1140     big_endian_store_16(network_pdu->data, 5, src);
1141     big_endian_store_16(network_pdu->data, 7, dest);
1142 }
1143 
1144 // Network PDU Getter
1145 uint8_t  mesh_network_nid(mesh_network_pdu_t * network_pdu){
1146     return network_pdu->data[0] & 0x7f;
1147 }
1148 uint16_t mesh_network_control(mesh_network_pdu_t * network_pdu){
1149     return network_pdu->data[1] & 0x80;
1150 }
1151 uint8_t mesh_network_ttl(mesh_network_pdu_t * network_pdu){
1152     return network_pdu->data[1] & 0x7f;
1153 }
1154 uint32_t mesh_network_seq(mesh_network_pdu_t * network_pdu){
1155     return big_endian_read_24(network_pdu->data, 2);
1156 }
1157 uint16_t mesh_network_src(mesh_network_pdu_t * network_pdu){
1158     return big_endian_read_16(network_pdu->data, 5);
1159 }
1160 uint16_t mesh_network_dst(mesh_network_pdu_t * network_pdu){
1161     return big_endian_read_16(network_pdu->data, 7);
1162 }
1163 int mesh_network_segmented(mesh_network_pdu_t * network_pdu){
1164     return network_pdu->data[9] & 0x80;
1165 }
1166 uint8_t mesh_network_control_opcode(mesh_network_pdu_t * network_pdu){
1167     return network_pdu->data[9] & 0x7f;
1168 }
1169 uint8_t * mesh_network_pdu_data(mesh_network_pdu_t * network_pdu){
1170     return &network_pdu->data[9];
1171 }
1172 uint8_t   mesh_network_pdu_len(mesh_network_pdu_t * network_pdu){
1173     return network_pdu->len - 9;
1174 }
1175 
1176 void mesh_network_pdu_set_seq(mesh_network_pdu_t * network_pdu, uint32_t seq){
1177     big_endian_store_24(network_pdu->data, 2, seq);
1178 }
1179 
1180 static void mesh_network_dump_network_pdu(mesh_network_pdu_t * network_pdu){
1181     if (network_pdu){
1182         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
1183     }
1184 }
1185 static void mesh_network_dump_network_pdus(const char * name, btstack_linked_list_t * list){
1186     printf("List: %s:\n", name);
1187     btstack_linked_list_iterator_t it;
1188     btstack_linked_list_iterator_init(&it, list);
1189     while (btstack_linked_list_iterator_has_next(&it)){
1190         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
1191         mesh_network_dump_network_pdu(network_pdu);
1192     }
1193 }
1194 static void mesh_network_reset_network_pdus(btstack_linked_list_t * list){
1195     while (!btstack_linked_list_empty(list)){
1196         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
1197         btstack_memory_mesh_network_pdu_free(pdu);
1198     }
1199 }
1200 void mesh_network_dump(void){
1201     mesh_network_dump_network_pdus("network_pdus_received", &network_pdus_received);
1202     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1203     mesh_network_dump_network_pdus("network_pdus_outgoing_gatt", &network_pdus_outgoing_gatt);
1204     mesh_network_dump_network_pdus("network_pdus_outgoing_adv", &network_pdus_outgoing_adv);
1205     printf("outgoing_pdu: \n");
1206     mesh_network_dump_network_pdu(outgoing_pdu);
1207     printf("incoming_pdu_raw: \n");
1208     mesh_network_dump_network_pdu(incoming_pdu_raw);
1209 #ifdef ENABLE_MESH_GATT_BEARER
1210     printf("gatt_bearer_network_pdu: \n");
1211     mesh_network_dump_network_pdu(gatt_bearer_network_pdu);
1212 #endif
1213 #ifdef ENABLE_MESH_ADV_BEARER
1214     printf("adv_bearer_network_pdu: \n");
1215     mesh_network_dump_network_pdu(adv_bearer_network_pdu);
1216 #endif
1217 
1218 }
1219 void mesh_network_reset(void){
1220     mesh_network_reset_network_pdus(&network_pdus_received);
1221     mesh_network_reset_network_pdus(&network_pdus_queued);
1222     mesh_network_reset_network_pdus(&network_pdus_outgoing_gatt);
1223     mesh_network_reset_network_pdus(&network_pdus_outgoing_adv);
1224 
1225     // outgoing network pdus are owned by higher layer, so we don't free:
1226     // - adv_bearer_network_pdu
1227     // - gatt_bearer_network_pdu
1228     // - outoing_pdu
1229 #ifdef ENABLE_MESH_ADV_BEARER
1230     adv_bearer_network_pdu = NULL;
1231 #endif
1232 #ifdef ENABLE_MESH_GATT_BEARER
1233     gatt_bearer_network_pdu = NULL;
1234 #endif
1235     outgoing_pdu = NULL;
1236 
1237     if (incoming_pdu_raw){
1238         mesh_network_pdu_free(incoming_pdu_raw);
1239         incoming_pdu_raw = NULL;
1240     }
1241     if (incoming_pdu_decoded){
1242         mesh_network_pdu_free(incoming_pdu_decoded);
1243         incoming_pdu_decoded = NULL;
1244     }
1245     mesh_crypto_active = 0;
1246 }
1247 
1248 // buffer pool
1249 mesh_network_pdu_t * mesh_network_pdu_get(void){
1250     mesh_network_pdu_t * network_pdu = btstack_memory_mesh_network_pdu_get();
1251     if (network_pdu) {
1252         memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
1253         network_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_NETWORK;
1254     }
1255     return network_pdu;
1256 }
1257 
1258 void mesh_network_pdu_free(mesh_network_pdu_t * network_pdu){
1259     btstack_memory_mesh_network_pdu_free(network_pdu);
1260     if (mesh_network_free_pdu_callback!=NULL){
1261         void (*callback)(void) = mesh_network_free_pdu_callback;
1262         mesh_network_free_pdu_callback= NULL;
1263         (*callback)();
1264     }
1265 }
1266 
1267 void mesh_network_notify_on_freed_pdu(void (*callback)(void)){
1268     btstack_assert(mesh_network_free_pdu_callback == NULL);
1269     mesh_network_free_pdu_callback = callback;
1270 }
1271 
1272 
1273 // Mesh Subnet Management
1274 
1275 void mesh_subnet_add(mesh_subnet_t * subnet){
1276     btstack_linked_list_add_tail(&subnets, (btstack_linked_item_t *) subnet);
1277 }
1278 
1279 void mesh_subnet_remove(mesh_subnet_t * subnet){
1280     btstack_linked_list_remove(&subnets, (btstack_linked_item_t *) subnet);
1281 }
1282 
1283 mesh_subnet_t * mesh_subnet_get_by_netkey_index(uint16_t netkey_index){
1284     btstack_linked_list_iterator_t it;
1285     btstack_linked_list_iterator_init(&it, &subnets);
1286     while (btstack_linked_list_iterator_has_next(&it)){
1287         mesh_subnet_t * item = (mesh_subnet_t *) btstack_linked_list_iterator_next(&it);
1288         if (item->netkey_index == netkey_index) return item;
1289     }
1290     return NULL;
1291 }
1292 
1293 int mesh_subnet_list_count(void){
1294     return btstack_linked_list_count(&subnets);
1295 }
1296 
1297 // mesh network key iterator over all keys
1298 void mesh_subnet_iterator_init(mesh_subnet_iterator_t *it){
1299     btstack_linked_list_iterator_init(&it->it, &subnets);
1300 }
1301 
1302 int mesh_subnet_iterator_has_more(mesh_subnet_iterator_t *it){
1303     return btstack_linked_list_iterator_has_next(&it->it);
1304 }
1305 
1306 mesh_subnet_t * mesh_subnet_iterator_get_next(mesh_subnet_iterator_t *it){
1307     return (mesh_subnet_t *) btstack_linked_list_iterator_next(&it->it);
1308 }
1309 
1310 mesh_network_key_t * mesh_subnet_get_outgoing_network_key(mesh_subnet_t * subnet){
1311     switch (subnet->key_refresh){
1312         case MESH_KEY_REFRESH_SECOND_PHASE:
1313             return subnet->new_key;
1314         case MESH_KEY_REFRESH_NOT_ACTIVE:
1315         case MESH_KEY_REFRESH_FIRST_PHASE:
1316         default:
1317             return subnet->old_key;
1318     }
1319 }
1320 
1321 /**
1322  * @brief Setup subnet for given netkey index
1323  */
1324 void mesh_subnet_setup_for_netkey_index(uint16_t netkey_index){
1325     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
1326     if (subnet != NULL) return;
1327 
1328     // find old / new keys
1329     mesh_network_key_t * old_key = NULL;
1330     mesh_network_key_t * new_key = NULL;
1331     mesh_network_key_iterator_t it;
1332     mesh_network_key_iterator_init(&it);
1333     while (mesh_network_key_iterator_has_more(&it)){
1334         mesh_network_key_t * network_key = mesh_network_key_iterator_get_next(&it);
1335         if (network_key->netkey_index != netkey_index) continue;
1336         if (old_key == NULL){
1337             old_key = network_key;
1338             continue;
1339         }
1340         // assign current key depending on key version
1341         if (((int8_t) (network_key->version - new_key->version)) > 0) {
1342             new_key = network_key;
1343         } else {
1344             new_key = old_key;
1345             old_key = network_key;
1346         }
1347     }
1348 
1349     // create subnet for netkey index
1350     subnet = btstack_memory_mesh_subnet_get();
1351     if (subnet == NULL) return;
1352     subnet->netkey_index = netkey_index;
1353     mesh_subnet_add(subnet);
1354 
1355     // set keys
1356     subnet->old_key = old_key;
1357     subnet->new_key = new_key;
1358 
1359     // key refresh
1360     if (new_key == NULL){
1361         // single key -> key refresh not active
1362         subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1363     }
1364     else {
1365         // two keys -> at least phase 1
1366         subnet->key_refresh = MESH_KEY_REFRESH_FIRST_PHASE;
1367     }
1368 }
1369