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