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