xref: /btstack/src/mesh/mesh_upper_transport.c (revision cae44b3ba863442855cdde1aef115bc53c4e4599)
1 /*
2  * Copyright (C) 2014 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_upper_transport.c"
39 
40 #include "mesh/mesh_upper_transport.h"
41 
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 
46 #include "btstack_util.h"
47 #include "btstack_memory.h"
48 #include "btstack_debug.h"
49 
50 #include "mesh/beacon.h"
51 #include "mesh/mesh_iv_index_seq_number.h"
52 #include "mesh/mesh_keys.h"
53 #include "mesh/mesh_lower_transport.h"
54 #include "mesh/mesh_peer.h"
55 #include "mesh/mesh_virtual_addresses.h"
56 
57 // TODO: extract mesh_pdu functions into lower transport or network
58 #include "mesh/mesh_access.h"
59 
60 // combined key x address iterator for upper transport decryption
61 
62 typedef struct {
63     // state
64     mesh_transport_key_iterator_t  key_it;
65     mesh_virtual_address_iterator_t address_it;
66     // elements
67     const mesh_transport_key_t *   key;
68     const mesh_virtual_address_t * address;
69     // address - might be virtual
70     uint16_t dst;
71     // key info
72 } mesh_transport_key_and_virtual_address_iterator_t;
73 
74 static void (*higher_layer_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu);
75 
76 static void mesh_upper_transport_validate_unsegmented_message(void);
77 static void mesh_upper_transport_validate_segmented_message(void);
78 static void mesh_upper_transport_run(void);
79 
80 static int crypto_active;
81 static mesh_unsegmented_incoming_pdu_t * incoming_unsegmented_pdu_raw;
82 static mesh_network_pdu_t   * incoming_network_pdu_decoded;
83 static mesh_transport_pdu_t   incoming_transport_pdu_singleton;
84 static mesh_transport_pdu_t * incoming_transport_pdu_raw;
85 static mesh_transport_pdu_t * incoming_transport_pdu_decoded;
86 static mesh_message_pdu_t     incoming_message_pdu_singleton;
87 static uint8_t application_nonce[13];
88 static btstack_crypto_ccm_t ccm;
89 static mesh_transport_key_and_virtual_address_iterator_t mesh_transport_key_it;
90 
91 // upper transport callbacks - in access layer
92 static void (*mesh_access_message_handler)(mesh_pdu_t * pdu);
93 static void (*mesh_control_message_handler)(mesh_pdu_t * pdu);
94 
95 // incoming unsegmented (network) and segmented (transport) control and access messages
96 static btstack_linked_list_t upper_transport_incoming;
97 
98 // outgoing unsegmented (network) and segmented (uppert_transport_outgoing) control and access messages
99 static btstack_linked_list_t upper_transport_outgoing;
100 
101 
102 // TODO: higher layer define used for assert
103 #define MESH_ACCESS_OPCODE_NOT_SET 0xFFFFFFFEu
104 
105 void mesh_upper_transport_send_access_pdu(mesh_pdu_t *pdu){
106     btstack_assert(pdu->pdu_type != MESH_PDU_TYPE_NETWORK);
107 
108     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
109     mesh_upper_transport_run();
110 }
111 
112 void mesh_upper_transport_send_control_pdu(mesh_pdu_t * pdu){
113     if (pdu->pdu_type == MESH_PDU_TYPE_NETWORK){
114         btstack_assert( ((mesh_network_pdu_t *) pdu)->len >= 9);
115     }
116 
117     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
118     mesh_upper_transport_run();
119 }
120 
121 static void mesh_print_hex(const char * name, const uint8_t * data, uint16_t len){
122     printf("%-20s ", name);
123     printf_hexdump(data, len);
124 }
125 // static void mesh_print_x(const char * name, uint32_t value){
126 //     printf("%20s: 0x%x", name, (int) value);
127 // }
128 
129 static void mesh_transport_key_and_virtual_address_iterator_init(mesh_transport_key_and_virtual_address_iterator_t *it,
130                                                                  uint16_t dst, uint16_t netkey_index, uint8_t akf,
131                                                                  uint8_t aid) {
132     printf("KEY_INIT: dst %04x, akf %x, aid %x\n", dst, akf, aid);
133     // config
134     it->dst   = dst;
135     // init elements
136     it->key     = NULL;
137     it->address = NULL;
138     // init element iterators
139     mesh_transport_key_aid_iterator_init(&it->key_it, netkey_index, akf, aid);
140     // init address iterator
141     if (mesh_network_address_virtual(it->dst)){
142         mesh_virtual_address_iterator_init(&it->address_it, dst);
143         // get first key
144         if (mesh_transport_key_aid_iterator_has_more(&it->key_it)) {
145             it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
146         }
147     }
148 }
149 
150 // cartesian product: keys x addressses
151 static int mesh_transport_key_and_virtual_address_iterator_has_more(mesh_transport_key_and_virtual_address_iterator_t * it){
152     if (mesh_network_address_virtual(it->dst)) {
153         // find next valid entry
154         while (true){
155             if (mesh_virtual_address_iterator_has_more(&it->address_it)) return 1;
156             if (!mesh_transport_key_aid_iterator_has_more(&it->key_it)) return 0;
157             // get next key
158             it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
159             mesh_virtual_address_iterator_init(&it->address_it, it->dst);
160         }
161     } else {
162         return mesh_transport_key_aid_iterator_has_more(&it->key_it);
163     }
164 }
165 
166 static void mesh_transport_key_and_virtual_address_iterator_next(mesh_transport_key_and_virtual_address_iterator_t * it){
167     if (mesh_network_address_virtual(it->dst)) {
168         it->address = mesh_virtual_address_iterator_get_next(&it->address_it);
169     } else {
170         it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
171     }
172 }
173 
174 // UPPER TRANSPORT
175 
176 // stub lower transport
177 
178 static void mesh_upper_transport_dump_pdus(const char *name, btstack_linked_list_t *list){
179     printf("List: %s:\n", name);
180     btstack_linked_list_iterator_t it;
181     btstack_linked_list_iterator_init(&it, list);
182     while (btstack_linked_list_iterator_has_next(&it)){
183         mesh_pdu_t * pdu = (mesh_pdu_t*) btstack_linked_list_iterator_next(&it);
184         printf("- %p\n", pdu);
185         // printf_hexdump( mesh_pdu_data(pdu), mesh_pdu_len(pdu));
186     }
187 }
188 
189 static void mesh_upper_transport_reset_pdus(btstack_linked_list_t *list){
190     while (!btstack_linked_list_empty(list)){
191         mesh_upper_transport_pdu_free((mesh_pdu_t *) btstack_linked_list_pop(list));
192     }
193 }
194 
195 void mesh_upper_transport_dump(void){
196     printf("incoming_unsegmented_pdu_raw: %p\n", incoming_unsegmented_pdu_raw);
197     printf("incoming_network_pdu_decoded: %p\n", incoming_network_pdu_decoded);
198     mesh_upper_transport_dump_pdus("upper_transport_incoming", &upper_transport_incoming);
199 }
200 
201 void mesh_upper_transport_reset(void){
202     crypto_active = 0;
203     if (incoming_unsegmented_pdu_raw){
204         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&incoming_unsegmented_pdu_raw->segments);
205         btstack_assert(network_pdu != NULL);
206         mesh_network_pdu_free(network_pdu);
207         incoming_unsegmented_pdu_raw = NULL;
208     }
209     mesh_upper_transport_reset_pdus(&upper_transport_incoming);
210 }
211 
212 static uint32_t iv_index_for_ivi_nid(uint8_t ivi_nid){
213     // get IV Index and IVI
214     uint32_t iv_index = mesh_get_iv_index();
215     int ivi = ivi_nid >> 7;
216 
217     // if least significant bit differs, use previous IV Index
218     if ((iv_index & 1 ) ^ ivi){
219         iv_index--;
220     }
221     return iv_index;
222 }
223 
224 static void transport_unsegmented_setup_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
225     nonce[1] = 0x00;    // SZMIC if a Segmented Access message or 0 for all other message formats
226     (void)memcpy(&nonce[2], &network_pdu->data[2], 7);
227     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(network_pdu->data[0]));
228 }
229 
230 static void transport_segmented_setup_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
231     nonce[1] = transport_pdu->transmic_len == 8 ? 0x80 : 0x00;
232     (void)memcpy(&nonce[2], &transport_pdu->network_header[2], 7);
233     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(transport_pdu->network_header[0]));
234 }
235 
236 static void transport_unsegmented_setup_application_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
237     nonce[0] = 0x01;
238     transport_unsegmented_setup_nonce(nonce, network_pdu);
239     mesh_print_hex("AppNonce", nonce, 13);
240 }
241 
242 static void transport_unsegmented_setup_device_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
243     nonce[0] = 0x02;
244     transport_unsegmented_setup_nonce(nonce, network_pdu);
245     mesh_print_hex("DeviceNonce", nonce, 13);
246 }
247 
248 static void transport_segmented_setup_application_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
249     nonce[0] = 0x01;
250     transport_segmented_setup_nonce(nonce, transport_pdu);
251     mesh_print_hex("AppNonce", nonce, 13);
252 }
253 
254 static void transport_segmented_setup_device_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
255     nonce[0] = 0x02;
256     transport_segmented_setup_nonce(nonce, transport_pdu);
257     mesh_print_hex("DeviceNonce", nonce, 13);
258 }
259 
260 static void mesh_upper_unsegmented_control_message_received(mesh_network_pdu_t * network_pdu){
261     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
262     uint8_t  opcode = lower_transport_pdu[0];
263     if (mesh_control_message_handler){
264         mesh_control_message_handler((mesh_pdu_t*) network_pdu);
265     } else {
266         printf("[!] Unhandled Control message with opcode %02x\n", opcode);
267         // done
268         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
269     }
270 }
271 
272 static void mesh_upper_transport_process_message_done(mesh_message_pdu_t *message_pdu){
273     crypto_active = 0;
274     btstack_assert(message_pdu == &incoming_message_pdu_singleton);
275     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&incoming_message_pdu_singleton.segments);
276     if (mesh_network_control(network_pdu)) {
277         btstack_assert(0);
278     } else {
279         btstack_assert(network_pdu != NULL);
280         mesh_network_pdu_free(network_pdu);
281         mesh_pdu_t * pdu = (mesh_pdu_t *) incoming_unsegmented_pdu_raw;
282         incoming_unsegmented_pdu_raw = NULL;
283         mesh_lower_transport_message_processed_by_higher_layer(pdu);
284     }
285     mesh_upper_transport_run();
286 }
287 
288 static void mesh_upper_transport_process_unsegmented_message_done(mesh_network_pdu_t *network_pdu){
289     crypto_active = 0;
290     if (mesh_network_control(network_pdu)) {
291         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
292     } else {
293         btstack_assert(network_pdu != NULL);
294         mesh_network_pdu_free(network_pdu);
295         mesh_pdu_t * pdu = (mesh_pdu_t *) incoming_unsegmented_pdu_raw;
296         incoming_unsegmented_pdu_raw = NULL;
297         incoming_unsegmented_pdu_raw = NULL;
298         mesh_lower_transport_message_processed_by_higher_layer(pdu);
299     }
300     mesh_upper_transport_run();
301 }
302 
303 static void mesh_upper_transport_process_segmented_message_done(mesh_transport_pdu_t *transport_pdu){
304     crypto_active = 0;
305     if (mesh_transport_ctl(transport_pdu)) {
306         btstack_assert(0);
307     } else {
308         mesh_transport_pdu_free(transport_pdu);
309         incoming_transport_pdu_raw = NULL;
310     }
311     mesh_upper_transport_run();
312 }
313 
314 static void mesh_upper_transport_validate_unsegmented_message_ccm(void * arg){
315     UNUSED(arg);
316 
317     uint8_t * lower_transport_pdu = mesh_network_pdu_data(incoming_network_pdu_decoded);
318     uint8_t trans_mic_len = 4;
319 
320     // store TransMIC
321     uint8_t trans_mic[8];
322     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
323     mesh_print_hex("TransMIC", trans_mic, trans_mic_len);
324 
325     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(incoming_network_pdu_decoded) + 1;
326     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(incoming_network_pdu_decoded)  - 1;
327 
328     mesh_print_hex("Decryted PDU", upper_transport_pdu, upper_transport_pdu_len - trans_mic_len);
329 
330     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len - trans_mic_len], trans_mic_len) == 0){
331         printf("TransMIC matches\n");
332 
333         // remove TransMIC from payload
334         incoming_network_pdu_decoded->len -= trans_mic_len;
335 
336         // if virtual address, update dst to pseudo_dst
337         if (mesh_network_address_virtual(mesh_network_dst(incoming_network_pdu_decoded))){
338             big_endian_store_16(incoming_network_pdu_decoded->data, 7, mesh_transport_key_it.address->pseudo_dst);
339         }
340 
341         // pass to upper layer
342         if (mesh_access_message_handler){
343             mesh_pdu_t * pdu = (mesh_pdu_t*) incoming_network_pdu_decoded;
344             incoming_network_pdu_decoded = NULL;
345             mesh_access_message_handler((mesh_pdu_t*) &incoming_message_pdu_singleton);
346         } else {
347             printf("[!] Unhandled Unsegmented Access message\n");
348             // done
349             mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
350         }
351 
352         printf("\n");
353     } else {
354         uint8_t afk = lower_transport_pdu[0] & 0x40;
355         if (afk){
356             printf("TransMIC does not match, try next key\n");
357             mesh_upper_transport_validate_unsegmented_message();
358         } else {
359             printf("TransMIC does not match device key, done\n");
360             // done
361             mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
362         }
363     }
364 }
365 
366 static void mesh_upper_transport_validate_segmented_message_ccm(void * arg){
367     UNUSED(arg);
368 
369     uint8_t * upper_transport_pdu     =  incoming_transport_pdu_decoded->data;
370     uint8_t   upper_transport_pdu_len =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
371 
372     mesh_print_hex("Decrypted PDU", upper_transport_pdu, upper_transport_pdu_len);
373 
374     // store TransMIC
375     uint8_t trans_mic[8];
376     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
377     mesh_print_hex("TransMIC", trans_mic, incoming_transport_pdu_decoded->transmic_len);
378 
379     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len], incoming_transport_pdu_decoded->transmic_len) == 0){
380         printf("TransMIC matches\n");
381 
382         // remove TransMIC from payload
383         incoming_transport_pdu_decoded->len -= incoming_transport_pdu_decoded->transmic_len;
384 
385         // if virtual address, update dst to pseudo_dst
386         if (mesh_network_address_virtual(mesh_transport_dst(incoming_transport_pdu_decoded))){
387             big_endian_store_16(incoming_transport_pdu_decoded->network_header, 7, mesh_transport_key_it.address->pseudo_dst);
388         }
389 
390         // pass to upper layer
391         if (mesh_access_message_handler){
392             mesh_pdu_t * pdu = (mesh_pdu_t*) incoming_transport_pdu_decoded;
393             incoming_network_pdu_decoded = NULL;
394             mesh_access_message_handler(pdu);
395         } else {
396             printf("[!] Unhandled Segmented Access/Control message\n");
397             // done
398             mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
399         }
400 
401         printf("\n");
402 
403     } else {
404         uint8_t akf = incoming_transport_pdu_decoded->akf_aid_control & 0x40;
405         if (akf){
406             printf("TransMIC does not match, try next key\n");
407             mesh_upper_transport_validate_segmented_message();
408         } else {
409             printf("TransMIC does not match device key, done\n");
410             // done
411             mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
412         }
413     }
414 }
415 
416 static void mesh_upper_transport_validate_segmented_message_digest(void * arg){
417     UNUSED(arg);
418     uint8_t   upper_transport_pdu_len      = incoming_transport_pdu_raw->len - incoming_transport_pdu_raw->transmic_len;
419     uint8_t * upper_transport_pdu_data_in  = incoming_transport_pdu_raw->data;
420     uint8_t * upper_transport_pdu_data_out = incoming_transport_pdu_decoded->data;
421     btstack_crypto_ccm_decrypt_block(&ccm, upper_transport_pdu_len, upper_transport_pdu_data_in, upper_transport_pdu_data_out, &mesh_upper_transport_validate_segmented_message_ccm, NULL);
422 }
423 
424 static void mesh_upper_transport_validate_unsegmented_message_digest(void * arg){
425     UNUSED(arg);
426     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&incoming_unsegmented_pdu_raw->segments);
427     uint8_t   trans_mic_len = 4;
428     uint8_t   lower_transport_pdu_len      = network_pdu->len - 9;
429     uint8_t * upper_transport_pdu_data_in  = &network_pdu->data[10];
430     uint8_t * upper_transport_pdu_data_out = &incoming_network_pdu_decoded->data[10];
431     uint8_t   upper_transport_pdu_len      = lower_transport_pdu_len - 1 - trans_mic_len;
432     btstack_crypto_ccm_decrypt_block(&ccm, upper_transport_pdu_len, upper_transport_pdu_data_in, upper_transport_pdu_data_out, &mesh_upper_transport_validate_unsegmented_message_ccm, NULL);
433 }
434 
435 static void mesh_upper_transport_validate_unsegmented_message(void){
436 
437     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
438         printf("No valid transport key found\n");
439         mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
440         return;
441     }
442     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
443     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
444 
445     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&incoming_unsegmented_pdu_raw->segments);
446     if (message_key->akf){
447         transport_unsegmented_setup_application_nonce(application_nonce, network_pdu);
448     } else {
449         transport_unsegmented_setup_device_nonce(application_nonce, network_pdu);
450     }
451 
452     // store application / device key index
453     mesh_print_hex("AppOrDevKey", message_key->key, 16);
454     incoming_message_pdu_singleton.appkey_index = message_key->appkey_index;
455 
456     // unsegmented message have TransMIC of 32 bit
457     uint8_t trans_mic_len = 4;
458     printf("Unsegmented Access message with TransMIC len 4\n");
459 
460     uint8_t   lower_transport_pdu_len = network_pdu->len - 9;
461     uint8_t * upper_transport_pdu_data = &network_pdu->data[10];
462     uint8_t   upper_transport_pdu_len  = lower_transport_pdu_len - 1 - trans_mic_len;
463 
464     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
465 
466     // decrypt ccm
467     crypto_active = 1;
468     uint16_t aad_len  = 0;
469     if (mesh_network_address_virtual(mesh_network_dst(incoming_network_pdu_decoded))){
470         aad_len  = 16;
471     }
472     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, trans_mic_len);
473     if (aad_len){
474         btstack_crypto_ccm_digest(&ccm, (uint8_t*) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_unsegmented_message_digest, NULL);
475     } else {
476         mesh_upper_transport_validate_unsegmented_message_digest(incoming_network_pdu_decoded);
477     }
478 }
479 
480 static void mesh_upper_transport_validate_segmented_message(void){
481     uint8_t * upper_transport_pdu_data =  incoming_transport_pdu_decoded->data;
482     uint8_t   upper_transport_pdu_len  =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
483 
484     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
485         printf("No valid transport key found\n");
486         mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
487         return;
488     }
489     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
490     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
491 
492     if (message_key->akf){
493         transport_segmented_setup_application_nonce(application_nonce, incoming_transport_pdu_raw);
494     } else {
495         transport_segmented_setup_device_nonce(application_nonce, incoming_transport_pdu_raw);
496     }
497 
498     // store application / device key index
499     mesh_print_hex("AppOrDevKey", message_key->key, 16);
500     incoming_transport_pdu_decoded->appkey_index = message_key->appkey_index;
501 
502     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
503 
504     // decrypt ccm
505     crypto_active = 1;
506     uint16_t aad_len  = 0;
507     if (mesh_network_address_virtual(mesh_transport_dst(incoming_transport_pdu_decoded))){
508         aad_len  = 16;
509     }
510     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, incoming_transport_pdu_decoded->transmic_len);
511 
512     if (aad_len){
513         btstack_crypto_ccm_digest(&ccm, (uint8_t *) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_segmented_message_digest, NULL);
514     } else {
515         mesh_upper_transport_validate_segmented_message_digest(NULL);
516     }
517 }
518 
519 static void mesh_upper_transport_process_unsegmented_access_message(void){
520     // copy original pdu
521     mesh_network_pdu_t * raw_network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&incoming_unsegmented_pdu_raw->segments);
522     incoming_network_pdu_decoded->len = raw_network_pdu->len;
523     (void)memcpy(incoming_network_pdu_decoded->data,
524                  raw_network_pdu->data,
525                  incoming_network_pdu_decoded->len);
526 
527     //
528     uint8_t * lower_transport_pdu     = &raw_network_pdu->data[9];
529     uint8_t   lower_transport_pdu_len = raw_network_pdu->len - 9;
530 
531     mesh_print_hex("Lower Transport network pdu", &raw_network_pdu->data[9], lower_transport_pdu_len);
532 
533     uint8_t aid =  lower_transport_pdu[0] & 0x3f;
534     uint8_t akf = (lower_transport_pdu[0] & 0x40) >> 6;
535     printf("AKF: %u\n",   akf);
536     printf("AID: %02x\n", aid);
537 
538     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_network_dst(incoming_network_pdu_decoded),
539             incoming_network_pdu_decoded->netkey_index, akf, aid);
540     mesh_upper_transport_validate_unsegmented_message();
541 }
542 
543 static void mesh_upper_transport_process_message(void){
544     // copy original pdu
545     (void)memcpy(incoming_transport_pdu_decoded, incoming_transport_pdu_raw,
546                  sizeof(mesh_transport_pdu_t));
547 
548     //
549     uint8_t * upper_transport_pdu     =  incoming_transport_pdu_decoded->data;
550     uint8_t   upper_transport_pdu_len =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
551     mesh_print_hex("Upper Transport pdu", upper_transport_pdu, upper_transport_pdu_len);
552 
553     uint8_t aid =  incoming_transport_pdu_decoded->akf_aid_control & 0x3f;
554     uint8_t akf = (incoming_transport_pdu_decoded->akf_aid_control & 0x40) >> 6;
555 
556     printf("AKF: %u\n",   akf);
557     printf("AID: %02x\n", aid);
558 
559     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_transport_dst(incoming_transport_pdu_decoded),
560             incoming_transport_pdu_decoded->netkey_index, akf, aid);
561     mesh_upper_transport_validate_segmented_message();
562 }
563 
564 static void mesh_upper_transport_message_received(mesh_pdu_t * pdu){
565     btstack_linked_list_add_tail(&upper_transport_incoming, (btstack_linked_item_t*) pdu);
566     mesh_upper_transport_run();
567 }
568 
569 
570 
571 static void mesh_upper_transport_pdu_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
572     switch (callback_type){
573         case MESH_TRANSPORT_PDU_RECEIVED:
574             mesh_upper_transport_message_received(pdu);
575             break;
576         case MESH_TRANSPORT_PDU_SENT:
577             // notify upper layer (or just free pdu)
578             if (higher_layer_handler){
579                 higher_layer_handler(callback_type, status, pdu);
580             } else {
581                 mesh_upper_transport_pdu_free(pdu);
582             }
583             mesh_upper_transport_run();
584             break;
585         default:
586             break;
587     }
588 }
589 static void mesh_upper_transport_send_unsegmented_access_pdu_ccm(void * arg){
590     crypto_active = 0;
591 
592     mesh_message_pdu_t * message_pdu = (mesh_message_pdu_t *) arg;
593     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
594 
595     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(network_pdu) + 1;
596     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(network_pdu)  - 1;
597     mesh_print_hex("EncAccessPayload", upper_transport_pdu, upper_transport_pdu_len);
598     // store TransMIC
599     btstack_crypto_ccm_get_authentication_value(&ccm, &upper_transport_pdu[upper_transport_pdu_len]);
600     mesh_print_hex("TransMIC", &upper_transport_pdu[upper_transport_pdu_len], 4);
601     network_pdu->len        += 4;
602     upper_transport_pdu_len += 4;
603     mesh_print_hex("UpperTransportPDU", upper_transport_pdu, upper_transport_pdu_len);
604     // send network pdu
605     mesh_lower_transport_send_pdu((mesh_pdu_t*) message_pdu);
606 }
607 
608 static void mesh_upper_transport_send_segmented_access_pdu_ccm(void * arg){
609     crypto_active = 0;
610 
611     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
612     mesh_print_hex("EncAccessPayload", transport_pdu->data, transport_pdu->len);
613     // store TransMIC
614     btstack_crypto_ccm_get_authentication_value(&ccm, &transport_pdu->data[transport_pdu->len]);
615     mesh_print_hex("TransMIC", &transport_pdu->data[transport_pdu->len], transport_pdu->transmic_len);
616     transport_pdu->len += transport_pdu->transmic_len;
617     mesh_print_hex("UpperTransportPDU", transport_pdu->data, transport_pdu->len);
618     mesh_lower_transport_send_pdu((mesh_pdu_t*) transport_pdu);
619 }
620 
621 static uint8_t mesh_upper_transport_setup_unsegmented_control_pdu(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode,
622                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
623 
624     if (control_pdu_len > 11) return 1;
625 
626     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
627     if (!network_key) return 1;
628 
629     uint8_t transport_pdu_data[12];
630     transport_pdu_data[0] = opcode;
631     (void)memcpy(&transport_pdu_data[1], control_pdu_data, control_pdu_len);
632     uint16_t transport_pdu_len = control_pdu_len + 1;
633 
634     // setup network_pdu
635     mesh_network_setup_pdu(network_pdu, netkey_index, network_key->nid, 1, ttl, 0, src, dest, transport_pdu_data, transport_pdu_len);
636 
637     return 0;
638 }
639 
640 static uint8_t mesh_upper_transport_setup_segmented_control_pdu(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode,
641                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
642 
643     if (control_pdu_len > 256) return 1;
644 
645     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
646     if (!network_key) return 1;
647 
648     (void)memcpy(transport_pdu->data, control_pdu_data, control_pdu_len);
649     transport_pdu->len = control_pdu_len;
650     transport_pdu->netkey_index = netkey_index;
651     transport_pdu->akf_aid_control = opcode;
652     transport_pdu->transmic_len = 0;    // no TransMIC for control
653     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid);
654     mesh_transport_set_src(transport_pdu, src);
655     mesh_transport_set_dest(transport_pdu, dest);
656     mesh_transport_set_ctl_ttl(transport_pdu, 0x80 | ttl);
657 
658     return 0;
659 }
660 
661 uint8_t mesh_upper_transport_setup_control_pdu(mesh_pdu_t * pdu, uint16_t netkey_index,
662                                                uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode, const uint8_t * control_pdu_data, uint16_t control_pdu_len){
663     switch (pdu->pdu_type){
664         case MESH_PDU_TYPE_NETWORK:
665             return mesh_upper_transport_setup_unsegmented_control_pdu((mesh_network_pdu_t *) pdu, netkey_index, ttl, src, dest, opcode, control_pdu_data, control_pdu_len);
666         case MESH_PDU_TYPE_TRANSPORT:
667             return mesh_upper_transport_setup_segmented_control_pdu((mesh_transport_pdu_t *) pdu, netkey_index, ttl, src, dest, opcode, control_pdu_data, control_pdu_len);
668         case MESH_PDU_TYPE_MESSAGE:
669             btstack_assert(0);
670             break;
671         default:
672             return 1;
673     }
674 }
675 
676 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu_header(mesh_message_pdu_t * message_pdu, uint16_t netkey_index,
677         uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest){
678 
679     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
680 
681     // get app or device key
682     const mesh_transport_key_t * appkey;
683     appkey = mesh_transport_key_get(appkey_index);
684     if (appkey == NULL){
685         printf("appkey_index %x unknown\n", appkey_index);
686         return 1;
687     }
688     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
689 
690     // lookup network by netkey_index
691     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
692     if (!network_key) return 1;
693 
694     message_pdu->appkey_index = appkey_index;
695 
696     network_pdu->data[9] = akf_aid;
697     // setup network_pdu
698     mesh_network_setup_pdu_header(network_pdu, netkey_index, network_key->nid, 0, ttl, 0, src, dest);
699     return 0;
700 }
701 
702 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu(mesh_message_pdu_t * message_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
703                                                        const uint8_t * access_pdu_data, uint8_t access_pdu_len){
704 
705     int status = mesh_upper_transport_setup_unsegmented_access_pdu_header(message_pdu, netkey_index, appkey_index, ttl, src, dest);
706     if (status) return status;
707 
708     // store in transport pdu
709     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
710     (void)memcpy(&network_pdu->data[10], access_pdu_data, access_pdu_len);
711     network_pdu->len = 10 + access_pdu_len;
712     return 0;
713 }
714 
715 static uint8_t mesh_upper_transport_setup_segmented_access_pdu_header(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index,
716     uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
717 
718     // get app or device key
719     const mesh_transport_key_t *appkey;
720     appkey = mesh_transport_key_get(appkey_index);
721     if (appkey == NULL) {
722         printf("[!] Upper transport, setup segmented Access PDU - appkey_index %x unknown\n", appkey_index);
723         return 1;
724     }
725     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
726 
727     // lookup network by netkey_index
728     const mesh_network_key_t *network_key = mesh_network_key_list_get(netkey_index);
729     if (!network_key) return 1;
730     if (network_key == NULL) {
731         printf("[!] Upper transport, setup segmented Access PDU - netkey_index %x unknown\n", appkey_index);
732         return 1;
733     }
734 
735     const uint8_t trans_mic_len = szmic ? 8 : 4;
736 
737     // store in transport pdu
738     transport_pdu->transmic_len = trans_mic_len;
739     transport_pdu->netkey_index = netkey_index;
740     transport_pdu->appkey_index = appkey_index;
741     transport_pdu->akf_aid_control = akf_aid;
742     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid | ((mesh_get_iv_index_for_tx() & 1) << 7));
743     mesh_transport_set_src(transport_pdu, src);
744     mesh_transport_set_dest(transport_pdu, dest);
745     mesh_transport_set_ctl_ttl(transport_pdu, ttl);
746     return 0;
747 }
748 
749 
750 static uint8_t mesh_upper_transport_setup_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
751                           uint8_t szmic, const uint8_t * access_pdu_data, uint8_t access_pdu_len){
752     int status = mesh_upper_transport_setup_segmented_access_pdu_header(transport_pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
753     if (status) return status;
754 
755     // store in transport pdu
756     (void)memcpy(transport_pdu->data, access_pdu_data, access_pdu_len);
757     transport_pdu->len = access_pdu_len;
758     return 0;
759 }
760 uint8_t mesh_upper_transport_setup_access_pdu_header(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
761                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
762     switch (pdu->pdu_type){
763         case MESH_PDU_TYPE_NETWORK:
764             btstack_assert(0);
765         case MESH_PDU_TYPE_TRANSPORT:
766             return mesh_upper_transport_setup_segmented_access_pdu_header((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
767         case MESH_PDU_TYPE_MESSAGE:
768             return mesh_upper_transport_setup_unsegmented_access_pdu_header((mesh_message_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest);
769         default:
770             return 1;
771     }
772 }
773 
774 uint8_t mesh_upper_transport_setup_access_pdu(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
775                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic,
776                                               const uint8_t * access_pdu_data, uint8_t access_pdu_len){
777     switch (pdu->pdu_type){
778         case MESH_PDU_TYPE_NETWORK:
779             btstack_assert(0);
780             break;
781         case MESH_PDU_TYPE_MESSAGE:
782             return mesh_upper_transport_setup_unsegmented_access_pdu((mesh_message_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, access_pdu_data, access_pdu_len);
783         case MESH_PDU_TYPE_TRANSPORT:
784             return mesh_upper_transport_setup_segmented_access_pdu((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic, access_pdu_data, access_pdu_len);
785         default:
786             return 1;
787     }
788 }
789 
790 static void mesh_upper_transport_send_unsegmented_access_pdu_digest(void * arg){
791     mesh_message_pdu_t * message_pdu = (mesh_message_pdu_t *) arg;
792     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
793     uint8_t * access_pdu_data = mesh_network_pdu_data(network_pdu) + 1;
794     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
795     btstack_crypto_ccm_encrypt_block(&ccm, access_pdu_len, access_pdu_data, access_pdu_data, &mesh_upper_transport_send_unsegmented_access_pdu_ccm, message_pdu);
796 }
797 
798 static mesh_transport_key_t * mesh_upper_transport_get_outgoing_appkey(uint16_t netkey_index, uint16_t appkey_index){
799     // Device Key is fixed
800     if (appkey_index == MESH_DEVICE_KEY_INDEX) {
801         return mesh_transport_key_get(appkey_index);
802     }
803 
804     // Get key refresh state from subnet
805     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
806     if (subnet == NULL) return NULL;
807 
808     // identify old and new app keys for given appkey_index
809     mesh_transport_key_t * old_key = NULL;
810     mesh_transport_key_t * new_key = NULL;
811     mesh_transport_key_iterator_t it;
812     mesh_transport_key_iterator_init(&it, netkey_index);
813     while (mesh_transport_key_iterator_has_more(&it)){
814         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
815         if (transport_key->appkey_index != appkey_index) continue;
816         if (transport_key->old_key == 0) {
817             new_key = transport_key;
818         } else {
819             old_key = transport_key;
820         }
821     }
822 
823     // if no key is marked as old, just use the current one
824     if (old_key == NULL) return new_key;
825 
826     // use new key if it exists in phase two
827     if ((subnet->key_refresh == MESH_KEY_REFRESH_SECOND_PHASE) && (new_key != NULL)){
828         return new_key;
829     } else {
830         return old_key;
831     }
832 }
833 
834 static void mesh_upper_transport_send_unsegmented_access_pdu(mesh_message_pdu_t * message_pdu){
835 
836     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
837 
838     // if dst is virtual address, lookup label uuid and hash
839     uint16_t aad_len = 0;
840     mesh_virtual_address_t * virtual_address = NULL;
841     uint16_t dst = mesh_network_dst(network_pdu);
842     if (mesh_network_address_virtual(dst)){
843         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
844         if (!virtual_address){
845             printf("No virtual address register for pseudo dst %4x\n", dst);
846             btstack_memory_mesh_network_pdu_free(network_pdu);
847             return;
848         }
849         aad_len = 16;
850         big_endian_store_16(network_pdu->data, 7, virtual_address->hash);
851     }
852 
853     // reserve slot
854     mesh_lower_transport_reserve_slot();
855 
856     // Nonce for Access Payload based on Network Sequence number: needs to be fixed now and lower layers need to send packet in right order
857     uint32_t seq = mesh_sequence_number_next();
858     mesh_network_pdu_set_seq(network_pdu, seq);
859 
860     // Dump PDU
861     printf("[+] Upper transport, send unsegmented Access PDU - dest %04x, seq %06x\n", dst, mesh_network_seq(network_pdu));
862     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
863 
864     // setup nonce
865     uint16_t appkey_index = message_pdu->appkey_index;
866     if (appkey_index == MESH_DEVICE_KEY_INDEX){
867         transport_unsegmented_setup_device_nonce(application_nonce, network_pdu);
868     } else {
869         transport_unsegmented_setup_application_nonce(application_nonce, network_pdu);
870     }
871 
872     // get app or device key
873     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(network_pdu->netkey_index, appkey_index);
874     mesh_print_hex("AppOrDevKey", appkey->key, 16);
875 
876     // encrypt ccm
877     uint8_t   trans_mic_len = 4;
878     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
879     crypto_active = 1;
880 
881     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, trans_mic_len);
882     if (virtual_address){
883         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
884         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_unsegmented_access_pdu_digest, message_pdu);
885     } else {
886         mesh_upper_transport_send_unsegmented_access_pdu_digest(message_pdu);
887     }
888 }
889 
890 static void mesh_upper_transport_send_segmented_access_pdu_digest(void *arg){
891     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
892     uint16_t  access_pdu_len  = transport_pdu->len;
893     uint8_t * access_pdu_data = transport_pdu->data;
894     btstack_crypto_ccm_encrypt_block(&ccm, access_pdu_len,access_pdu_data, access_pdu_data, &mesh_upper_transport_send_segmented_access_pdu_ccm, transport_pdu);
895 }
896 
897 static void mesh_upper_transport_send_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu){
898 
899     // if dst is virtual address, lookup label uuid and hash
900     uint16_t aad_len = 0;
901     mesh_virtual_address_t * virtual_address = NULL;
902     uint16_t dst = mesh_transport_dst(transport_pdu);
903     if (mesh_network_address_virtual(dst)){
904         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
905         if (!virtual_address){
906             printf("No virtual address register for pseudo dst %4x\n", dst);
907             btstack_memory_mesh_transport_pdu_free(transport_pdu);
908             return;
909         }
910         // printf("Using hash %4x with LabelUUID: ", virtual_address->hash);
911         // printf_hexdump(virtual_address->label_uuid, 16);
912         aad_len = 16;
913         big_endian_store_16(transport_pdu->network_header, 7, virtual_address->hash);
914     }
915 
916     // get app or device key
917     uint16_t appkey_index = transport_pdu->appkey_index;
918     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(transport_pdu->netkey_index, appkey_index);
919     if (appkey == NULL){
920         printf("AppKey %04x not found, drop message\n", appkey_index);
921         btstack_memory_mesh_transport_pdu_free(transport_pdu);
922         return;
923     }
924 
925     // reserve slot
926     mesh_lower_transport_reserve_slot();
927 
928     // reserve one sequence number, which is also used to encrypt access payload
929     uint32_t seq = mesh_sequence_number_next();
930     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
931     mesh_transport_set_seq(transport_pdu, seq);
932 
933     // Dump PDU
934     printf("[+] Upper transport, send segmented Access PDU - dest %04x, seq %06x\n", dst, mesh_transport_seq(transport_pdu));
935     mesh_print_hex("Access Payload", transport_pdu->data, transport_pdu->len);
936 
937     // setup nonce - uses dst, so after pseudo address translation
938     if (appkey_index == MESH_DEVICE_KEY_INDEX){
939         transport_segmented_setup_device_nonce(application_nonce, transport_pdu);
940     } else {
941         transport_segmented_setup_application_nonce(application_nonce, transport_pdu);
942     }
943 
944     // Dump key
945     mesh_print_hex("AppOrDevKey", appkey->key, 16);
946 
947     // encrypt ccm
948     uint8_t   transmic_len    = transport_pdu->transmic_len;
949     uint16_t  access_pdu_len  = transport_pdu->len;
950     crypto_active = 1;
951     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, transmic_len);
952     if (virtual_address){
953         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
954         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_segmented_access_pdu_digest, transport_pdu);
955     } else {
956         mesh_upper_transport_send_segmented_access_pdu_digest(transport_pdu);
957     }
958 }
959 
960 static void mesh_upper_transport_send_unsegmented_control_pdu(mesh_network_pdu_t * network_pdu){
961     // reserve slot
962     mesh_lower_transport_reserve_slot();
963     // reserve sequence number
964     uint32_t seq = mesh_sequence_number_next();
965     mesh_network_pdu_set_seq(network_pdu, seq);
966     // Dump PDU
967     uint8_t opcode = network_pdu->data[9];
968     printf("[+] Upper transport, send unsegmented Control PDU %p - seq %06x opcode %02x\n", network_pdu, seq, opcode);
969     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
970     // send
971     mesh_lower_transport_send_pdu((mesh_pdu_t *) network_pdu);
972 }
973 
974 static void mesh_upper_transport_send_segmented_control_pdu(mesh_transport_pdu_t * transport_pdu){
975     // reserve slot
976     mesh_lower_transport_reserve_slot();
977     // reserve sequence number
978     uint32_t seq = mesh_sequence_number_next();
979     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
980     mesh_transport_set_seq(transport_pdu, seq);
981     // Dump PDU
982     uint8_t opcode = transport_pdu->data[0];
983     printf("[+] Upper transport, send segmented Control PDU %p - seq %06x opcode %02x\n", transport_pdu, seq, opcode);
984     mesh_print_hex("Access Payload", &transport_pdu->data[1], transport_pdu->len - 1);
985     // send
986     mesh_lower_transport_send_pdu((mesh_pdu_t *) transport_pdu);
987 }
988 
989 static void mesh_upper_transport_run(void){
990 
991     while(!btstack_linked_list_empty(&upper_transport_incoming)){
992 
993         if (crypto_active) return;
994 
995         // peek at next message
996         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_incoming);
997         mesh_network_pdu_t   * network_pdu;
998         mesh_transport_pdu_t * transport_pdu;
999         mesh_message_pdu_t   * message_pdu;
1000         mesh_unsegmented_incoming_pdu_t * unsegmented_pdu;
1001         switch (pdu->pdu_type){
1002             case MESH_PDU_TYPE_NETWORK:
1003                 network_pdu = (mesh_network_pdu_t *) pdu;
1004                 // control?
1005                 if (mesh_network_control(network_pdu)) {
1006                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1007                     mesh_upper_unsegmented_control_message_received(network_pdu);
1008                 } else {
1009                     btstack_assert(0);
1010                     break;
1011                 }
1012                 break;
1013             case MESH_PDU_TYPE_UNSEGMENTED_INCOMING:
1014                 unsegmented_pdu = (mesh_unsegmented_incoming_pdu_t *) pdu;
1015                 network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&unsegmented_pdu->segments);
1016                 btstack_assert(network_pdu != NULL);
1017                 // control?
1018                 if (mesh_network_control(network_pdu)) {
1019                     // TODO: handle unsegmented control message
1020                     btstack_assert(0);
1021                     break;
1022                 } else {
1023                     incoming_network_pdu_decoded = mesh_network_pdu_get();
1024                     if (!incoming_network_pdu_decoded) return;
1025 
1026                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1027                     incoming_unsegmented_pdu_raw = unsegmented_pdu;
1028 
1029                     // use pre-allocated message pdu
1030                     incoming_message_pdu_singleton.pdu_header.pdu_type = MESH_PDU_TYPE_MESSAGE;
1031                     btstack_linked_list_add(&incoming_message_pdu_singleton.segments, (btstack_linked_item_t *) incoming_network_pdu_decoded);
1032                     mesh_upper_transport_process_unsegmented_access_message();
1033                 }
1034                 break;
1035             case MESH_PDU_TYPE_MESSAGE:
1036                 message_pdu = (mesh_message_pdu_t *) pdu;
1037                 uint8_t ctl = mesh_message_ctl(message_pdu);
1038                 if (ctl){
1039                     printf("Ignoring Segmented Control Message\n");
1040                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1041                     mesh_lower_transport_message_processed_by_higher_layer(pdu);
1042                 } else {
1043                     incoming_transport_pdu_decoded = mesh_transport_pdu_get();
1044                     if (!incoming_transport_pdu_decoded) return;
1045 
1046                     // use pre-allocated transport buffer
1047                     transport_pdu = &incoming_transport_pdu_singleton;
1048                     incoming_transport_pdu_singleton.pdu_header.pdu_type = MESH_PDU_TYPE_TRANSPORT;
1049 
1050                     // flatten segmented message into mesh_transport_pdu_t
1051 
1052                     // assemble payload
1053                     while (message_pdu->segments){
1054                         mesh_network_pdu_t * segment  = (mesh_network_pdu_t *) btstack_linked_list_pop(&message_pdu->segments);
1055                         // get segment n
1056                         uint8_t * lower_transport_pdu = mesh_network_pdu_data(segment);
1057                         uint8_t   seg_o               =  ( big_endian_read_16(lower_transport_pdu, 2) >> 5) & 0x001f;
1058                         uint8_t * segment_data = &lower_transport_pdu[4];
1059                         (void)memcpy(&transport_pdu->data[seg_o * 12], segment_data, 12);
1060                     }
1061 
1062                     // copy meta data
1063                     transport_pdu->len =  message_pdu->len;
1064                     transport_pdu->netkey_index =  message_pdu->netkey_index;
1065                     transport_pdu->transmic_len =  message_pdu->transmic_len;
1066                     transport_pdu->akf_aid_control =  message_pdu->akf_aid_control;
1067                     transport_pdu->flags =  message_pdu->flags;
1068                     transport_pdu->message_complete =  message_pdu->message_complete;
1069                     transport_pdu->seq_zero = message_pdu->seq_zero;
1070                     (void)memcpy(transport_pdu->network_header, message_pdu->network_header, 9);
1071 
1072                     mesh_print_hex("Assembled payload", transport_pdu->data, transport_pdu->len);
1073 
1074                     // free mesh message
1075                     mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *)message_pdu);
1076 
1077                     // get encoded transport pdu and start processing
1078                     incoming_transport_pdu_raw = transport_pdu;
1079                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1080                     mesh_upper_transport_process_message();
1081                 }
1082                 break;
1083             default:
1084                 break;
1085         }
1086     }
1087 
1088     while (!btstack_linked_list_empty(&upper_transport_outgoing)){
1089 
1090         if (crypto_active) break;
1091 
1092         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_outgoing);
1093         if (mesh_lower_transport_can_send_to_dest(mesh_pdu_dst(pdu)) == 0) break;
1094 
1095         (void) btstack_linked_list_pop(&upper_transport_outgoing);
1096 
1097         if (mesh_pdu_ctl(pdu)){
1098             switch (pdu->pdu_type){
1099                 case MESH_PDU_TYPE_NETWORK:
1100                     mesh_upper_transport_send_unsegmented_control_pdu((mesh_network_pdu_t *) pdu);
1101                     break;
1102                 case MESH_PDU_TYPE_MESSAGE:
1103                     btstack_assert(0);
1104                     break;
1105                 case MESH_PDU_TYPE_TRANSPORT:
1106                     mesh_upper_transport_send_segmented_control_pdu((mesh_transport_pdu_t *) pdu);
1107                     break;
1108                 default:
1109                     break;
1110             }
1111         } else {
1112             switch (pdu->pdu_type){
1113                 case MESH_PDU_TYPE_NETWORK:
1114                     btstack_assert(0);
1115                     break;
1116                 case MESH_PDU_TYPE_MESSAGE:
1117                     mesh_upper_transport_send_unsegmented_access_pdu((mesh_message_pdu_t *) pdu);
1118                     break;
1119                 case MESH_PDU_TYPE_TRANSPORT:
1120                     mesh_upper_transport_send_segmented_access_pdu((mesh_transport_pdu_t *) pdu);
1121                     break;
1122                 default:
1123                     break;
1124             }
1125         }
1126     }
1127 }
1128 
1129 void mesh_upper_transport_pdu_free(mesh_pdu_t * pdu){
1130     mesh_network_pdu_t   * network_pdu;
1131     mesh_transport_pdu_t * transport_pdu;
1132     mesh_message_pdu_t   * message_pdu;
1133     switch (pdu->pdu_type) {
1134         case MESH_PDU_TYPE_NETWORK:
1135             network_pdu = (mesh_network_pdu_t *) pdu;
1136             mesh_network_pdu_free(network_pdu);
1137             break;
1138         case MESH_PDU_TYPE_TRANSPORT:
1139             transport_pdu = (mesh_transport_pdu_t *) pdu;
1140             mesh_transport_pdu_free(transport_pdu);
1141             break;
1142         case MESH_PDU_TYPE_MESSAGE:
1143             message_pdu = (mesh_message_pdu_t *) pdu;
1144             mesh_message_pdu_free(message_pdu);
1145         default:
1146             break;
1147     }
1148 }
1149 
1150 void mesh_upper_transport_message_processed_by_higher_layer(mesh_pdu_t * pdu){
1151     crypto_active = 0;
1152     switch (pdu->pdu_type){
1153         case MESH_PDU_TYPE_NETWORK:
1154             mesh_upper_transport_process_unsegmented_message_done((mesh_network_pdu_t *) pdu);
1155             break;
1156         case MESH_PDU_TYPE_TRANSPORT:
1157             mesh_upper_transport_process_segmented_message_done((mesh_transport_pdu_t *) pdu);
1158             break;
1159         case MESH_PDU_TYPE_MESSAGE:
1160             mesh_upper_transport_process_message_done((mesh_message_pdu_t *) pdu);
1161             break;
1162         default:
1163             break;
1164     }
1165 }
1166 
1167 void mesh_upper_transport_register_access_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1168     mesh_access_message_handler = callback;
1169 }
1170 
1171 void mesh_upper_transport_register_control_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1172     mesh_control_message_handler = callback;
1173 }
1174 
1175 void mesh_upper_transport_set_higher_layer_handler(void (*pdu_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu)){
1176     higher_layer_handler = pdu_handler;
1177 }
1178 
1179 void mesh_upper_transport_init(){
1180     mesh_lower_transport_set_higher_layer_handler(&mesh_upper_transport_pdu_handler);
1181 }
1182