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