xref: /btstack/src/mesh/mesh_upper_transport.c (revision bb588228dfe9304f77394ce1346265d38a29618b)
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_message_pdu_singleton.appkey_index = message_key->appkey_index;
450 
451     // unsegmented message have TransMIC of 32 bit
452     uint8_t trans_mic_len = 4;
453     printf("Unsegmented Access message with TransMIC len 4\n");
454 
455     uint8_t   lower_transport_pdu_len = incoming_network_pdu_raw->len - 9;
456     uint8_t * upper_transport_pdu_data = &incoming_network_pdu_raw->data[10];
457     uint8_t   upper_transport_pdu_len  = lower_transport_pdu_len - 1 - trans_mic_len;
458 
459     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
460 
461     // decrypt ccm
462     crypto_active = 1;
463     uint16_t aad_len  = 0;
464     if (mesh_network_address_virtual(mesh_network_dst(incoming_network_pdu_decoded))){
465         aad_len  = 16;
466     }
467     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, trans_mic_len);
468     if (aad_len){
469         btstack_crypto_ccm_digest(&ccm, (uint8_t*) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_unsegmented_message_digest, NULL);
470     } else {
471         mesh_upper_transport_validate_unsegmented_message_digest(incoming_network_pdu_decoded);
472     }
473 }
474 
475 static void mesh_upper_transport_validate_segmented_message(void){
476     uint8_t * upper_transport_pdu_data =  incoming_transport_pdu_decoded->data;
477     uint8_t   upper_transport_pdu_len  =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
478 
479     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
480         printf("No valid transport key found\n");
481         mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
482         return;
483     }
484     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
485     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
486 
487     if (message_key->akf){
488         transport_segmented_setup_application_nonce(application_nonce, incoming_transport_pdu_raw);
489     } else {
490         transport_segmented_setup_device_nonce(application_nonce, incoming_transport_pdu_raw);
491     }
492 
493     // store application / device key index
494     mesh_print_hex("AppOrDevKey", message_key->key, 16);
495     incoming_transport_pdu_decoded->appkey_index = message_key->appkey_index;
496 
497     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
498 
499     // decrypt ccm
500     crypto_active = 1;
501     uint16_t aad_len  = 0;
502     if (mesh_network_address_virtual(mesh_transport_dst(incoming_transport_pdu_decoded))){
503         aad_len  = 16;
504     }
505     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, incoming_transport_pdu_decoded->transmic_len);
506 
507     if (aad_len){
508         btstack_crypto_ccm_digest(&ccm, (uint8_t *) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_segmented_message_digest, NULL);
509     } else {
510         mesh_upper_transport_validate_segmented_message_digest(NULL);
511     }
512 }
513 
514 static void mesh_upper_transport_process_unsegmented_access_message(void){
515     // copy original pdu
516     incoming_network_pdu_decoded->len = incoming_network_pdu_raw->len;
517     (void)memcpy(incoming_network_pdu_decoded->data,
518                  incoming_network_pdu_raw->data,
519                  incoming_network_pdu_decoded->len);
520 
521     //
522     uint8_t * lower_transport_pdu     = &incoming_network_pdu_raw->data[9];
523     uint8_t   lower_transport_pdu_len = incoming_network_pdu_raw->len - 9;
524 
525     mesh_print_hex("Lower Transport network pdu", &incoming_network_pdu_raw->data[9], lower_transport_pdu_len);
526 
527     uint8_t aid =  lower_transport_pdu[0] & 0x3f;
528     uint8_t akf = (lower_transport_pdu[0] & 0x40) >> 6;
529     printf("AKF: %u\n",   akf);
530     printf("AID: %02x\n", aid);
531 
532     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_network_dst(incoming_network_pdu_decoded),
533             incoming_network_pdu_decoded->netkey_index, akf, aid);
534     mesh_upper_transport_validate_unsegmented_message();
535 }
536 
537 static void mesh_upper_transport_process_message(void){
538     // copy original pdu
539     (void)memcpy(incoming_transport_pdu_decoded, incoming_transport_pdu_raw,
540                  sizeof(mesh_transport_pdu_t));
541 
542     //
543     uint8_t * upper_transport_pdu     =  incoming_transport_pdu_decoded->data;
544     uint8_t   upper_transport_pdu_len =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
545     mesh_print_hex("Upper Transport pdu", upper_transport_pdu, upper_transport_pdu_len);
546 
547     uint8_t aid =  incoming_transport_pdu_decoded->akf_aid_control & 0x3f;
548     uint8_t akf = (incoming_transport_pdu_decoded->akf_aid_control & 0x40) >> 6;
549 
550     printf("AKF: %u\n",   akf);
551     printf("AID: %02x\n", aid);
552 
553     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_transport_dst(incoming_transport_pdu_decoded),
554             incoming_transport_pdu_decoded->netkey_index, akf, aid);
555     mesh_upper_transport_validate_segmented_message();
556 }
557 
558 static void mesh_upper_transport_message_received(mesh_pdu_t * pdu){
559     btstack_linked_list_add_tail(&upper_transport_incoming, (btstack_linked_item_t*) pdu);
560     mesh_upper_transport_run();
561 }
562 
563 void mesh_upper_transport_pdu_free(mesh_pdu_t * pdu){
564     mesh_network_pdu_t   * network_pdu;
565     mesh_transport_pdu_t * transport_pdu;
566     mesh_message_pdu_t   * message_pdu;
567     switch (pdu->pdu_type) {
568         case MESH_PDU_TYPE_NETWORK:
569             network_pdu = (mesh_network_pdu_t *) pdu;
570             mesh_network_pdu_free(network_pdu);
571             break;
572         case MESH_PDU_TYPE_TRANSPORT:
573             transport_pdu = (mesh_transport_pdu_t *) pdu;
574             mesh_transport_pdu_free(transport_pdu);
575             break;
576         case MESH_PDU_TYPE_MESSAGE:
577             message_pdu = (mesh_message_pdu_t *) pdu;
578             mesh_message_pdu_free(message_pdu);
579         default:
580             break;
581     }
582 }
583 
584 static void mesh_upper_transport_pdu_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
585     switch (callback_type){
586         case MESH_TRANSPORT_PDU_RECEIVED:
587             mesh_upper_transport_message_received(pdu);
588             break;
589         case MESH_TRANSPORT_PDU_SENT:
590             // notify upper layer (or just free pdu)
591             if (higher_layer_handler){
592                 higher_layer_handler(callback_type, status, pdu);
593             } else {
594                 mesh_upper_transport_pdu_free(pdu);
595             }
596             mesh_upper_transport_run();
597             break;
598         default:
599             break;
600     }
601 }
602 static void mesh_upper_transport_send_unsegmented_access_pdu_ccm(void * arg){
603     crypto_active = 0;
604 
605     mesh_message_pdu_t * message_pdu = (mesh_message_pdu_t *) arg;
606     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
607 
608     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(network_pdu) + 1;
609     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(network_pdu)  - 1;
610     mesh_print_hex("EncAccessPayload", upper_transport_pdu, upper_transport_pdu_len);
611     // store TransMIC
612     btstack_crypto_ccm_get_authentication_value(&ccm, &upper_transport_pdu[upper_transport_pdu_len]);
613     mesh_print_hex("TransMIC", &upper_transport_pdu[upper_transport_pdu_len], 4);
614     network_pdu->len        += 4;
615     upper_transport_pdu_len += 4;
616     mesh_print_hex("UpperTransportPDU", upper_transport_pdu, upper_transport_pdu_len);
617     // send network pdu
618     mesh_lower_transport_send_pdu((mesh_pdu_t*) message_pdu);
619 }
620 
621 static void mesh_upper_transport_send_segmented_access_pdu_ccm(void * arg){
622     crypto_active = 0;
623 
624     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
625     mesh_print_hex("EncAccessPayload", transport_pdu->data, transport_pdu->len);
626     // store TransMIC
627     btstack_crypto_ccm_get_authentication_value(&ccm, &transport_pdu->data[transport_pdu->len]);
628     mesh_print_hex("TransMIC", &transport_pdu->data[transport_pdu->len], transport_pdu->transmic_len);
629     transport_pdu->len += transport_pdu->transmic_len;
630     mesh_print_hex("UpperTransportPDU", transport_pdu->data, transport_pdu->len);
631     mesh_lower_transport_send_pdu((mesh_pdu_t*) transport_pdu);
632 }
633 
634 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,
635                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
636 
637     if (control_pdu_len > 11) return 1;
638 
639     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
640     if (!network_key) return 1;
641 
642     uint8_t transport_pdu_data[12];
643     transport_pdu_data[0] = opcode;
644     (void)memcpy(&transport_pdu_data[1], control_pdu_data, control_pdu_len);
645     uint16_t transport_pdu_len = control_pdu_len + 1;
646 
647     // setup network_pdu
648     mesh_network_setup_pdu(network_pdu, netkey_index, network_key->nid, 1, ttl, 0, src, dest, transport_pdu_data, transport_pdu_len);
649 
650     return 0;
651 }
652 
653 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,
654                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
655 
656     if (control_pdu_len > 256) return 1;
657 
658     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
659     if (!network_key) return 1;
660 
661     (void)memcpy(transport_pdu->data, control_pdu_data, control_pdu_len);
662     transport_pdu->len = control_pdu_len;
663     transport_pdu->netkey_index = netkey_index;
664     transport_pdu->akf_aid_control = opcode;
665     transport_pdu->transmic_len = 0;    // no TransMIC for control
666     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid);
667     mesh_transport_set_src(transport_pdu, src);
668     mesh_transport_set_dest(transport_pdu, dest);
669     mesh_transport_set_ctl_ttl(transport_pdu, 0x80 | ttl);
670 
671     return 0;
672 }
673 
674 uint8_t mesh_upper_transport_setup_control_pdu(mesh_pdu_t * pdu, uint16_t netkey_index,
675                                                uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode, const uint8_t * control_pdu_data, uint16_t control_pdu_len){
676     switch (pdu->pdu_type){
677         case MESH_PDU_TYPE_NETWORK:
678             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);
679         case MESH_PDU_TYPE_TRANSPORT:
680             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);
681         case MESH_PDU_TYPE_MESSAGE:
682             btstack_assert(0);
683             break;
684         default:
685             return 1;
686     }
687 }
688 
689 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu_header(mesh_message_pdu_t * message_pdu, uint16_t netkey_index,
690         uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest){
691 
692     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
693 
694     // get app or device key
695     const mesh_transport_key_t * appkey;
696     appkey = mesh_transport_key_get(appkey_index);
697     if (appkey == NULL){
698         printf("appkey_index %x unknown\n", appkey_index);
699         return 1;
700     }
701     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
702 
703     // lookup network by netkey_index
704     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
705     if (!network_key) return 1;
706 
707     message_pdu->appkey_index = appkey_index;
708 
709     network_pdu->data[9] = akf_aid;
710     // setup network_pdu
711     mesh_network_setup_pdu_header(network_pdu, netkey_index, network_key->nid, 0, ttl, 0, src, dest);
712     return 0;
713 }
714 
715 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,
716                                                        const uint8_t * access_pdu_data, uint8_t access_pdu_len){
717 
718     int status = mesh_upper_transport_setup_unsegmented_access_pdu_header(message_pdu, netkey_index, appkey_index, ttl, src, dest);
719     if (status) return status;
720 
721     // store in transport pdu
722     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
723     (void)memcpy(&network_pdu->data[10], access_pdu_data, access_pdu_len);
724     network_pdu->len = 10 + access_pdu_len;
725     return 0;
726 }
727 
728 static uint8_t mesh_upper_transport_setup_segmented_access_pdu_header(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index,
729     uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
730 
731     // get app or device key
732     const mesh_transport_key_t *appkey;
733     appkey = mesh_transport_key_get(appkey_index);
734     if (appkey == NULL) {
735         printf("[!] Upper transport, setup segmented Access PDU - appkey_index %x unknown\n", appkey_index);
736         return 1;
737     }
738     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
739 
740     // lookup network by netkey_index
741     const mesh_network_key_t *network_key = mesh_network_key_list_get(netkey_index);
742     if (!network_key) return 1;
743     if (network_key == NULL) {
744         printf("[!] Upper transport, setup segmented Access PDU - netkey_index %x unknown\n", appkey_index);
745         return 1;
746     }
747 
748     const uint8_t trans_mic_len = szmic ? 8 : 4;
749 
750     // store in transport pdu
751     transport_pdu->transmic_len = trans_mic_len;
752     transport_pdu->netkey_index = netkey_index;
753     transport_pdu->appkey_index = appkey_index;
754     transport_pdu->akf_aid_control = akf_aid;
755     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid | ((mesh_get_iv_index_for_tx() & 1) << 7));
756     mesh_transport_set_src(transport_pdu, src);
757     mesh_transport_set_dest(transport_pdu, dest);
758     mesh_transport_set_ctl_ttl(transport_pdu, ttl);
759     return 0;
760 }
761 
762 
763 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,
764                           uint8_t szmic, const uint8_t * access_pdu_data, uint8_t access_pdu_len){
765     int status = mesh_upper_transport_setup_segmented_access_pdu_header(transport_pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
766     if (status) return status;
767 
768     // store in transport pdu
769     (void)memcpy(transport_pdu->data, access_pdu_data, access_pdu_len);
770     transport_pdu->len = access_pdu_len;
771     return 0;
772 }
773 uint8_t mesh_upper_transport_setup_access_pdu_header(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
774                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
775     switch (pdu->pdu_type){
776         case MESH_PDU_TYPE_NETWORK:
777             btstack_assert(0);
778         case MESH_PDU_TYPE_TRANSPORT:
779             return mesh_upper_transport_setup_segmented_access_pdu_header((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
780         case MESH_PDU_TYPE_MESSAGE:
781             return mesh_upper_transport_setup_unsegmented_access_pdu_header((mesh_message_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest);
782         default:
783             return 1;
784     }
785 }
786 
787 uint8_t mesh_upper_transport_setup_access_pdu(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
788                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic,
789                                               const uint8_t * access_pdu_data, uint8_t access_pdu_len){
790     switch (pdu->pdu_type){
791         case MESH_PDU_TYPE_NETWORK:
792             btstack_assert(0);
793             break;
794         case MESH_PDU_TYPE_MESSAGE:
795             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);
796         case MESH_PDU_TYPE_TRANSPORT:
797             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);
798         default:
799             return 1;
800     }
801 }
802 
803 static void mesh_upper_transport_send_unsegmented_access_pdu_digest(void * arg){
804     mesh_message_pdu_t * message_pdu = (mesh_message_pdu_t *) arg;
805     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
806     uint8_t * access_pdu_data = mesh_network_pdu_data(network_pdu) + 1;
807     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
808     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);
809 }
810 
811 static mesh_transport_key_t * mesh_upper_transport_get_outgoing_appkey(uint16_t netkey_index, uint16_t appkey_index){
812     // Device Key is fixed
813     if (appkey_index == MESH_DEVICE_KEY_INDEX) {
814         return mesh_transport_key_get(appkey_index);
815     }
816 
817     // Get key refresh state from subnet
818     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
819     if (subnet == NULL) return NULL;
820 
821     // identify old and new app keys for given appkey_index
822     mesh_transport_key_t * old_key = NULL;
823     mesh_transport_key_t * new_key = NULL;
824     mesh_transport_key_iterator_t it;
825     mesh_transport_key_iterator_init(&it, netkey_index);
826     while (mesh_transport_key_iterator_has_more(&it)){
827         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
828         if (transport_key->appkey_index != appkey_index) continue;
829         if (transport_key->old_key == 0) {
830             new_key = transport_key;
831         } else {
832             old_key = transport_key;
833         }
834     }
835 
836     // if no key is marked as old, just use the current one
837     if (old_key == NULL) return new_key;
838 
839     // use new key if it exists in phase two
840     if ((subnet->key_refresh == MESH_KEY_REFRESH_SECOND_PHASE) && (new_key != NULL)){
841         return new_key;
842     } else {
843         return old_key;
844     }
845 }
846 
847 static void mesh_upper_transport_send_unsegmented_access_pdu(mesh_message_pdu_t * message_pdu){
848 
849     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
850 
851     // if dst is virtual address, lookup label uuid and hash
852     uint16_t aad_len = 0;
853     mesh_virtual_address_t * virtual_address = NULL;
854     uint16_t dst = mesh_network_dst(network_pdu);
855     if (mesh_network_address_virtual(dst)){
856         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
857         if (!virtual_address){
858             printf("No virtual address register for pseudo dst %4x\n", dst);
859             btstack_memory_mesh_network_pdu_free(network_pdu);
860             return;
861         }
862         aad_len = 16;
863         big_endian_store_16(network_pdu->data, 7, virtual_address->hash);
864     }
865 
866     // reserve slot
867     mesh_lower_transport_reserve_slot();
868 
869     // Nonce for Access Payload based on Network Sequence number: needs to be fixed now and lower layers need to send packet in right order
870     uint32_t seq = mesh_sequence_number_next();
871     mesh_network_pdu_set_seq(network_pdu, seq);
872 
873     // Dump PDU
874     printf("[+] Upper transport, send unsegmented Access PDU - dest %04x, seq %06x\n", dst, mesh_network_seq(network_pdu));
875     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
876 
877     // setup nonce
878     uint16_t appkey_index = message_pdu->appkey_index;
879     if (appkey_index == MESH_DEVICE_KEY_INDEX){
880         transport_unsegmented_setup_device_nonce(application_nonce, network_pdu);
881     } else {
882         transport_unsegmented_setup_application_nonce(application_nonce, network_pdu);
883     }
884 
885     // get app or device key
886     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(network_pdu->netkey_index, appkey_index);
887     mesh_print_hex("AppOrDevKey", appkey->key, 16);
888 
889     // encrypt ccm
890     uint8_t   trans_mic_len = 4;
891     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
892     crypto_active = 1;
893 
894     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, trans_mic_len);
895     if (virtual_address){
896         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
897         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_unsegmented_access_pdu_digest, message_pdu);
898     } else {
899         mesh_upper_transport_send_unsegmented_access_pdu_digest(message_pdu);
900     }
901 }
902 
903 static void mesh_upper_transport_send_segmented_access_pdu_digest(void *arg){
904     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
905     uint16_t  access_pdu_len  = transport_pdu->len;
906     uint8_t * access_pdu_data = transport_pdu->data;
907     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);
908 }
909 
910 static void mesh_upper_transport_send_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu){
911 
912     // if dst is virtual address, lookup label uuid and hash
913     uint16_t aad_len = 0;
914     mesh_virtual_address_t * virtual_address = NULL;
915     uint16_t dst = mesh_transport_dst(transport_pdu);
916     if (mesh_network_address_virtual(dst)){
917         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
918         if (!virtual_address){
919             printf("No virtual address register for pseudo dst %4x\n", dst);
920             btstack_memory_mesh_transport_pdu_free(transport_pdu);
921             return;
922         }
923         // printf("Using hash %4x with LabelUUID: ", virtual_address->hash);
924         // printf_hexdump(virtual_address->label_uuid, 16);
925         aad_len = 16;
926         big_endian_store_16(transport_pdu->network_header, 7, virtual_address->hash);
927     }
928 
929     // get app or device key
930     uint16_t appkey_index = transport_pdu->appkey_index;
931     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(transport_pdu->netkey_index, appkey_index);
932     if (appkey == NULL){
933         printf("AppKey %04x not found, drop message\n", appkey_index);
934         btstack_memory_mesh_transport_pdu_free(transport_pdu);
935         return;
936     }
937 
938     // reserve slot
939     mesh_lower_transport_reserve_slot();
940 
941     // reserve one sequence number, which is also used to encrypt access payload
942     uint32_t seq = mesh_sequence_number_next();
943     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
944     mesh_transport_set_seq(transport_pdu, seq);
945 
946     // Dump PDU
947     printf("[+] Upper transport, send segmented Access PDU - dest %04x, seq %06x\n", dst, mesh_transport_seq(transport_pdu));
948     mesh_print_hex("Access Payload", transport_pdu->data, transport_pdu->len);
949 
950     // setup nonce - uses dst, so after pseudo address translation
951     if (appkey_index == MESH_DEVICE_KEY_INDEX){
952         transport_segmented_setup_device_nonce(application_nonce, transport_pdu);
953     } else {
954         transport_segmented_setup_application_nonce(application_nonce, transport_pdu);
955     }
956 
957     // Dump key
958     mesh_print_hex("AppOrDevKey", appkey->key, 16);
959 
960     // encrypt ccm
961     uint8_t   transmic_len    = transport_pdu->transmic_len;
962     uint16_t  access_pdu_len  = transport_pdu->len;
963     crypto_active = 1;
964     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, transmic_len);
965     if (virtual_address){
966         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
967         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_segmented_access_pdu_digest, transport_pdu);
968     } else {
969         mesh_upper_transport_send_segmented_access_pdu_digest(transport_pdu);
970     }
971 }
972 
973 static void mesh_upper_transport_send_unsegmented_control_pdu(mesh_network_pdu_t * network_pdu){
974     // reserve slot
975     mesh_lower_transport_reserve_slot();
976     // reserve sequence number
977     uint32_t seq = mesh_sequence_number_next();
978     mesh_network_pdu_set_seq(network_pdu, seq);
979     // Dump PDU
980     uint8_t opcode = network_pdu->data[9];
981     printf("[+] Upper transport, send unsegmented Control PDU %p - seq %06x opcode %02x\n", network_pdu, seq, opcode);
982     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
983     // send
984     mesh_lower_transport_send_pdu((mesh_pdu_t *) network_pdu);
985 }
986 
987 static void mesh_upper_transport_send_segmented_control_pdu(mesh_transport_pdu_t * transport_pdu){
988     // reserve slot
989     mesh_lower_transport_reserve_slot();
990     // reserve sequence number
991     uint32_t seq = mesh_sequence_number_next();
992     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
993     mesh_transport_set_seq(transport_pdu, seq);
994     // Dump PDU
995     uint8_t opcode = transport_pdu->data[0];
996     printf("[+] Upper transport, send segmented Control PDU %p - seq %06x opcode %02x\n", transport_pdu, seq, opcode);
997     mesh_print_hex("Access Payload", &transport_pdu->data[1], transport_pdu->len - 1);
998     // send
999     mesh_lower_transport_send_pdu((mesh_pdu_t *) transport_pdu);
1000 }
1001 
1002 static void mesh_upper_transport_run(void){
1003 
1004     while(!btstack_linked_list_empty(&upper_transport_incoming)){
1005 
1006         if (crypto_active) return;
1007 
1008         // peek at next message
1009         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_incoming);
1010         mesh_network_pdu_t   * network_pdu;
1011         mesh_transport_pdu_t * transport_pdu;
1012         mesh_message_pdu_t   * message_pdu;
1013         switch (pdu->pdu_type){
1014             case MESH_PDU_TYPE_NETWORK:
1015                 network_pdu = (mesh_network_pdu_t *) pdu;
1016                 // control?
1017                 if (mesh_network_control(network_pdu)) {
1018                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1019                     mesh_upper_unsegmented_control_message_received(network_pdu);
1020                 } else {
1021                     incoming_network_pdu_decoded = mesh_network_pdu_get();
1022                     if (!incoming_network_pdu_decoded) return;
1023 
1024                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1025                     incoming_network_pdu_raw = network_pdu;
1026 
1027                     // use pre-allocated message pdu
1028                     incoming_message_pdu_singleton.pdu_header.pdu_type = MESH_PDU_TYPE_MESSAGE;
1029                     btstack_linked_list_add(&incoming_message_pdu_singleton.segments, (btstack_linked_item_t *) incoming_network_pdu_decoded);
1030                     mesh_upper_transport_process_unsegmented_access_message();
1031                 }
1032                 break;
1033             case MESH_PDU_TYPE_MESSAGE:
1034                 message_pdu = (mesh_message_pdu_t *) pdu;
1035                 uint8_t ctl = mesh_message_ctl(message_pdu);
1036                 if (ctl){
1037                     printf("Ignoring Segmented Control Message\n");
1038                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1039                     mesh_lower_transport_message_processed_by_higher_layer(pdu);
1040                 } else {
1041                     incoming_transport_pdu_decoded = mesh_transport_pdu_get();
1042                     if (!incoming_transport_pdu_decoded) return;
1043 
1044                     // use pre-allocated transport buffer
1045                     transport_pdu = &incoming_transport_pdu_singleton;
1046                     incoming_transport_pdu_singleton.pdu_header.pdu_type = MESH_PDU_TYPE_TRANSPORT;
1047 
1048                     // flatten segmented message into mesh_transport_pdu_t
1049 
1050                     // assemble payload
1051                     while (message_pdu->segments){
1052                         mesh_network_pdu_t * segment  = (mesh_network_pdu_t *) btstack_linked_list_pop(&message_pdu->segments);
1053                         // get segment n
1054                         uint8_t * lower_transport_pdu = mesh_network_pdu_data(segment);
1055                         uint8_t   seg_o               =  ( big_endian_read_16(lower_transport_pdu, 2) >> 5) & 0x001f;
1056                         uint8_t * segment_data = &lower_transport_pdu[4];
1057                         (void)memcpy(&transport_pdu->data[seg_o * 12], segment_data, 12);
1058                     }
1059 
1060                     // copy meta data
1061                     transport_pdu->len =  message_pdu->len;
1062                     transport_pdu->netkey_index =  message_pdu->netkey_index;
1063                     transport_pdu->transmic_len =  message_pdu->transmic_len;
1064                     transport_pdu->akf_aid_control =  message_pdu->akf_aid_control;
1065                     transport_pdu->flags =  message_pdu->flags;
1066                     transport_pdu->message_complete =  message_pdu->message_complete;
1067                     transport_pdu->seq_zero = message_pdu->seq_zero;
1068                     (void)memcpy(transport_pdu->network_header, message_pdu->network_header, 9);
1069 
1070                     mesh_print_hex("Assembled payload", transport_pdu->data, transport_pdu->len);
1071 
1072                     // free mesh message
1073                     mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *)message_pdu);
1074 
1075                     // get encoded transport pdu and start processing
1076                     incoming_transport_pdu_raw = transport_pdu;
1077                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1078                     mesh_upper_transport_process_message();
1079                 }
1080                 break;
1081             default:
1082                 break;
1083         }
1084     }
1085 
1086     while (!btstack_linked_list_empty(&upper_transport_outgoing)){
1087 
1088         if (crypto_active) break;
1089 
1090         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_outgoing);
1091         if (mesh_lower_transport_can_send_to_dest(mesh_pdu_dst(pdu)) == 0) break;
1092 
1093         (void) btstack_linked_list_pop(&upper_transport_outgoing);
1094 
1095         if (mesh_pdu_ctl(pdu)){
1096             switch (pdu->pdu_type){
1097                 case MESH_PDU_TYPE_NETWORK:
1098                     mesh_upper_transport_send_unsegmented_control_pdu((mesh_network_pdu_t *) pdu);
1099                     break;
1100                 case MESH_PDU_TYPE_MESSAGE:
1101                     btstack_assert(0);
1102                     break;
1103                 case MESH_PDU_TYPE_TRANSPORT:
1104                     mesh_upper_transport_send_segmented_control_pdu((mesh_transport_pdu_t *) pdu);
1105                     break;
1106                 default:
1107                     break;
1108             }
1109         } else {
1110             switch (pdu->pdu_type){
1111                 case MESH_PDU_TYPE_NETWORK:
1112                     btstack_assert(0);
1113                     break;
1114                 case MESH_PDU_TYPE_MESSAGE:
1115                     mesh_upper_transport_send_unsegmented_access_pdu((mesh_message_pdu_t *) pdu);
1116                     break;
1117                 case MESH_PDU_TYPE_TRANSPORT:
1118                     mesh_upper_transport_send_segmented_access_pdu((mesh_transport_pdu_t *) pdu);
1119                     break;
1120                 default:
1121                     break;
1122             }
1123         }
1124     }
1125 }
1126 
1127 void mesh_upper_transport_register_access_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1128     mesh_access_message_handler = callback;
1129 }
1130 
1131 void mesh_upper_transport_register_control_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1132     mesh_control_message_handler = callback;
1133 }
1134 
1135 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)){
1136     higher_layer_handler = pdu_handler;
1137 }
1138 
1139 void mesh_upper_transport_init(){
1140     mesh_lower_transport_set_higher_layer_handler(&mesh_upper_transport_pdu_handler);
1141 }
1142 
1143 // TODO: higher layer define used for assert
1144 #define MESH_ACCESS_OPCODE_NOT_SET 0xFFFFFFFEu
1145 
1146 void mesh_upper_transport_send_access_pdu(mesh_pdu_t *pdu){
1147     btstack_assert(pdu->pdu_type != MESH_PDU_TYPE_NETWORK);
1148 
1149     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
1150     mesh_upper_transport_run();
1151 }
1152 
1153 void mesh_upper_transport_send_control_pdu(mesh_pdu_t * pdu){
1154     if (pdu->pdu_type == MESH_PDU_TYPE_NETWORK){
1155         btstack_assert( ((mesh_network_pdu_t *) pdu)->len >= 9);
1156     }
1157 
1158     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
1159     mesh_upper_transport_run();
1160 }
1161