xref: /btstack/src/mesh/mesh_upper_transport.c (revision e41a4a086c5518ba043c9e3c94f32ed742660f22)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "mesh_upper_transport.c"
39 
40 #include "mesh/mesh_upper_transport.h"
41 
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 
46 #include "btstack_util.h"
47 #include "btstack_memory.h"
48 #include "btstack_debug.h"
49 
50 #include "mesh/beacon.h"
51 #include "mesh/mesh_iv_index_seq_number.h"
52 #include "mesh/mesh_keys.h"
53 #include "mesh/mesh_lower_transport.h"
54 #include "mesh/mesh_peer.h"
55 #include "mesh/mesh_virtual_addresses.h"
56 
57 // TODO: extract mesh_pdu functions into lower transport or network
58 #include "mesh/mesh_access.h"
59 
60 static void (*higher_layer_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu);
61 
62 static void mesh_print_hex(const char * name, const uint8_t * data, uint16_t len){
63     printf("%-20s ", name);
64     printf_hexdump(data, len);
65 }
66 // static void mesh_print_x(const char * name, uint32_t value){
67 //     printf("%20s: 0x%x", name, (int) value);
68 // }
69 
70 
71 // combined key x address iterator for upper transport decryption
72 
73 typedef struct {
74     // state
75     mesh_transport_key_iterator_t  key_it;
76     mesh_virtual_address_iterator_t address_it;
77     // elements
78     const mesh_transport_key_t *   key;
79     const mesh_virtual_address_t * address;
80     // address - might be virtual
81     uint16_t dst;
82     // key info
83 } mesh_transport_key_and_virtual_address_iterator_t;
84 
85 static void mesh_transport_key_and_virtual_address_iterator_init(mesh_transport_key_and_virtual_address_iterator_t *it,
86                                                                  uint16_t dst, uint16_t netkey_index, uint8_t akf,
87                                                                  uint8_t aid) {
88     printf("KEY_INIT: dst %04x, akf %x, aid %x\n", dst, akf, aid);
89     // config
90     it->dst   = dst;
91     // init elements
92     it->key     = NULL;
93     it->address = NULL;
94     // init element iterators
95     mesh_transport_key_aid_iterator_init(&it->key_it, netkey_index, akf, aid);
96     // init address iterator
97     if (mesh_network_address_virtual(it->dst)){
98         mesh_virtual_address_iterator_init(&it->address_it, dst);
99         // get first key
100         if (mesh_transport_key_aid_iterator_has_more(&it->key_it)) {
101             it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
102         }
103     }
104 }
105 
106 // cartesian product: keys x addressses
107 static int mesh_transport_key_and_virtual_address_iterator_has_more(mesh_transport_key_and_virtual_address_iterator_t * it){
108     if (mesh_network_address_virtual(it->dst)) {
109         // find next valid entry
110         while (true){
111             if (mesh_virtual_address_iterator_has_more(&it->address_it)) return 1;
112             if (!mesh_transport_key_aid_iterator_has_more(&it->key_it)) return 0;
113             // get next key
114             it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
115             mesh_virtual_address_iterator_init(&it->address_it, it->dst);
116         }
117     } else {
118         return mesh_transport_key_aid_iterator_has_more(&it->key_it);
119     }
120 }
121 
122 static void mesh_transport_key_and_virtual_address_iterator_next(mesh_transport_key_and_virtual_address_iterator_t * it){
123     if (mesh_network_address_virtual(it->dst)) {
124         it->address = mesh_virtual_address_iterator_get_next(&it->address_it);
125     } else {
126         it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
127     }
128 }
129 
130 // UPPER TRANSPORT
131 
132 // stub lower transport
133 
134 static void mesh_upper_transport_validate_unsegmented_message(void);
135 static void mesh_upper_transport_validate_segmented_message(void);
136 
137 static void mesh_upper_transport_run(void);
138 
139 static int crypto_active;
140 static mesh_network_pdu_t   * incoming_network_pdu_raw;
141 static mesh_network_pdu_t   * incoming_network_pdu_decoded;
142 static mesh_transport_pdu_t   incoming_transport_pdu_singleton;
143 static mesh_transport_pdu_t * incoming_transport_pdu_raw;
144 static mesh_transport_pdu_t * incoming_transport_pdu_decoded;
145 static uint8_t application_nonce[13];
146 static btstack_crypto_ccm_t ccm;
147 static mesh_transport_key_and_virtual_address_iterator_t mesh_transport_key_it;
148 
149 // upper transport callbacks - in access layer
150 static void (*mesh_access_message_handler)(mesh_pdu_t * pdu);
151 static void (*mesh_control_message_handler)(mesh_pdu_t * pdu);
152 
153 // incoming unsegmented (network) and segmented (transport) control and access messages
154 static btstack_linked_list_t upper_transport_incoming;
155 
156 // outgoing unsegmented (network) and segmented (uppert_transport_outgoing) control and access messages
157 static btstack_linked_list_t upper_transport_outgoing;
158 
159 static void mesh_upper_transport_dump_pdus(const char *name, btstack_linked_list_t *list){
160     printf("List: %s:\n", name);
161     btstack_linked_list_iterator_t it;
162     btstack_linked_list_iterator_init(&it, list);
163     while (btstack_linked_list_iterator_has_next(&it)){
164         mesh_pdu_t * pdu = (mesh_pdu_t*) btstack_linked_list_iterator_next(&it);
165         printf("- %p\n", pdu);
166         // printf_hexdump( mesh_pdu_data(pdu), mesh_pdu_len(pdu));
167     }
168 }
169 
170 static void mesh_upper_transport_reset_pdus(btstack_linked_list_t *list){
171     while (!btstack_linked_list_empty(list)){
172         mesh_upper_transport_pdu_free((mesh_pdu_t *) btstack_linked_list_pop(list));
173     }
174 }
175 
176 void mesh_upper_transport_dump(void){
177     printf("incoming_network_pdu_raw: %p\n", incoming_network_pdu_raw);
178     printf("incoming_network_pdu_decoded: %p\n", incoming_network_pdu_decoded);
179     mesh_upper_transport_dump_pdus("upper_transport_incoming", &upper_transport_incoming);
180 }
181 
182 void mesh_upper_transport_reset(void){
183     crypto_active = 0;
184     if (incoming_network_pdu_raw){
185         mesh_network_pdu_free(incoming_network_pdu_raw);
186         incoming_network_pdu_raw = NULL;
187     }
188     // if (incoming_network_pdu_decoded){
189     //     mesh_network_pdu_free(incoming_network_pdu_decoded);
190     //     incoming_network_pdu_decoded = NULL;
191     // }
192     mesh_upper_transport_reset_pdus(&upper_transport_incoming);
193 }
194 
195 static void mesh_upper_unsegmented_control_message_received(mesh_network_pdu_t * network_pdu){
196     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
197     uint8_t  opcode = lower_transport_pdu[0];
198     if (mesh_control_message_handler){
199         mesh_control_message_handler((mesh_pdu_t*) network_pdu);
200     } else {
201         printf("[!] Unhandled Control message with opcode %02x\n", opcode);
202         // done
203         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
204     }
205 }
206 
207 static void mesh_upper_transport_process_unsegmented_message_done(mesh_network_pdu_t *network_pdu){
208     crypto_active = 0;
209     if (mesh_network_control(network_pdu)) {
210         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
211     } else {
212         mesh_network_pdu_free(network_pdu);
213         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) incoming_network_pdu_raw);
214         incoming_network_pdu_raw = NULL;
215     }
216     mesh_upper_transport_run();
217 }
218 
219 static void mesh_upper_transport_process_segmented_message_done(mesh_transport_pdu_t *transport_pdu){
220     crypto_active = 0;
221     if (mesh_transport_ctl(transport_pdu)) {
222         btstack_assert(0);
223     } else {
224         mesh_transport_pdu_free(transport_pdu);
225         incoming_transport_pdu_raw = NULL;
226     }
227     mesh_upper_transport_run();
228 }
229 
230 static uint32_t iv_index_for_ivi_nid(uint8_t ivi_nid){
231     // get IV Index and IVI
232     uint32_t iv_index = mesh_get_iv_index();
233     int ivi = ivi_nid >> 7;
234 
235     // if least significant bit differs, use previous IV Index
236     if ((iv_index & 1 ) ^ ivi){
237         iv_index--;
238     }
239     return iv_index;
240 }
241 
242 static void transport_unsegmented_setup_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
243     nonce[1] = 0x00;    // SZMIC if a Segmented Access message or 0 for all other message formats
244     (void)memcpy(&nonce[2], &network_pdu->data[2], 7);
245     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(network_pdu->data[0]));
246 }
247 
248 static void transport_segmented_setup_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
249     nonce[1] = transport_pdu->transmic_len == 8 ? 0x80 : 0x00;
250     (void)memcpy(&nonce[2], &transport_pdu->network_header[2], 7);
251     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(transport_pdu->network_header[0]));
252 }
253 
254 static void transport_unsegmented_setup_application_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
255     nonce[0] = 0x01;
256     transport_unsegmented_setup_nonce(nonce, network_pdu);
257     mesh_print_hex("AppNonce", nonce, 13);
258 }
259 
260 static void transport_unsegmented_setup_device_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
261     nonce[0] = 0x02;
262     transport_unsegmented_setup_nonce(nonce, network_pdu);
263     mesh_print_hex("DeviceNonce", nonce, 13);
264 }
265 
266 static void transport_segmented_setup_application_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
267     nonce[0] = 0x01;
268     transport_segmented_setup_nonce(nonce, transport_pdu);
269     mesh_print_hex("AppNonce", nonce, 13);
270 }
271 
272 static void transport_segmented_setup_device_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
273     nonce[0] = 0x02;
274     transport_segmented_setup_nonce(nonce, transport_pdu);
275     mesh_print_hex("DeviceNonce", nonce, 13);
276 }
277 
278 static void mesh_upper_transport_validate_unsegmented_message_ccm(void * arg){
279     UNUSED(arg);
280 
281     uint8_t * lower_transport_pdu = mesh_network_pdu_data(incoming_network_pdu_decoded);
282     uint8_t trans_mic_len = 4;
283 
284     // store TransMIC
285     uint8_t trans_mic[8];
286     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
287     mesh_print_hex("TransMIC", trans_mic, trans_mic_len);
288 
289     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(incoming_network_pdu_decoded) + 1;
290     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(incoming_network_pdu_decoded)  - 1;
291 
292     mesh_print_hex("Decryted PDU", upper_transport_pdu, upper_transport_pdu_len - trans_mic_len);
293 
294     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len - trans_mic_len], trans_mic_len) == 0){
295         printf("TransMIC matches\n");
296 
297         // remove TransMIC from payload
298         incoming_network_pdu_decoded->len -= trans_mic_len;
299 
300         // if virtual address, update dst to pseudo_dst
301         if (mesh_network_address_virtual(mesh_network_dst(incoming_network_pdu_decoded))){
302             big_endian_store_16(incoming_network_pdu_decoded->data, 7, mesh_transport_key_it.address->pseudo_dst);
303         }
304 
305         // pass to upper layer
306         if (mesh_access_message_handler){
307             mesh_pdu_t * pdu = (mesh_pdu_t*) incoming_network_pdu_decoded;
308             incoming_network_pdu_decoded = NULL;
309             mesh_access_message_handler(pdu);
310         } else {
311             printf("[!] Unhandled Unsegmented Access message\n");
312             // done
313             mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
314         }
315 
316         printf("\n");
317     } else {
318         uint8_t afk = lower_transport_pdu[0] & 0x40;
319         if (afk){
320             printf("TransMIC does not match, try next key\n");
321             mesh_upper_transport_validate_unsegmented_message();
322         } else {
323             printf("TransMIC does not match device key, done\n");
324             // done
325             mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
326         }
327     }
328 }
329 
330 static void mesh_upper_transport_validate_segmented_message_ccm(void * arg){
331     UNUSED(arg);
332 
333     uint8_t * upper_transport_pdu     =  incoming_transport_pdu_decoded->data;
334     uint8_t   upper_transport_pdu_len =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
335 
336     mesh_print_hex("Decrypted PDU", upper_transport_pdu, upper_transport_pdu_len);
337 
338     // store TransMIC
339     uint8_t trans_mic[8];
340     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
341     mesh_print_hex("TransMIC", trans_mic, incoming_transport_pdu_decoded->transmic_len);
342 
343     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len], incoming_transport_pdu_decoded->transmic_len) == 0){
344         printf("TransMIC matches\n");
345 
346         // remove TransMIC from payload
347         incoming_transport_pdu_decoded->len -= incoming_transport_pdu_decoded->transmic_len;
348 
349         // if virtual address, update dst to pseudo_dst
350         if (mesh_network_address_virtual(mesh_transport_dst(incoming_transport_pdu_decoded))){
351             big_endian_store_16(incoming_transport_pdu_decoded->network_header, 7, mesh_transport_key_it.address->pseudo_dst);
352         }
353 
354         // pass to upper layer
355         if (mesh_access_message_handler){
356             mesh_pdu_t * pdu = (mesh_pdu_t*) incoming_transport_pdu_decoded;
357             incoming_network_pdu_decoded = NULL;
358             mesh_access_message_handler(pdu);
359         } else {
360             printf("[!] Unhandled Segmented Access/Control message\n");
361             // done
362             mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
363         }
364 
365         printf("\n");
366 
367     } else {
368         uint8_t akf = incoming_transport_pdu_decoded->akf_aid_control & 0x40;
369         if (akf){
370             printf("TransMIC does not match, try next key\n");
371             mesh_upper_transport_validate_segmented_message();
372         } else {
373             printf("TransMIC does not match device key, done\n");
374             // done
375             mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
376         }
377     }
378 }
379 
380 void mesh_upper_transport_message_processed_by_higher_layer(mesh_pdu_t * pdu){
381     crypto_active = 0;
382     switch (pdu->pdu_type){
383         case MESH_PDU_TYPE_NETWORK:
384             mesh_upper_transport_process_unsegmented_message_done((mesh_network_pdu_t *) pdu);
385             break;
386         case MESH_PDU_TYPE_TRANSPORT:
387             mesh_upper_transport_process_segmented_message_done((mesh_transport_pdu_t *) pdu);
388             break;
389         default:
390             break;
391     }
392 }
393 
394 static void mesh_upper_transport_validate_segmented_message_digest(void * arg){
395     UNUSED(arg);
396     uint8_t   upper_transport_pdu_len      = incoming_transport_pdu_raw->len - incoming_transport_pdu_raw->transmic_len;
397     uint8_t * upper_transport_pdu_data_in  = incoming_transport_pdu_raw->data;
398     uint8_t * upper_transport_pdu_data_out = incoming_transport_pdu_decoded->data;
399     btstack_crypto_ccm_decrypt_block(&ccm, upper_transport_pdu_len, upper_transport_pdu_data_in, upper_transport_pdu_data_out, &mesh_upper_transport_validate_segmented_message_ccm, NULL);
400 }
401 
402 static void mesh_upper_transport_validate_unsegmented_message_digest(void * arg){
403     UNUSED(arg);
404     uint8_t   trans_mic_len = 4;
405     uint8_t   lower_transport_pdu_len      = incoming_network_pdu_raw->len - 9;
406     uint8_t * upper_transport_pdu_data_in  = &incoming_network_pdu_raw->data[10];
407     uint8_t * upper_transport_pdu_data_out = &incoming_network_pdu_decoded->data[10];
408     uint8_t   upper_transport_pdu_len      = lower_transport_pdu_len - 1 - trans_mic_len;
409     btstack_crypto_ccm_decrypt_block(&ccm, upper_transport_pdu_len, upper_transport_pdu_data_in, upper_transport_pdu_data_out, &mesh_upper_transport_validate_unsegmented_message_ccm, NULL);
410 }
411 
412 static void mesh_upper_transport_validate_unsegmented_message(void){
413 
414     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
415         printf("No valid transport key found\n");
416         mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
417         return;
418     }
419     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
420     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
421 
422     if (message_key->akf){
423         transport_unsegmented_setup_application_nonce(application_nonce, incoming_network_pdu_raw);
424     } else {
425         transport_unsegmented_setup_device_nonce(application_nonce, incoming_network_pdu_raw);
426     }
427 
428     // store application / device key index
429     mesh_print_hex("AppOrDevKey", message_key->key, 16);
430     incoming_network_pdu_decoded->appkey_index = message_key->appkey_index;
431 
432     // unsegmented message have TransMIC of 32 bit
433     uint8_t trans_mic_len = 4;
434     printf("Unsegmented Access message with TransMIC len 4\n");
435 
436     uint8_t   lower_transport_pdu_len = incoming_network_pdu_raw->len - 9;
437     uint8_t * upper_transport_pdu_data = &incoming_network_pdu_raw->data[10];
438     uint8_t   upper_transport_pdu_len  = lower_transport_pdu_len - 1 - trans_mic_len;
439 
440     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
441 
442     // decrypt ccm
443     crypto_active = 1;
444     uint16_t aad_len  = 0;
445     if (mesh_network_address_virtual(mesh_network_dst(incoming_network_pdu_decoded))){
446         aad_len  = 16;
447     }
448     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, trans_mic_len);
449     if (aad_len){
450         btstack_crypto_ccm_digest(&ccm, (uint8_t*) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_unsegmented_message_digest, NULL);
451     } else {
452         mesh_upper_transport_validate_unsegmented_message_digest(incoming_network_pdu_decoded);
453     }
454 }
455 
456 static void mesh_upper_transport_validate_segmented_message(void){
457     uint8_t * upper_transport_pdu_data =  incoming_transport_pdu_decoded->data;
458     uint8_t   upper_transport_pdu_len  =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
459 
460     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
461         printf("No valid transport key found\n");
462         mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
463         return;
464     }
465     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
466     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
467 
468     if (message_key->akf){
469         transport_segmented_setup_application_nonce(application_nonce, incoming_transport_pdu_raw);
470     } else {
471         transport_segmented_setup_device_nonce(application_nonce, incoming_transport_pdu_raw);
472     }
473 
474     // store application / device key index
475     mesh_print_hex("AppOrDevKey", message_key->key, 16);
476     incoming_transport_pdu_decoded->appkey_index = message_key->appkey_index;
477 
478     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
479 
480     // decrypt ccm
481     crypto_active = 1;
482     uint16_t aad_len  = 0;
483     if (mesh_network_address_virtual(mesh_transport_dst(incoming_transport_pdu_decoded))){
484         aad_len  = 16;
485     }
486     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, incoming_transport_pdu_decoded->transmic_len);
487 
488     if (aad_len){
489         btstack_crypto_ccm_digest(&ccm, (uint8_t *) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_segmented_message_digest, NULL);
490     } else {
491         mesh_upper_transport_validate_segmented_message_digest(NULL);
492     }
493 }
494 
495 static void mesh_upper_transport_process_unsegmented_access_message(void){
496     // copy original pdu
497     incoming_network_pdu_decoded->len = incoming_network_pdu_raw->len;
498     (void)memcpy(incoming_network_pdu_decoded->data,
499                  incoming_network_pdu_raw->data,
500                  incoming_network_pdu_decoded->len);
501 
502     //
503     uint8_t * lower_transport_pdu     = &incoming_network_pdu_raw->data[9];
504     uint8_t   lower_transport_pdu_len = incoming_network_pdu_raw->len - 9;
505 
506     mesh_print_hex("Lower Transport network pdu", &incoming_network_pdu_raw->data[9], lower_transport_pdu_len);
507 
508     uint8_t aid =  lower_transport_pdu[0] & 0x3f;
509     uint8_t akf = (lower_transport_pdu[0] & 0x40) >> 6;
510     printf("AKF: %u\n",   akf);
511     printf("AID: %02x\n", aid);
512 
513     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_network_dst(incoming_network_pdu_decoded),
514             incoming_network_pdu_decoded->netkey_index, akf, aid);
515     mesh_upper_transport_validate_unsegmented_message();
516 }
517 
518 static void mesh_upper_transport_process_message(void){
519     // copy original pdu
520     (void)memcpy(incoming_transport_pdu_decoded, incoming_transport_pdu_raw,
521                  sizeof(mesh_transport_pdu_t));
522 
523     //
524     uint8_t * upper_transport_pdu     =  incoming_transport_pdu_decoded->data;
525     uint8_t   upper_transport_pdu_len =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
526     mesh_print_hex("Upper Transport pdu", upper_transport_pdu, upper_transport_pdu_len);
527 
528     uint8_t aid =  incoming_transport_pdu_decoded->akf_aid_control & 0x3f;
529     uint8_t akf = (incoming_transport_pdu_decoded->akf_aid_control & 0x40) >> 6;
530 
531     printf("AKF: %u\n",   akf);
532     printf("AID: %02x\n", aid);
533 
534     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_transport_dst(incoming_transport_pdu_decoded),
535             incoming_transport_pdu_decoded->netkey_index, akf, aid);
536     mesh_upper_transport_validate_segmented_message();
537 }
538 
539 static void mesh_upper_transport_message_received(mesh_pdu_t * pdu){
540     btstack_linked_list_add_tail(&upper_transport_incoming, (btstack_linked_item_t*) pdu);
541     mesh_upper_transport_run();
542 }
543 
544 void mesh_upper_transport_pdu_free(mesh_pdu_t * pdu){
545     mesh_network_pdu_t   * network_pdu;
546     mesh_transport_pdu_t * transport_pdu;
547     mesh_message_pdu_t   * message_pdu;
548     switch (pdu->pdu_type) {
549         case MESH_PDU_TYPE_NETWORK:
550             network_pdu = (mesh_network_pdu_t *) pdu;
551             mesh_network_pdu_free(network_pdu);
552             break;
553         case MESH_PDU_TYPE_TRANSPORT:
554             transport_pdu = (mesh_transport_pdu_t *) pdu;
555             mesh_transport_pdu_free(transport_pdu);
556             break;
557         case MESH_PDU_TYPE_MESSAGE:
558             message_pdu = (mesh_message_pdu_t *) pdu;
559             mesh_message_pdu_free(message_pdu);
560         default:
561             break;
562     }
563 }
564 
565 static void mesh_upper_transport_pdu_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
566     switch (callback_type){
567         case MESH_TRANSPORT_PDU_RECEIVED:
568             mesh_upper_transport_message_received(pdu);
569             break;
570         case MESH_TRANSPORT_PDU_SENT:
571             // notify upper layer (or just free pdu)
572             if (higher_layer_handler){
573                 higher_layer_handler(callback_type, status, pdu);
574             } else {
575                 mesh_upper_transport_pdu_free(pdu);
576             }
577             mesh_upper_transport_run();
578             break;
579         default:
580             break;
581     }
582 }
583 static void mesh_upper_transport_send_unsegmented_access_pdu_ccm(void * arg){
584     crypto_active = 0;
585 
586     mesh_message_pdu_t * message_pdu = (mesh_message_pdu_t *) arg;
587     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
588 
589     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(network_pdu) + 1;
590     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(network_pdu)  - 1;
591     mesh_print_hex("EncAccessPayload", upper_transport_pdu, upper_transport_pdu_len);
592     // store TransMIC
593     btstack_crypto_ccm_get_authentication_value(&ccm, &upper_transport_pdu[upper_transport_pdu_len]);
594     mesh_print_hex("TransMIC", &upper_transport_pdu[upper_transport_pdu_len], 4);
595     network_pdu->len        += 4;
596     upper_transport_pdu_len += 4;
597     mesh_print_hex("UpperTransportPDU", upper_transport_pdu, upper_transport_pdu_len);
598     // send network pdu
599     mesh_lower_transport_send_pdu((mesh_pdu_t*) message_pdu);
600 }
601 
602 static void mesh_upper_transport_send_segmented_access_pdu_ccm(void * arg){
603     crypto_active = 0;
604 
605     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
606     mesh_print_hex("EncAccessPayload", transport_pdu->data, transport_pdu->len);
607     // store TransMIC
608     btstack_crypto_ccm_get_authentication_value(&ccm, &transport_pdu->data[transport_pdu->len]);
609     mesh_print_hex("TransMIC", &transport_pdu->data[transport_pdu->len], transport_pdu->transmic_len);
610     transport_pdu->len += transport_pdu->transmic_len;
611     mesh_print_hex("UpperTransportPDU", transport_pdu->data, transport_pdu->len);
612     mesh_lower_transport_send_pdu((mesh_pdu_t*) transport_pdu);
613 }
614 
615 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,
616                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
617 
618     if (control_pdu_len > 11) return 1;
619 
620     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
621     if (!network_key) return 1;
622 
623     uint8_t transport_pdu_data[12];
624     transport_pdu_data[0] = opcode;
625     (void)memcpy(&transport_pdu_data[1], control_pdu_data, control_pdu_len);
626     uint16_t transport_pdu_len = control_pdu_len + 1;
627 
628     // setup network_pdu
629     mesh_network_setup_pdu(network_pdu, netkey_index, network_key->nid, 1, ttl, 0, src, dest, transport_pdu_data, transport_pdu_len);
630 
631     return 0;
632 }
633 
634 static uint8_t mesh_upper_transport_setup_segmented_control_pdu(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode,
635                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
636 
637     if (control_pdu_len > 256) return 1;
638 
639     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
640     if (!network_key) return 1;
641 
642     (void)memcpy(transport_pdu->data, control_pdu_data, control_pdu_len);
643     transport_pdu->len = control_pdu_len;
644     transport_pdu->netkey_index = netkey_index;
645     transport_pdu->akf_aid_control = opcode;
646     transport_pdu->transmic_len = 0;    // no TransMIC for control
647     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid);
648     mesh_transport_set_src(transport_pdu, src);
649     mesh_transport_set_dest(transport_pdu, dest);
650     mesh_transport_set_ctl_ttl(transport_pdu, 0x80 | ttl);
651 
652     return 0;
653 }
654 
655 uint8_t mesh_upper_transport_setup_control_pdu(mesh_pdu_t * pdu, uint16_t netkey_index,
656                                                uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode, const uint8_t * control_pdu_data, uint16_t control_pdu_len){
657     switch (pdu->pdu_type){
658         case MESH_PDU_TYPE_NETWORK:
659             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);
660         case MESH_PDU_TYPE_TRANSPORT:
661             return mesh_upper_transport_setup_segmented_control_pdu((mesh_transport_pdu_t *) pdu, netkey_index, ttl, src, dest, opcode, control_pdu_data, control_pdu_len);
662         case MESH_PDU_TYPE_MESSAGE:
663             btstack_assert(0);
664             break;
665         default:
666             return 1;
667     }
668 }
669 
670 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu_header(mesh_message_pdu_t * message_pdu, uint16_t netkey_index,
671         uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest){
672 
673     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
674 
675     // get app or device key
676     const mesh_transport_key_t * appkey;
677     appkey = mesh_transport_key_get(appkey_index);
678     if (appkey == NULL){
679         printf("appkey_index %x unknown\n", appkey_index);
680         return 1;
681     }
682     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
683 
684     // lookup network by netkey_index
685     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
686     if (!network_key) return 1;
687 
688     network_pdu->data[9] = akf_aid;
689     // setup network_pdu
690     mesh_network_setup_pdu_header(network_pdu, netkey_index, network_key->nid, 0, ttl, 0, src, dest);
691     network_pdu->appkey_index = appkey_index;
692     return 0;
693 }
694 
695 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu(mesh_message_pdu_t * message_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
696                                                        const uint8_t * access_pdu_data, uint8_t access_pdu_len){
697 
698     int status = mesh_upper_transport_setup_unsegmented_access_pdu_header(message_pdu, netkey_index, appkey_index, ttl, src, dest);
699     if (status) return status;
700 
701     // store in transport pdu
702     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
703     (void)memcpy(&network_pdu->data[10], access_pdu_data, access_pdu_len);
704     network_pdu->len = 10 + access_pdu_len;
705     return 0;
706 }
707 
708 static uint8_t mesh_upper_transport_setup_segmented_access_pdu_header(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index,
709     uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
710 
711     // get app or device key
712     const mesh_transport_key_t *appkey;
713     appkey = mesh_transport_key_get(appkey_index);
714     if (appkey == NULL) {
715         printf("[!] Upper transport, setup segmented Access PDU - appkey_index %x unknown\n", appkey_index);
716         return 1;
717     }
718     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
719 
720     // lookup network by netkey_index
721     const mesh_network_key_t *network_key = mesh_network_key_list_get(netkey_index);
722     if (!network_key) return 1;
723     if (network_key == NULL) {
724         printf("[!] Upper transport, setup segmented Access PDU - netkey_index %x unknown\n", appkey_index);
725         return 1;
726     }
727 
728     const uint8_t trans_mic_len = szmic ? 8 : 4;
729 
730     // store in transport pdu
731     transport_pdu->transmic_len = trans_mic_len;
732     transport_pdu->netkey_index = netkey_index;
733     transport_pdu->appkey_index = appkey_index;
734     transport_pdu->akf_aid_control = akf_aid;
735     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid | ((mesh_get_iv_index_for_tx() & 1) << 7));
736     mesh_transport_set_src(transport_pdu, src);
737     mesh_transport_set_dest(transport_pdu, dest);
738     mesh_transport_set_ctl_ttl(transport_pdu, ttl);
739     return 0;
740 }
741 
742 
743 static uint8_t mesh_upper_transport_setup_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
744                           uint8_t szmic, const uint8_t * access_pdu_data, uint8_t access_pdu_len){
745     int status = mesh_upper_transport_setup_segmented_access_pdu_header(transport_pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
746     if (status) return status;
747 
748     // store in transport pdu
749     (void)memcpy(transport_pdu->data, access_pdu_data, access_pdu_len);
750     transport_pdu->len = access_pdu_len;
751     return 0;
752 }
753 uint8_t mesh_upper_transport_setup_access_pdu_header(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
754                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
755     switch (pdu->pdu_type){
756         case MESH_PDU_TYPE_NETWORK:
757             btstack_assert(0);
758         case MESH_PDU_TYPE_TRANSPORT:
759             return mesh_upper_transport_setup_segmented_access_pdu_header((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
760         case MESH_PDU_TYPE_MESSAGE:
761             return mesh_upper_transport_setup_unsegmented_access_pdu_header((mesh_message_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest);
762         default:
763             return 1;
764     }
765 }
766 
767 uint8_t mesh_upper_transport_setup_access_pdu(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
768                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic,
769                                               const uint8_t * access_pdu_data, uint8_t access_pdu_len){
770     switch (pdu->pdu_type){
771         case MESH_PDU_TYPE_NETWORK:
772             btstack_assert(0);
773             break;
774         case MESH_PDU_TYPE_MESSAGE:
775             return mesh_upper_transport_setup_unsegmented_access_pdu((mesh_message_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, access_pdu_data, access_pdu_len);
776         case MESH_PDU_TYPE_TRANSPORT:
777             return mesh_upper_transport_setup_segmented_access_pdu((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic, access_pdu_data, access_pdu_len);
778         default:
779             return 1;
780     }
781 }
782 
783 static void mesh_upper_transport_send_unsegmented_access_pdu_digest(void * arg){
784     mesh_message_pdu_t * message_pdu = (mesh_message_pdu_t *) arg;
785     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
786     uint8_t * access_pdu_data = mesh_network_pdu_data(network_pdu) + 1;
787     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
788     btstack_crypto_ccm_encrypt_block(&ccm, access_pdu_len, access_pdu_data, access_pdu_data, &mesh_upper_transport_send_unsegmented_access_pdu_ccm, message_pdu);
789 }
790 
791 static mesh_transport_key_t * mesh_upper_transport_get_outgoing_appkey(uint16_t netkey_index, uint16_t appkey_index){
792     // Device Key is fixed
793     if (appkey_index == MESH_DEVICE_KEY_INDEX) {
794         return mesh_transport_key_get(appkey_index);
795     }
796 
797     // Get key refresh state from subnet
798     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
799     if (subnet == NULL) return NULL;
800 
801     // identify old and new app keys for given appkey_index
802     mesh_transport_key_t * old_key = NULL;
803     mesh_transport_key_t * new_key = NULL;
804     mesh_transport_key_iterator_t it;
805     mesh_transport_key_iterator_init(&it, netkey_index);
806     while (mesh_transport_key_iterator_has_more(&it)){
807         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
808         if (transport_key->appkey_index != appkey_index) continue;
809         if (transport_key->old_key == 0) {
810             new_key = transport_key;
811         } else {
812             old_key = transport_key;
813         }
814     }
815 
816     // if no key is marked as old, just use the current one
817     if (old_key == NULL) return new_key;
818 
819     // use new key if it exists in phase two
820     if ((subnet->key_refresh == MESH_KEY_REFRESH_SECOND_PHASE) && (new_key != NULL)){
821         return new_key;
822     } else {
823         return old_key;
824     }
825 }
826 
827 static void mesh_upper_transport_send_unsegmented_access_pdu(mesh_message_pdu_t * message_pdu){
828 
829     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&message_pdu->segments);
830 
831     // if dst is virtual address, lookup label uuid and hash
832     uint16_t aad_len = 0;
833     mesh_virtual_address_t * virtual_address = NULL;
834     uint16_t dst = mesh_network_dst(network_pdu);
835     if (mesh_network_address_virtual(dst)){
836         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
837         if (!virtual_address){
838             printf("No virtual address register for pseudo dst %4x\n", dst);
839             btstack_memory_mesh_network_pdu_free(network_pdu);
840             return;
841         }
842         aad_len = 16;
843         big_endian_store_16(network_pdu->data, 7, virtual_address->hash);
844     }
845 
846     // reserve slot
847     mesh_lower_transport_reserve_slot();
848 
849     // Nonce for Access Payload based on Network Sequence number: needs to be fixed now and lower layers need to send packet in right order
850     uint32_t seq = mesh_sequence_number_next();
851     mesh_network_pdu_set_seq(network_pdu, seq);
852 
853     // Dump PDU
854     printf("[+] Upper transport, send unsegmented Access PDU - dest %04x, seq %06x\n", dst, mesh_network_seq(network_pdu));
855     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
856 
857     // setup nonce
858     uint16_t appkey_index = network_pdu->appkey_index;
859     if (appkey_index == MESH_DEVICE_KEY_INDEX){
860         transport_unsegmented_setup_device_nonce(application_nonce, network_pdu);
861     } else {
862         transport_unsegmented_setup_application_nonce(application_nonce, network_pdu);
863     }
864 
865     // get app or device key
866     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(network_pdu->netkey_index, appkey_index);
867     mesh_print_hex("AppOrDevKey", appkey->key, 16);
868 
869     // encrypt ccm
870     uint8_t   trans_mic_len = 4;
871     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
872     crypto_active = 1;
873 
874     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, trans_mic_len);
875     if (virtual_address){
876         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
877         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_unsegmented_access_pdu_digest, message_pdu);
878     } else {
879         mesh_upper_transport_send_unsegmented_access_pdu_digest(message_pdu);
880     }
881 }
882 
883 static void mesh_upper_transport_send_segmented_access_pdu_digest(void *arg){
884     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
885     uint16_t  access_pdu_len  = transport_pdu->len;
886     uint8_t * access_pdu_data = transport_pdu->data;
887     btstack_crypto_ccm_encrypt_block(&ccm, access_pdu_len,access_pdu_data, access_pdu_data, &mesh_upper_transport_send_segmented_access_pdu_ccm, transport_pdu);
888 }
889 
890 static void mesh_upper_transport_send_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu){
891 
892     // if dst is virtual address, lookup label uuid and hash
893     uint16_t aad_len = 0;
894     mesh_virtual_address_t * virtual_address = NULL;
895     uint16_t dst = mesh_transport_dst(transport_pdu);
896     if (mesh_network_address_virtual(dst)){
897         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
898         if (!virtual_address){
899             printf("No virtual address register for pseudo dst %4x\n", dst);
900             btstack_memory_mesh_transport_pdu_free(transport_pdu);
901             return;
902         }
903         // printf("Using hash %4x with LabelUUID: ", virtual_address->hash);
904         // printf_hexdump(virtual_address->label_uuid, 16);
905         aad_len = 16;
906         big_endian_store_16(transport_pdu->network_header, 7, virtual_address->hash);
907     }
908 
909     // get app or device key
910     uint16_t appkey_index = transport_pdu->appkey_index;
911     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(transport_pdu->netkey_index, appkey_index);
912     if (appkey == NULL){
913         printf("AppKey %04x not found, drop message\n", appkey_index);
914         btstack_memory_mesh_transport_pdu_free(transport_pdu);
915         return;
916     }
917 
918     // reserve slot
919     mesh_lower_transport_reserve_slot();
920 
921     // reserve one sequence number, which is also used to encrypt access payload
922     uint32_t seq = mesh_sequence_number_next();
923     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
924     mesh_transport_set_seq(transport_pdu, seq);
925 
926     // Dump PDU
927     printf("[+] Upper transport, send segmented Access PDU - dest %04x, seq %06x\n", dst, mesh_transport_seq(transport_pdu));
928     mesh_print_hex("Access Payload", transport_pdu->data, transport_pdu->len);
929 
930     // setup nonce - uses dst, so after pseudo address translation
931     if (appkey_index == MESH_DEVICE_KEY_INDEX){
932         transport_segmented_setup_device_nonce(application_nonce, transport_pdu);
933     } else {
934         transport_segmented_setup_application_nonce(application_nonce, transport_pdu);
935     }
936 
937     // Dump key
938     mesh_print_hex("AppOrDevKey", appkey->key, 16);
939 
940     // encrypt ccm
941     uint8_t   transmic_len    = transport_pdu->transmic_len;
942     uint16_t  access_pdu_len  = transport_pdu->len;
943     crypto_active = 1;
944     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, transmic_len);
945     if (virtual_address){
946         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
947         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_segmented_access_pdu_digest, transport_pdu);
948     } else {
949         mesh_upper_transport_send_segmented_access_pdu_digest(transport_pdu);
950     }
951 }
952 
953 static void mesh_upper_transport_send_unsegmented_control_pdu(mesh_network_pdu_t * network_pdu){
954     // reserve slot
955     mesh_lower_transport_reserve_slot();
956     // reserve sequence number
957     uint32_t seq = mesh_sequence_number_next();
958     mesh_network_pdu_set_seq(network_pdu, seq);
959     // Dump PDU
960     uint8_t opcode = network_pdu->data[9];
961     printf("[+] Upper transport, send unsegmented Control PDU %p - seq %06x opcode %02x\n", network_pdu, seq, opcode);
962     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
963     // send
964     mesh_lower_transport_send_pdu((mesh_pdu_t *) network_pdu);
965 }
966 
967 static void mesh_upper_transport_send_segmented_control_pdu(mesh_transport_pdu_t * transport_pdu){
968     // reserve slot
969     mesh_lower_transport_reserve_slot();
970     // reserve sequence number
971     uint32_t seq = mesh_sequence_number_next();
972     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
973     mesh_transport_set_seq(transport_pdu, seq);
974     // Dump PDU
975     uint8_t opcode = transport_pdu->data[0];
976     printf("[+] Upper transport, send segmented Control PDU %p - seq %06x opcode %02x\n", transport_pdu, seq, opcode);
977     mesh_print_hex("Access Payload", &transport_pdu->data[1], transport_pdu->len - 1);
978     // send
979     mesh_lower_transport_send_pdu((mesh_pdu_t *) transport_pdu);
980 }
981 
982 static void mesh_upper_transport_run(void){
983 
984     while(!btstack_linked_list_empty(&upper_transport_incoming)){
985 
986         if (crypto_active) return;
987 
988         // peek at next message
989         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_incoming);
990         mesh_network_pdu_t   * network_pdu;
991         mesh_transport_pdu_t * transport_pdu;
992         mesh_message_pdu_t   * message_pdu;
993         switch (pdu->pdu_type){
994             case MESH_PDU_TYPE_NETWORK:
995                 network_pdu = (mesh_network_pdu_t *) pdu;
996                 // control?
997                 if (mesh_network_control(network_pdu)) {
998                     (void) btstack_linked_list_pop(&upper_transport_incoming);
999                     mesh_upper_unsegmented_control_message_received(network_pdu);
1000                 } else {
1001                     incoming_network_pdu_decoded = mesh_network_pdu_get();
1002                     if (!incoming_network_pdu_decoded) return;
1003                     // get encoded network pdu and start processing
1004                     incoming_network_pdu_raw = network_pdu;
1005                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1006                     mesh_upper_transport_process_unsegmented_access_message();
1007                 }
1008                 break;
1009             case MESH_PDU_TYPE_MESSAGE:
1010                 message_pdu = (mesh_message_pdu_t *) pdu;
1011                 uint8_t ctl = mesh_message_ctl(message_pdu);
1012                 if (ctl){
1013                     printf("Ignoring Segmented Control Message\n");
1014                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1015                     mesh_lower_transport_message_processed_by_higher_layer(pdu);
1016                 } else {
1017                     incoming_transport_pdu_decoded = mesh_transport_pdu_get();
1018                     if (!incoming_transport_pdu_decoded) return;
1019 
1020                     // use pre-allocated transport buffer
1021                     transport_pdu = &incoming_transport_pdu_singleton;
1022                     incoming_transport_pdu_singleton.pdu_header.pdu_type = MESH_PDU_TYPE_TRANSPORT;
1023 
1024                     // flatten segmented message into mesh_transport_pdu_t
1025 
1026                     // assemble payload
1027                     while (message_pdu->segments){
1028                         mesh_network_pdu_t * segment  = (mesh_network_pdu_t *) btstack_linked_list_pop(&message_pdu->segments);
1029                         // get segment n
1030                         uint8_t * lower_transport_pdu = mesh_network_pdu_data(segment);
1031                         uint8_t   seg_o               =  ( big_endian_read_16(lower_transport_pdu, 2) >> 5) & 0x001f;
1032                         uint8_t * segment_data = &lower_transport_pdu[4];
1033                         (void)memcpy(&transport_pdu->data[seg_o * 12], segment_data, 12);
1034                     }
1035 
1036                     // copy meta data
1037                     transport_pdu->len =  message_pdu->len;
1038                     transport_pdu->netkey_index =  message_pdu->netkey_index;
1039                     transport_pdu->transmic_len =  message_pdu->transmic_len;
1040                     transport_pdu->akf_aid_control =  message_pdu->akf_aid_control;
1041                     transport_pdu->flags =  message_pdu->flags;
1042                     transport_pdu->message_complete =  message_pdu->message_complete;
1043                     transport_pdu->seq_zero = message_pdu->seq_zero;
1044                     (void)memcpy(transport_pdu->network_header, message_pdu->network_header, 9);
1045 
1046                     mesh_print_hex("Assembled payload", transport_pdu->data, transport_pdu->len);
1047 
1048                     // free mesh message
1049                     mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *)message_pdu);
1050 
1051                     // get encoded transport pdu and start processing
1052                     incoming_transport_pdu_raw = transport_pdu;
1053                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1054                     mesh_upper_transport_process_message();
1055                 }
1056                 break;
1057             default:
1058                 break;
1059         }
1060     }
1061 
1062     while (!btstack_linked_list_empty(&upper_transport_outgoing)){
1063 
1064         if (crypto_active) break;
1065 
1066         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_outgoing);
1067         if (mesh_lower_transport_can_send_to_dest(mesh_pdu_dst(pdu)) == 0) break;
1068 
1069         (void) btstack_linked_list_pop(&upper_transport_outgoing);
1070 
1071         if (mesh_pdu_ctl(pdu)){
1072             switch (pdu->pdu_type){
1073                 case MESH_PDU_TYPE_NETWORK:
1074                     mesh_upper_transport_send_unsegmented_control_pdu((mesh_network_pdu_t *) pdu);
1075                     break;
1076                 case MESH_PDU_TYPE_MESSAGE:
1077                     btstack_assert(0);
1078                     break;
1079                 case MESH_PDU_TYPE_TRANSPORT:
1080                     mesh_upper_transport_send_segmented_control_pdu((mesh_transport_pdu_t *) pdu);
1081                     break;
1082                 default:
1083                     break;
1084             }
1085         } else {
1086             switch (pdu->pdu_type){
1087                 case MESH_PDU_TYPE_NETWORK:
1088                     btstack_assert(0);
1089                     break;
1090                 case MESH_PDU_TYPE_MESSAGE:
1091                     mesh_upper_transport_send_unsegmented_access_pdu((mesh_message_pdu_t *) pdu);
1092                     break;
1093                 case MESH_PDU_TYPE_TRANSPORT:
1094                     mesh_upper_transport_send_segmented_access_pdu((mesh_transport_pdu_t *) pdu);
1095                     break;
1096                 default:
1097                     break;
1098             }
1099         }
1100     }
1101 }
1102 
1103 void mesh_upper_transport_register_access_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1104     mesh_access_message_handler = callback;
1105 }
1106 
1107 void mesh_upper_transport_register_control_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1108     mesh_control_message_handler = callback;
1109 }
1110 
1111 void mesh_upper_transport_set_higher_layer_handler(void (*pdu_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu)){
1112     higher_layer_handler = pdu_handler;
1113 }
1114 
1115 void mesh_upper_transport_init(){
1116     mesh_lower_transport_set_higher_layer_handler(&mesh_upper_transport_pdu_handler);
1117 }
1118 
1119 // TODO: higher layer define used for assert
1120 #define MESH_ACCESS_OPCODE_NOT_SET 0xFFFFFFFEu
1121 
1122 void mesh_upper_transport_send_access_pdu(mesh_pdu_t *pdu){
1123     btstack_assert(pdu->ack_opcode != MESH_ACCESS_OPCODE_NOT_SET);
1124     btstack_assert(pdu->pdu_type != MESH_PDU_TYPE_NETWORK);
1125 
1126     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
1127     mesh_upper_transport_run();
1128 }
1129 
1130 void mesh_upper_transport_send_control_pdu(mesh_pdu_t * pdu){
1131     if (pdu->pdu_type == MESH_PDU_TYPE_NETWORK){
1132         btstack_assert( ((mesh_network_pdu_t *) pdu)->len >= 9);
1133     }
1134 
1135     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
1136     mesh_upper_transport_run();
1137 }
1138