xref: /btstack/src/mesh/mesh_network.c (revision 0ede23cc6eac275801541e169c35c1e9f13e182c)
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     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     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     memcpy(&outgoing_pdu->data[outgoing_pdu->len], net_mic, net_mic_len);
325     outgoing_pdu->len += net_mic_len;
326 
327 #ifdef LOG_NETWORK
328     printf("TX-B-NetworkPDU (%p): ", outgoing_pdu);
329     printf_hexdump(outgoing_pdu->data, outgoing_pdu->len);
330 #endif
331 
332     // calc PECB
333     memset(encryption_block, 0, 5);
334     big_endian_store_32(encryption_block, 5, iv_index);
335     memcpy(&encryption_block[9], &outgoing_pdu->data[7], 7);
336     btstack_crypto_aes128_encrypt(&mesh_network_crypto_request.aes128, current_network_key->privacy_key, encryption_block, obfuscation_block, &mesh_network_send_c, NULL);
337 }
338 
339 static void mesh_network_send_a(void){
340 
341     mesh_crypto_active = 1;
342 
343     uint32_t iv_index = mesh_get_iv_index_for_tx();
344 
345     // lookup subnet by netkey_index
346     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(outgoing_pdu->netkey_index);
347     if (!subnet) {
348         mesh_crypto_active = 0;
349         mesh_network_pdu_t * network_pdu = outgoing_pdu;
350         outgoing_pdu = NULL;
351         // notify upper layer
352         mesh_network_send_complete(network_pdu);
353         // run again
354         mesh_network_run();
355         return;
356     }
357 
358     // get network key to use for sending
359     current_network_key = mesh_subnet_get_outgoing_network_key(subnet);
360 
361 #ifdef LOG_NETWORK
362     printf("TX-A-NetworkPDU (%p): ", outgoing_pdu);
363     printf_hexdump(outgoing_pdu->data, outgoing_pdu->len);
364 #endif
365 
366     // get network nonce
367     if (outgoing_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
368         mesh_proxy_create_nonce(network_nonce, outgoing_pdu, iv_index);
369 #ifdef LOG_NETWORK
370         printf("TX-ProxyNonce:  ");
371         printf_hexdump(network_nonce, 13);
372 #endif
373     } else {
374         mesh_network_create_nonce(network_nonce, outgoing_pdu, iv_index);
375 #ifdef LOG_NETWORK
376         printf("TX-NetworkNonce:  ");
377         printf_hexdump(network_nonce, 13);
378 #endif
379     }
380 
381 #ifdef LOG_NETWORK
382    printf("TX-EncryptionKey: ");
383     printf_hexdump(current_network_key->encryption_key, 16);
384 #endif
385 
386     // start ccm
387     uint8_t cypher_len  = outgoing_pdu->len - 7;
388     uint8_t net_mic_len = outgoing_pdu->data[1] & 0x80 ? 8 : 4;
389     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
390     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);
391 }
392 
393 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
394 static void mesh_network_relay_message(mesh_network_pdu_t * network_pdu){
395 
396     uint8_t ctl_ttl     = network_pdu->data[1];
397     uint8_t ctl         = ctl_ttl & 0x80;
398     uint8_t ttl         = ctl_ttl & 0x7f;
399 
400 #ifdef LOG_NETWORK
401     printf("TX-Relay-NetworkPDU (%p): ", network_pdu);
402     printf_hexdump(network_pdu->data, network_pdu->len);
403     printf("^^ into network_pdus_queued\n");
404 #endif
405 
406     // prepare pdu for resending
407     network_pdu->data[1] = (ctl << 7) | (ttl - 1);
408     network_pdu->flags |= MESH_NETWORK_PDU_FLAGS_RELAY;
409 
410     // queue up
411     network_pdu->callback = &mesh_network_send_d;
412     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
413 }
414 #endif
415 
416 void mesh_network_message_processed_by_higher_layer(mesh_network_pdu_t * network_pdu){
417 
418 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
419 
420     // check if address does not matches elements on our node and TTL >= 2
421     uint16_t src     = mesh_network_src(network_pdu);
422     uint8_t  ttl     = mesh_network_ttl(network_pdu);
423 
424     uint16_t mesh_network_primary_address = mesh_node_get_primary_element_address();
425 
426     if (((src < mesh_network_primary_address) || (src > (mesh_network_primary_address + mesh_node_element_count()))) && (ttl >= 2)){
427 
428         if ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0){
429 
430             // message received via ADV bearer are relayed:
431 
432 #ifdef ENABLE_MESH_RELAY
433             if (mesh_foundation_relay_get() != 0){
434                 // - to ADV bearer, if Relay supported and enabled
435                 mesh_network_relay_message(network_pdu);
436                 mesh_network_run();
437                 return;
438             }
439 #endif
440 
441 #ifdef ENABLE_MESH_PROXY_SERVER
442             if (mesh_foundation_gatt_proxy_get() != 0){
443                 // - to GATT bearer, if Proxy supported and enabled
444                 mesh_network_relay_message(network_pdu);
445                 mesh_network_run();
446                 return;
447             }
448 #endif
449 
450         } else {
451 
452             // messages received via GATT bearer are relayed:
453 
454 #ifdef ENABLE_MESH_PROXY_SERVER
455             if (mesh_foundation_gatt_proxy_get() != 0){
456                 // - to ADV bearer, if Proxy supported and enabled
457                 mesh_network_relay_message(network_pdu);
458                 mesh_network_run();
459                 return;
460             }
461 #endif
462 
463         }
464     }
465 #endif
466 
467     // otherwise, we're done
468     btstack_memory_mesh_network_pdu_free(network_pdu);
469 }
470 
471 static void process_network_pdu_done(void){
472     btstack_memory_mesh_network_pdu_free(incoming_pdu_raw);
473     incoming_pdu_raw = NULL;
474     mesh_crypto_active = 0;
475 
476     mesh_network_run();
477 }
478 
479 static void process_network_pdu_validate_d(void * arg){
480     UNUSED(arg);
481     // mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
482 
483     uint8_t ctl_ttl     = incoming_pdu_decoded->data[1];
484     uint8_t ctl         = ctl_ttl >> 7;
485     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
486 
487     // store NetMIC
488     uint8_t net_mic[8];
489     btstack_crypto_ccm_get_authentication_value(&mesh_network_crypto_request.ccm, net_mic);
490 #ifdef LOG_NETWORK
491     printf("RX-NetMIC: ");
492     printf_hexdump(net_mic, net_mic_len);
493 #endif
494     // store in decoded pdu
495     memcpy(&incoming_pdu_decoded->data[incoming_pdu_decoded->len-net_mic_len], net_mic, net_mic_len);
496 
497 #ifdef LOG_NETWORK
498     uint8_t cypher_len  = incoming_pdu_decoded->len - 9 - net_mic_len;
499     printf("RX-Decrypted DST/TransportPDU: ");
500     printf_hexdump(&incoming_pdu_decoded->data[7], 2 + cypher_len);
501 
502     printf("RX-Decrypted: ");
503     printf_hexdump(incoming_pdu_decoded->data, incoming_pdu_decoded->len);
504 #endif
505 
506     // validate network mic
507     if (memcmp(net_mic, &incoming_pdu_raw->data[incoming_pdu_decoded->len-net_mic_len], net_mic_len) != 0){
508         // fail
509         printf("RX-NetMIC mismatch, try next key\n");
510         process_network_pdu_validate();
511         return;
512     }
513 
514     // remove NetMIC from payload
515     incoming_pdu_decoded->len -= net_mic_len;
516 
517 #ifdef LOG_NETWORK
518     // match
519     printf("RX-NetMIC matches\n");
520     printf("RX-TTL: 0x%02x\n", incoming_pdu_decoded->data[1] & 0x7f);
521 #endif
522 
523     // set netkey_index
524     incoming_pdu_decoded->netkey_index = current_network_key->netkey_index;
525 
526     if (incoming_pdu_decoded->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
527 
528         mesh_network_pdu_t * decoded_pdu = incoming_pdu_decoded;
529         incoming_pdu_decoded = NULL;
530 
531         // no additional checks for proxy messages
532         (*mesh_network_proxy_message_handler)(MESH_NETWORK_PDU_RECEIVED, decoded_pdu);
533 
534     } else {
535 
536         // validate src/dest addresses
537         uint16_t src = big_endian_read_16(incoming_pdu_decoded->data, 5);
538         uint16_t dst = big_endian_read_16(incoming_pdu_decoded->data, 7);
539         int valid = mesh_network_addresses_valid(ctl, src, dst);
540         if (!valid){
541             printf("RX Address invalid\n");
542             btstack_memory_mesh_network_pdu_free(incoming_pdu_decoded);
543             incoming_pdu_decoded = NULL;
544             process_network_pdu_done();
545             return;
546         }
547 
548         // check cache
549         uint32_t hash = mesh_network_cache_hash(incoming_pdu_decoded);
550 #ifdef LOG_NETWORK
551         printf("RX-Hash: %08x\n", hash);
552 #endif
553         if (mesh_network_cache_find(hash)){
554             // found in cache, drop
555             printf("Found in cache -> drop packet\n");
556             btstack_memory_mesh_network_pdu_free(incoming_pdu_decoded);
557             incoming_pdu_decoded = NULL;
558             process_network_pdu_done();
559             return;
560         }
561 
562         // store in network cache
563         mesh_network_cache_add(hash);
564 
565         // forward to lower transport layer. message is freed by call to mesh_network_message_processed_by_upper_layer
566         mesh_network_pdu_t * decoded_pdu = incoming_pdu_decoded;
567         incoming_pdu_decoded = NULL;
568         (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_RECEIVED, decoded_pdu);
569     }
570 
571     // done
572     process_network_pdu_done();
573 }
574 
575 static uint32_t iv_index_for_pdu(const mesh_network_pdu_t * network_pdu){
576     // get IV Index and IVI
577     uint32_t iv_index = mesh_get_iv_index();
578     int ivi = network_pdu->data[0] >> 7;
579 
580     // if least significant bit differs, use previous IV Index
581     if ((iv_index & 1 ) ^ ivi){
582         iv_index--;
583 #ifdef LOG_NETWORK
584         printf("RX-IV: IVI indicates previous IV index, using 0x%08x\n", iv_index);
585 #endif
586     }
587     return iv_index;
588 }
589 
590 static void process_network_pdu_validate_b(void * arg){
591     UNUSED(arg);
592 
593 #ifdef LOG_NETWORK
594     printf("RX-PECB: ");
595     printf_hexdump(obfuscation_block, 6);
596 #endif
597 
598     // de-obfuscate
599     unsigned int i;
600     for (i=0;i<6;i++){
601         incoming_pdu_decoded->data[1+i] = incoming_pdu_raw->data[1+i] ^ obfuscation_block[i];
602     }
603 
604     uint32_t iv_index = iv_index_for_pdu(incoming_pdu_raw);
605 
606     if (incoming_pdu_decoded->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
607         // create network nonce
608         mesh_proxy_create_nonce(network_nonce, incoming_pdu_decoded, iv_index);
609 #ifdef LOG_NETWORK
610         printf("RX-Proxy Nonce: ");
611         printf_hexdump(network_nonce, 13);
612 #endif
613     } else {
614         // create network nonce
615         mesh_network_create_nonce(network_nonce, incoming_pdu_decoded, iv_index);
616 #ifdef LOG_NETWORK
617         printf("RX-Network Nonce: ");
618         printf_hexdump(network_nonce, 13);
619 #endif
620     }
621 
622     //
623     uint8_t ctl_ttl     = incoming_pdu_decoded->data[1];
624     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
625     uint8_t cypher_len  = incoming_pdu_decoded->len - 7 - net_mic_len;
626 
627 #ifdef LOG_NETWORK
628     printf("RX-Cyper len %u, mic len %u\n", cypher_len, net_mic_len);
629 
630     printf("RX-Encryption Key: ");
631     printf_hexdump(current_network_key->encryption_key, 16);
632 
633 #endif
634 
635     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
636     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);
637 }
638 
639 static void process_network_pdu_validate(void){
640     if (!mesh_network_key_nid_iterator_has_more(&validation_network_key_it)){
641         printf("No valid network key found\n");
642         btstack_memory_mesh_network_pdu_free(incoming_pdu_decoded);
643         incoming_pdu_decoded = NULL;
644         process_network_pdu_done();
645         return;
646     }
647 
648     current_network_key = mesh_network_key_nid_iterator_get_next(&validation_network_key_it);
649 
650     // calc PECB
651     uint32_t iv_index = iv_index_for_pdu(incoming_pdu_raw);
652     memset(encryption_block, 0, 5);
653     big_endian_store_32(encryption_block, 5, iv_index);
654     memcpy(&encryption_block[9], &incoming_pdu_raw->data[7], 7);
655     btstack_crypto_aes128_encrypt(&mesh_network_crypto_request.aes128, current_network_key->privacy_key, encryption_block, obfuscation_block, &process_network_pdu_validate_b, NULL);
656 }
657 
658 
659 static void process_network_pdu(void){
660     //
661     uint8_t nid_ivi = incoming_pdu_raw->data[0];
662 
663     // setup pdu object
664     incoming_pdu_decoded->data[0] = nid_ivi;
665     incoming_pdu_decoded->len     = incoming_pdu_raw->len;
666     incoming_pdu_decoded->flags   = incoming_pdu_raw->flags;
667 
668     // init provisioning data iterator
669     uint8_t nid = nid_ivi & 0x7f;
670     // uint8_t iv_index = network_pdu_data[0] >> 7;
671     mesh_network_key_nid_iterator_init(&validation_network_key_it, nid);
672 
673     process_network_pdu_validate();
674 }
675 
676 static void mesh_network_run(void){
677     if (!btstack_linked_list_empty(&network_pdus_outgoing_gatt)){
678 
679 
680 #ifdef ENABLE_MESH_GATT_BEARER
681         if (gatt_bearer_network_pdu == NULL){
682             // move to 'gatt bearer queue'
683             mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_gatt);
684 
685 #ifdef LOG_NETWORK
686         printf("network run: pop %p from network_pdus_outgoing_gatt\n", network_pdu);
687 #endif
688         // request to send via gatt if:
689         // proxy active and connected
690         // packet wasn't received via gatt bearer
691             int send_via_gatt = ((mesh_foundation_gatt_proxy_get() != 0) &&
692             (gatt_bearer_con_handle != HCI_CON_HANDLE_INVALID) &&
693                                  ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0));
694             if (send_via_gatt){
695 #ifdef LOG_NETWORK
696         printf("network run: set %p as gatt_bearer_network_pdu\n", network_pdu);
697 #endif
698 
699                gatt_bearer_network_pdu = network_pdu;
700                 gatt_bearer_request_can_send_now_for_network_pdu();
701             } else {
702 #ifdef LOG_NETWORK
703         printf("network run: push %p to network_pdus_outgoing_adv\n", network_pdu);
704 #endif
705                 btstack_linked_list_add_tail(&network_pdus_outgoing_adv, (btstack_linked_item_t *) network_pdu);
706             }
707         }
708 #else
709         // directly move to 'outgoing adv bearer queue'
710         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_gatt);
711         btstack_linked_list_add_tail(&network_pdus_outgoing_adv, (btstack_linked_item_t *) network_pdu);
712 #endif
713     }
714 
715     if (!btstack_linked_list_empty(&network_pdus_outgoing_adv)){
716 #ifdef ENABLE_MESH_ADV_BEARER
717         if (adv_bearer_network_pdu == NULL){
718             // move to 'adv bearer queue'
719 #ifdef LOG_NETWORK
720             mesh_network_dump_network_pdus("network_pdus_outgoing_adv", &network_pdus_outgoing_adv);
721 #endif
722             mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_adv);
723 #ifdef LOG_NETWORK
724             printf("network run: pop %p from network_pdus_outgoing_adv\n", network_pdu);
725             mesh_network_dump_network_pdus("network_pdus_outgoing_adv", &network_pdus_outgoing_adv);
726 #endif
727             adv_bearer_network_pdu = network_pdu;
728             adv_bearer_request_can_send_now_for_network_pdu();
729         }
730 #else
731         // done
732         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing_adv);
733         // directly notify upper layer
734         mesh_network_send_complete(network_pdu);
735 #endif
736     }
737 
738     if (mesh_crypto_active) return;
739 
740     if (!btstack_linked_list_empty(&network_pdus_received)){
741         incoming_pdu_decoded = mesh_network_pdu_get();
742         if (!incoming_pdu_decoded) return;
743         // get encoded network pdu and start processing
744         mesh_crypto_active = 1;
745         incoming_pdu_raw = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_received);
746         process_network_pdu();
747         return;
748     }
749 
750     if (!btstack_linked_list_empty(&network_pdus_queued)){
751         // get queued network pdu and start processing
752 #ifdef LOG_NETWORK
753         mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
754 #endif
755         outgoing_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_queued);
756 #ifdef LOG_NETWORK
757         printf("network run: pop %p from network_pdus_queued\n", outgoing_pdu);
758         mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
759 #endif
760         mesh_network_send_a();
761         return;
762     }
763 }
764 
765 #ifdef ENABLE_MESH_ADV_BEARER
766 static void mesh_adv_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
767     UNUSED(channel);
768     mesh_network_pdu_t * network_pdu;
769     uint8_t  transmission_count;
770     uint16_t transmission_interval;
771     uint8_t  transmit_config;
772 
773     switch (packet_type){
774         case MESH_NETWORK_PACKET:
775             // check len. minimal transport PDU len = 1, 32 bit NetMIC -> 13 bytes
776             if (size < 13) break;
777 
778 #ifdef LOG_NETWORK
779             printf("received network pdu from adv (len %u): ", size);
780             printf_hexdump(packet, size);
781 #endif
782             mesh_network_received_message(packet, size, 0);
783             break;
784 
785         case HCI_EVENT_PACKET:
786             switch(packet[0]){
787                 case HCI_EVENT_MESH_META:
788                     switch(packet[2]){
789                         case MESH_SUBEVENT_CAN_SEND_NOW:
790                             if (adv_bearer_network_pdu == NULL) break;
791 
792                             // Get Transmission config depending on relay flag
793                             if (adv_bearer_network_pdu->flags & MESH_NETWORK_PDU_FLAGS_RELAY){
794                                 transmit_config = mesh_foundation_relay_get();
795                             } else {
796                                 transmit_config = mesh_foundation_network_transmit_get();
797                             }
798                             transmission_count     = (transmit_config & 0x07) + 1;
799                             transmission_interval = (transmit_config >> 3) * 10;
800 
801 #ifdef LOG_NETWORK
802                             printf("TX-E-NetworkPDU count %u, interval %u ms (%p): ", transmission_count, transmission_interval, adv_bearer_network_pdu);
803                             printf_hexdump(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len);
804 #endif
805 
806                             adv_bearer_send_network_pdu(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len, transmission_count, transmission_interval);
807                             network_pdu = adv_bearer_network_pdu;
808                             adv_bearer_network_pdu = NULL;
809 
810                             // notify upper layer
811                             mesh_network_send_complete(network_pdu);
812 
813                             // check if more to send
814                             mesh_network_run();
815                             break;
816                         default:
817                             break;
818                     }
819                     break;
820                 default:
821                     break;
822             }
823             break;
824     }
825 }
826 #endif
827 
828 #ifdef ENABLE_MESH_GATT_BEARER
829 static void mesh_network_gatt_bearer_outgoing_complete(void){
830 
831     if (gatt_bearer_network_pdu == NULL) return;
832 
833     // forward to adv bearer
834     btstack_linked_list_add_tail(&network_pdus_outgoing_adv, (btstack_linked_item_t*) gatt_bearer_network_pdu);
835     gatt_bearer_network_pdu = NULL;
836 
837     mesh_network_run();
838     return;
839 }
840 
841 static void mesh_network_gatt_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
842     UNUSED(channel);
843     switch (packet_type){
844         case MESH_PROXY_DATA_PACKET:
845             if (mesh_foundation_gatt_proxy_get() == 0) break;
846 #ifdef LOG_NETWORK
847             printf("received network pdu from gatt (len %u): ", size);
848             printf_hexdump(packet, size);
849 #endif
850             mesh_network_received_message(packet, size, MESH_NETWORK_PDU_FLAGS_GATT_BEARER);
851             break;
852         case HCI_EVENT_PACKET:
853             switch (hci_event_packet_get_type(packet)){
854                 case HCI_EVENT_MESH_META:
855                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
856                         case MESH_SUBEVENT_PROXY_CONNECTED:
857                             gatt_bearer_con_handle = mesh_subevent_proxy_connected_get_con_handle(packet);
858                             break;
859                         case MESH_SUBEVENT_PROXY_DISCONNECTED:
860                             gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
861                             mesh_network_gatt_bearer_outgoing_complete();
862                             break;
863                         case MESH_SUBEVENT_CAN_SEND_NOW:
864                             if (gatt_bearer_network_pdu == NULL) break;
865 #ifdef LOG_NETWORK
866                             printf("G-TX-E-NetworkPDU (%p): ", gatt_bearer_network_pdu);
867                             printf_hexdump(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
868 #endif
869                             gatt_bearer_send_network_pdu(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
870                             break;
871 
872                         case MESH_SUBEVENT_MESSAGE_SENT:
873                             mesh_network_gatt_bearer_outgoing_complete();
874                             break;
875                         default:
876                             break;
877                     }
878                     break;
879                 default:
880                     break;
881             }
882             break;
883         default:
884             break;
885     }
886 }
887 #endif
888 
889 #ifdef ENABLE_MESH_GATT_BEARER
890 static void mesh_netework_gatt_bearer_handle_proxy_configuration(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
891     UNUSED(channel);
892     switch (packet_type){
893         case MESH_PROXY_DATA_PACKET:
894             mesh_network_process_proxy_configuration_message(packet, size);
895             break;
896         case HCI_EVENT_PACKET:
897             switch (hci_event_packet_get_type(packet)){
898                 case HCI_EVENT_MESH_META:
899                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
900                         case MESH_SUBEVENT_CAN_SEND_NOW:
901                             // forward to higher layer
902                             (*mesh_network_proxy_message_handler)(MESH_NETWORK_CAN_SEND_NOW, NULL);
903                             break;
904                         default:
905                             break;
906                     }
907                     break;
908                 default:
909                     break;
910             }
911             break;
912         default:
913             break;
914     }
915 }
916 #endif
917 
918 void mesh_network_init(void){
919 #ifdef ENABLE_MESH_ADV_BEARER
920     adv_bearer_register_for_network_pdu(&mesh_adv_bearer_handle_network_event);
921 #endif
922 #ifdef ENABLE_MESH_GATT_BEARER
923     gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
924     gatt_bearer_register_for_network_pdu(&mesh_network_gatt_bearer_handle_network_event);
925     gatt_bearer_register_for_mesh_proxy_configuration(&mesh_netework_gatt_bearer_handle_proxy_configuration);
926 #endif
927 }
928 
929 void mesh_network_set_higher_layer_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
930     mesh_network_higher_layer_handler = packet_handler;
931 }
932 
933 void mesh_network_set_proxy_message_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
934     mesh_network_proxy_message_handler = packet_handler;
935 }
936 
937 void mesh_network_received_message(const uint8_t * pdu_data, uint8_t pdu_len, uint8_t flags){
938     // verify len
939     if (pdu_len > 29) return;
940 
941     // allocate network_pdu
942     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
943     if (!network_pdu) return;
944 
945     // store data
946     memcpy(network_pdu->data, pdu_data, pdu_len);
947     network_pdu->len = pdu_len;
948     network_pdu->flags = flags;
949 
950     // add to list and go
951     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
952     mesh_network_run();
953 
954 }
955 
956 void mesh_network_process_proxy_configuration_message(const uint8_t * pdu_data, uint8_t pdu_len){
957     // verify len
958     if (pdu_len > 29) return;
959 
960     // allocate network_pdu
961     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
962     if (!network_pdu) return;
963 
964     // store data
965     memcpy(network_pdu->data, pdu_data, pdu_len);
966     network_pdu->len = pdu_len;
967     network_pdu->flags = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION; // Network PDU
968 
969     // add to list and go
970     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
971     mesh_network_run();
972 }
973 
974 void mesh_network_send_pdu(mesh_network_pdu_t * network_pdu){
975 #ifdef LOG_NETWORK
976     printf("TX-NetworkPDU (%p):   ", network_pdu);
977     printf_hexdump(network_pdu->data, network_pdu->len);
978     printf("^^ into network_pdus_queued\n");
979 #endif
980 
981     if (network_pdu->len > 29){
982         printf("too long, %u\n", network_pdu->len);
983         while(1);
984     }
985 
986     // network pdu without payload and minimal mic = 13 bytes
987     if (network_pdu->len <13){
988         printf("too short, %u\n", network_pdu->len);
989         while(1);
990     }
991 
992     // setup callback
993     network_pdu->callback = &mesh_network_send_d;
994     network_pdu->flags    = 0;
995 
996     // queue up
997     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
998 #ifdef LOG_NETWORK
999     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1000 #endif
1001 
1002     // go
1003     mesh_network_run();
1004 }
1005 
1006 void mesh_network_encrypt_proxy_configuration_message(mesh_network_pdu_t * network_pdu, void (* callback)(mesh_network_pdu_t * callback)){
1007     printf("ProxyPDU(unencrypted): ");
1008     printf_hexdump(network_pdu->data, network_pdu->len);
1009 
1010     // setup callback
1011     network_pdu->callback = callback;
1012     network_pdu->flags    = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION;
1013 
1014     // queue up
1015     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
1016 
1017     // go
1018     mesh_network_run();
1019 }
1020 
1021 /*
1022  * @brief Setup network pdu header
1023  * @param netkey_index
1024  * @param ctl
1025  * @param ttl
1026  * @param seq
1027  * @param dest
1028  */
1029 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){
1030     memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
1031     // set netkey_index
1032     network_pdu->netkey_index = netkey_index;
1033     // setup header
1034     network_pdu->data[network_pdu->len++] = (mesh_get_iv_index_for_tx() << 7) |  nid;
1035     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
1036     network_pdu->data[network_pdu->len++] = ctl_ttl;
1037     big_endian_store_24(network_pdu->data, 2, seq);
1038     network_pdu->len += 3;
1039     big_endian_store_16(network_pdu->data, network_pdu->len, src);
1040     network_pdu->len += 2;
1041     big_endian_store_16(network_pdu->data, network_pdu->len, dest);
1042     network_pdu->len += 2;
1043     memcpy(&network_pdu->data[network_pdu->len], transport_pdu_data, transport_pdu_len);
1044     network_pdu->len += transport_pdu_len;
1045 }
1046 
1047 /*
1048  * @brief Setup network pdu header
1049  * @param netkey_index
1050  * @param ctl
1051  * @param ttl
1052  * @param seq
1053  * @param dest
1054  */
1055 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){
1056     // set netkey_index
1057     network_pdu->netkey_index = netkey_index;
1058     // setup header
1059     network_pdu->data[0] = (mesh_get_iv_index_for_tx() << 7) |  nid;
1060     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
1061     network_pdu->data[1] = ctl_ttl;
1062     big_endian_store_24(network_pdu->data, 2, seq);
1063     big_endian_store_16(network_pdu->data, 5, src);
1064     big_endian_store_16(network_pdu->data, 7, dest);
1065 }
1066 
1067 // Network PDU Getter
1068 uint8_t  mesh_network_nid(mesh_network_pdu_t * network_pdu){
1069     return network_pdu->data[0] & 0x7f;
1070 }
1071 uint16_t mesh_network_control(mesh_network_pdu_t * network_pdu){
1072     return network_pdu->data[1] & 0x80;
1073 }
1074 uint8_t mesh_network_ttl(mesh_network_pdu_t * network_pdu){
1075     return network_pdu->data[1] & 0x7f;
1076 }
1077 uint32_t mesh_network_seq(mesh_network_pdu_t * network_pdu){
1078     return big_endian_read_24(network_pdu->data, 2);
1079 }
1080 uint16_t mesh_network_src(mesh_network_pdu_t * network_pdu){
1081     return big_endian_read_16(network_pdu->data, 5);
1082 }
1083 uint16_t mesh_network_dst(mesh_network_pdu_t * network_pdu){
1084     return big_endian_read_16(network_pdu->data, 7);
1085 }
1086 int mesh_network_segmented(mesh_network_pdu_t * network_pdu){
1087     return network_pdu->data[9] & 0x80;
1088 }
1089 uint8_t mesh_network_control_opcode(mesh_network_pdu_t * network_pdu){
1090     return network_pdu->data[9] & 0x7f;
1091 }
1092 uint8_t * mesh_network_pdu_data(mesh_network_pdu_t * network_pdu){
1093     return &network_pdu->data[9];
1094 }
1095 uint8_t   mesh_network_pdu_len(mesh_network_pdu_t * network_pdu){
1096     return network_pdu->len - 9;
1097 }
1098 
1099 static void mesh_network_dump_network_pdu(mesh_network_pdu_t * network_pdu){
1100     if (network_pdu){
1101         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
1102     }
1103 }
1104 static void mesh_network_dump_network_pdus(const char * name, btstack_linked_list_t * list){
1105     printf("List: %s:\n", name);
1106     btstack_linked_list_iterator_t it;
1107     btstack_linked_list_iterator_init(&it, list);
1108     while (btstack_linked_list_iterator_has_next(&it)){
1109         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
1110         mesh_network_dump_network_pdu(network_pdu);
1111     }
1112 }
1113 static void mesh_network_reset_network_pdus(btstack_linked_list_t * list){
1114     while (!btstack_linked_list_empty(list)){
1115         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
1116         btstack_memory_mesh_network_pdu_free(pdu);
1117     }
1118 }
1119 void mesh_network_dump(void){
1120     mesh_network_dump_network_pdus("network_pdus_received", &network_pdus_received);
1121     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1122     mesh_network_dump_network_pdus("network_pdus_outgoing_gatt", &network_pdus_outgoing_gatt);
1123     mesh_network_dump_network_pdus("network_pdus_outgoing_adv", &network_pdus_outgoing_adv);
1124     printf("outgoing_pdu: \n");
1125     mesh_network_dump_network_pdu(outgoing_pdu);
1126     printf("incoming_pdu_raw: \n");
1127     mesh_network_dump_network_pdu(incoming_pdu_raw);
1128     printf("gatt_bearer_network_pdu: \n");
1129     mesh_network_dump_network_pdu(gatt_bearer_network_pdu);
1130     printf("adv_bearer_network_pdu: \n");
1131     mesh_network_dump_network_pdu(adv_bearer_network_pdu);
1132 }
1133 void mesh_network_reset(void){
1134     mesh_network_reset_network_pdus(&network_pdus_received);
1135     mesh_network_reset_network_pdus(&network_pdus_queued);
1136     mesh_network_reset_network_pdus(&network_pdus_outgoing_gatt);
1137     mesh_network_reset_network_pdus(&network_pdus_outgoing_adv);
1138     if (adv_bearer_network_pdu){
1139         mesh_network_pdu_free(adv_bearer_network_pdu);
1140         adv_bearer_network_pdu = NULL;
1141     }
1142     if (gatt_bearer_network_pdu){
1143         mesh_network_pdu_free(gatt_bearer_network_pdu);
1144         gatt_bearer_network_pdu = NULL;
1145     }
1146     if (outgoing_pdu){
1147         mesh_network_pdu_free(outgoing_pdu);
1148         outgoing_pdu = NULL;
1149     }
1150     if (incoming_pdu_raw){
1151         mesh_network_pdu_free(incoming_pdu_raw);
1152         incoming_pdu_raw = NULL;
1153     }
1154     if (incoming_pdu_decoded){
1155         mesh_network_pdu_free(incoming_pdu_decoded);
1156         incoming_pdu_decoded = NULL;
1157     }
1158     mesh_crypto_active = 0;
1159 }
1160 
1161 // buffer pool
1162 mesh_network_pdu_t * mesh_network_pdu_get(void){
1163     mesh_network_pdu_t * network_pdu = btstack_memory_mesh_network_pdu_get();
1164     if (network_pdu) {
1165         memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
1166         network_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_NETWORK;
1167     }
1168     return network_pdu;
1169 }
1170 
1171 void mesh_network_pdu_free(mesh_network_pdu_t * network_pdu){
1172     btstack_memory_mesh_network_pdu_free(network_pdu);
1173 }
1174 
1175 // Mesh Subnet Management
1176 
1177 void mesh_subnet_add(mesh_subnet_t * subnet){
1178     btstack_linked_list_add_tail(&subnets, (btstack_linked_item_t *) subnet);
1179 }
1180 
1181 void mesh_subnet_remove(mesh_subnet_t * subnet){
1182     btstack_linked_list_remove(&subnets, (btstack_linked_item_t *) subnet);
1183 }
1184 
1185 mesh_subnet_t * mesh_subnet_get_by_netkey_index(uint16_t netkey_index){
1186     btstack_linked_list_iterator_t it;
1187     btstack_linked_list_iterator_init(&it, &subnets);
1188     while (btstack_linked_list_iterator_has_next(&it)){
1189         mesh_subnet_t * item = (mesh_subnet_t *) btstack_linked_list_iterator_next(&it);
1190         if (item->netkey_index == netkey_index) return item;
1191     }
1192     return NULL;
1193 }
1194 
1195 int mesh_subnet_list_count(void){
1196     return btstack_linked_list_count(&subnets);
1197 }
1198 
1199 // mesh network key iterator over all keys
1200 void mesh_subnet_iterator_init(mesh_subnet_iterator_t *it){
1201     btstack_linked_list_iterator_init(&it->it, &subnets);
1202 }
1203 
1204 int mesh_subnet_iterator_has_more(mesh_subnet_iterator_t *it){
1205     return btstack_linked_list_iterator_has_next(&it->it);
1206 }
1207 
1208 mesh_subnet_t * mesh_subnet_iterator_get_next(mesh_subnet_iterator_t *it){
1209     return (mesh_subnet_t *) btstack_linked_list_iterator_next(&it->it);
1210 }
1211 
1212 mesh_network_key_t * mesh_subnet_get_outgoing_network_key(mesh_subnet_t * subnet){
1213     switch (subnet->key_refresh){
1214         case MESH_KEY_REFRESH_SECOND_PHASE:
1215             return subnet->new_key;
1216         case MESH_KEY_REFRESH_NOT_ACTIVE:
1217         case MESH_KEY_REFRESH_FIRST_PHASE:
1218         default:
1219             return subnet->old_key;
1220     }
1221 }
1222 
1223 /**
1224  * @brief Setup subnet for given netkey index
1225  */
1226 void mesh_subnet_setup_for_netkey_index(uint16_t netkey_index){
1227     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
1228     if (subnet != NULL) return;
1229 
1230     // find old / new keys
1231     mesh_network_key_t * old_key = NULL;
1232     mesh_network_key_t * new_key = NULL;
1233     mesh_network_key_iterator_t it;
1234     mesh_network_key_iterator_init(&it);
1235     while (mesh_network_key_iterator_has_more(&it)){
1236         mesh_network_key_t * network_key = mesh_network_key_iterator_get_next(&it);
1237         if (network_key->netkey_index != netkey_index) continue;
1238         if (old_key == NULL){
1239             old_key = network_key;
1240             continue;
1241         }
1242         // assign current key depending on key version
1243         if (((int8_t) (network_key->version - new_key->version)) > 0) {
1244             new_key = network_key;
1245         } else {
1246             new_key = old_key;
1247             old_key = network_key;
1248         }
1249     }
1250 
1251     // create subnet for netkey index
1252     subnet = btstack_memory_mesh_subnet_get();
1253     if (subnet == NULL) return;
1254     subnet->netkey_index = netkey_index;
1255     mesh_subnet_add(subnet);
1256 
1257     // set keys
1258     subnet->old_key = old_key;
1259     subnet->new_key = new_key;
1260 
1261     // key refresh
1262     if (new_key == NULL){
1263         // single key -> key refresh not active
1264         subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1265     }
1266     else {
1267         // two keys -> at least phase 1
1268         subnet->key_refresh = MESH_KEY_REFRESH_FIRST_PHASE;
1269     }
1270 }
1271