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