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