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