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