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