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