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