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