xref: /btstack/src/mesh/mesh_upper_transport.c (revision d58a1b5f11ada8ddf896c41fff5a35e7f140c37e)
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 (1){
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_raw;
143 static mesh_transport_pdu_t * incoming_transport_pdu_decoded;
144 static uint8_t application_nonce[13];
145 static btstack_crypto_ccm_t ccm;
146 static mesh_transport_key_and_virtual_address_iterator_t mesh_transport_key_it;
147 
148 // upper transport callbacks - in access layer
149 static void (*mesh_access_message_handler)(mesh_pdu_t * pdu);
150 static void (*mesh_control_message_handler)(mesh_pdu_t * pdu);
151 
152 // incoming unsegmented (network) and segmented (transport) control and access messages
153 static btstack_linked_list_t upper_transport_incoming;
154 
155 // outgoing unsegmented (network) and segmented (uppert_transport_outgoing) control and access messages
156 static btstack_linked_list_t upper_transport_outgoing;
157 
158 static void mesh_upper_transport_dump_pdus(const char *name, btstack_linked_list_t *list){
159     printf("List: %s:\n", name);
160     btstack_linked_list_iterator_t it;
161     btstack_linked_list_iterator_init(&it, list);
162     while (btstack_linked_list_iterator_has_next(&it)){
163         mesh_pdu_t * pdu = (mesh_pdu_t*) btstack_linked_list_iterator_next(&it);
164         printf("- %p\n", pdu);
165         // printf_hexdump( mesh_pdu_data(pdu), mesh_pdu_len(pdu));
166     }
167 }
168 
169 static void mesh_upper_transport_reset_pdus(btstack_linked_list_t *list){
170     while (!btstack_linked_list_empty(list)){
171         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_pop(list);
172         switch (pdu->pdu_type){
173             case MESH_PDU_TYPE_NETWORK:
174                 btstack_memory_mesh_network_pdu_free((mesh_network_pdu_t *) pdu);
175                 break;
176             case MESH_PDU_TYPE_TRANSPORT:
177                 btstack_memory_mesh_transport_pdu_free((mesh_transport_pdu_t *) pdu);
178                 break;
179             default:
180                 break;
181         }
182     }
183 }
184 
185 void mesh_upper_transport_dump(void){
186     printf("incoming_network_pdu_raw: %p\n", incoming_network_pdu_raw);
187     printf("incoming_network_pdu_decoded: %p\n", incoming_network_pdu_decoded);
188     mesh_upper_transport_dump_pdus("upper_transport_incoming", &upper_transport_incoming);
189 }
190 
191 void mesh_upper_transport_reset(void){
192     crypto_active = 0;
193     if (incoming_network_pdu_raw){
194         mesh_network_pdu_free(incoming_network_pdu_raw);
195         incoming_network_pdu_raw = NULL;
196     }
197     // if (incoming_network_pdu_decoded){
198     //     mesh_network_pdu_free(incoming_network_pdu_decoded);
199     //     incoming_network_pdu_decoded = NULL;
200     // }
201     mesh_upper_transport_reset_pdus(&upper_transport_incoming);
202 }
203 
204 static void mesh_upper_unsegmented_control_message_received(mesh_network_pdu_t * network_pdu){
205     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
206     uint8_t  opcode = lower_transport_pdu[0];
207     if (mesh_control_message_handler){
208         mesh_control_message_handler((mesh_pdu_t*) network_pdu);
209     } else {
210         printf("[!] Unhandled Control message with opcode %02x\n", opcode);
211         // done
212         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
213     }
214 }
215 
216 static void mesh_upper_transport_process_unsegmented_message_done(mesh_network_pdu_t *network_pdu){
217     crypto_active = 0;
218     if (mesh_network_control(network_pdu)) {
219         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
220     } else {
221         mesh_network_pdu_free(network_pdu);
222         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) incoming_network_pdu_raw);
223         incoming_network_pdu_raw = NULL;
224     }
225     mesh_upper_transport_run();
226 }
227 
228 static void mesh_upper_transport_process_segmented_message_done(mesh_transport_pdu_t *transport_pdu){
229     crypto_active = 0;
230     if (mesh_transport_ctl(transport_pdu)) {
231         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *)transport_pdu);
232     } else {
233         mesh_transport_pdu_free(transport_pdu);
234         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *)incoming_transport_pdu_raw);
235         incoming_transport_pdu_raw = NULL;
236     }
237     mesh_upper_transport_run();
238 }
239 
240 static uint32_t iv_index_for_ivi_nid(uint8_t ivi_nid){
241     // get IV Index and IVI
242     uint32_t iv_index = mesh_get_iv_index();
243     int ivi = ivi_nid >> 7;
244 
245     // if least significant bit differs, use previous IV Index
246     if ((iv_index & 1 ) ^ ivi){
247         iv_index--;
248     }
249     return iv_index;
250 }
251 
252 static void transport_unsegmented_setup_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
253     nonce[1] = 0x00;    // SZMIC if a Segmented Access message or 0 for all other message formats
254     memcpy(&nonce[2], &network_pdu->data[2], 7);
255     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(network_pdu->data[0]));
256 }
257 
258 static void transport_segmented_setup_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
259     nonce[1] = transport_pdu->transmic_len == 8 ? 0x80 : 0x00;
260     memcpy(&nonce[2], &transport_pdu->network_header[2], 7);
261     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(transport_pdu->network_header[0]));
262 }
263 
264 static void transport_unsegmented_setup_application_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
265     nonce[0] = 0x01;
266     transport_unsegmented_setup_nonce(nonce, network_pdu);
267     mesh_print_hex("AppNonce", nonce, 13);
268 }
269 
270 static void transport_unsegmented_setup_device_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
271     nonce[0] = 0x02;
272     transport_unsegmented_setup_nonce(nonce, network_pdu);
273     mesh_print_hex("DeviceNonce", nonce, 13);
274 }
275 
276 static void transport_segmented_setup_application_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
277     nonce[0] = 0x01;
278     transport_segmented_setup_nonce(nonce, transport_pdu);
279     mesh_print_hex("AppNonce", nonce, 13);
280 }
281 
282 static void transport_segmented_setup_device_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
283     nonce[0] = 0x02;
284     transport_segmented_setup_nonce(nonce, transport_pdu);
285     mesh_print_hex("DeviceNonce", nonce, 13);
286 }
287 
288 static void mesh_upper_transport_validate_unsegmented_message_ccm(void * arg){
289     UNUSED(arg);
290 
291     uint8_t * lower_transport_pdu = mesh_network_pdu_data(incoming_network_pdu_decoded);
292     uint8_t trans_mic_len = 4;
293 
294     // store TransMIC
295     uint8_t trans_mic[8];
296     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
297     mesh_print_hex("TransMIC", trans_mic, trans_mic_len);
298 
299     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(incoming_network_pdu_decoded) + 1;
300     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(incoming_network_pdu_decoded)  - 1;
301 
302     mesh_print_hex("Decryted PDU", upper_transport_pdu, upper_transport_pdu_len - trans_mic_len);
303 
304     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len - trans_mic_len], trans_mic_len) == 0){
305         printf("TransMIC matches\n");
306 
307         // remove TransMIC from payload
308         incoming_network_pdu_decoded->len -= trans_mic_len;
309 
310         // if virtual address, update dst to pseudo_dst
311         if (mesh_network_address_virtual(mesh_network_dst(incoming_network_pdu_decoded))){
312             big_endian_store_16(incoming_network_pdu_decoded->data, 7, mesh_transport_key_it.address->pseudo_dst);
313         }
314 
315         // pass to upper layer
316         if (mesh_access_message_handler){
317             mesh_pdu_t * pdu = (mesh_pdu_t*) incoming_network_pdu_decoded;
318             incoming_network_pdu_decoded = NULL;
319             mesh_access_message_handler(pdu);
320         } else {
321             printf("[!] Unhandled Unsegmented Access message\n");
322             // done
323             mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
324         }
325 
326         printf("\n");
327     } else {
328         uint8_t afk = lower_transport_pdu[0] & 0x40;
329         if (afk){
330             printf("TransMIC does not match, try next key\n");
331             mesh_upper_transport_validate_unsegmented_message();
332         } else {
333             printf("TransMIC does not match device key, done\n");
334             // done
335             mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
336         }
337     }
338 }
339 
340 static void mesh_upper_transport_validate_segmented_message_ccm(void * arg){
341     UNUSED(arg);
342 
343     uint8_t * upper_transport_pdu     =  incoming_transport_pdu_decoded->data;
344     uint8_t   upper_transport_pdu_len =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
345 
346     mesh_print_hex("Decrypted PDU", upper_transport_pdu, upper_transport_pdu_len);
347 
348     // store TransMIC
349     uint8_t trans_mic[8];
350     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
351     mesh_print_hex("TransMIC", trans_mic, incoming_transport_pdu_decoded->transmic_len);
352 
353     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len], incoming_transport_pdu_decoded->transmic_len) == 0){
354         printf("TransMIC matches\n");
355 
356         // remove TransMIC from payload
357         incoming_transport_pdu_decoded->len -= incoming_transport_pdu_decoded->transmic_len;
358 
359         // if virtual address, update dst to pseudo_dst
360         if (mesh_network_address_virtual(mesh_transport_dst(incoming_transport_pdu_decoded))){
361             big_endian_store_16(incoming_transport_pdu_decoded->network_header, 7, mesh_transport_key_it.address->pseudo_dst);
362         }
363 
364         // pass to upper layer
365         if (mesh_access_message_handler){
366             mesh_pdu_t * pdu = (mesh_pdu_t*) incoming_transport_pdu_decoded;
367             incoming_network_pdu_decoded = NULL;
368             mesh_access_message_handler(pdu);
369         } else {
370             printf("[!] Unhandled Segmented Access/Control message\n");
371             // done
372             mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
373         }
374 
375         printf("\n");
376 
377     } else {
378         uint8_t akf = incoming_transport_pdu_decoded->akf_aid_control & 0x40;
379         if (akf){
380             printf("TransMIC does not match, try next key\n");
381             mesh_upper_transport_validate_segmented_message();
382         } else {
383             printf("TransMIC does not match device key, done\n");
384             // done
385             mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
386         }
387     }
388 }
389 
390 void mesh_upper_transport_message_processed_by_higher_layer(mesh_pdu_t * pdu){
391     crypto_active = 0;
392     switch (pdu->pdu_type){
393         case MESH_PDU_TYPE_NETWORK:
394             mesh_upper_transport_process_unsegmented_message_done((mesh_network_pdu_t *) pdu);
395             break;
396         case MESH_PDU_TYPE_TRANSPORT:
397             mesh_upper_transport_process_segmented_message_done((mesh_transport_pdu_t *) pdu);
398             break;
399         default:
400             break;
401     }
402 }
403 
404 static void mesh_upper_transport_validate_segmented_message_digest(void * arg){
405     UNUSED(arg);
406     uint8_t   upper_transport_pdu_len      = incoming_transport_pdu_raw->len - incoming_transport_pdu_raw->transmic_len;
407     uint8_t * upper_transport_pdu_data_in  = incoming_transport_pdu_raw->data;
408     uint8_t * upper_transport_pdu_data_out = incoming_transport_pdu_decoded->data;
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_segmented_message_ccm, NULL);
410 }
411 
412 static void mesh_upper_transport_validate_unsegmented_message_digest(void * arg){
413     UNUSED(arg);
414     uint8_t   trans_mic_len = 4;
415     uint8_t   lower_transport_pdu_len      = incoming_network_pdu_raw->len - 9;
416     uint8_t * upper_transport_pdu_data_in  = &incoming_network_pdu_raw->data[10];
417     uint8_t * upper_transport_pdu_data_out = &incoming_network_pdu_decoded->data[10];
418     uint8_t   upper_transport_pdu_len      = lower_transport_pdu_len - 1 - trans_mic_len;
419     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);
420 }
421 
422 static void mesh_upper_transport_validate_unsegmented_message(void){
423 
424     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
425         printf("No valid transport key found\n");
426         mesh_upper_transport_process_unsegmented_message_done(incoming_network_pdu_decoded);
427         return;
428     }
429     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
430     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
431 
432     if (message_key->akf){
433         transport_unsegmented_setup_application_nonce(application_nonce, incoming_network_pdu_raw);
434     } else {
435         transport_unsegmented_setup_device_nonce(application_nonce, incoming_network_pdu_raw);
436     }
437 
438     // store application / device key index
439     mesh_print_hex("AppOrDevKey", message_key->key, 16);
440     incoming_network_pdu_decoded->appkey_index = message_key->appkey_index;
441 
442     // unsegmented message have TransMIC of 32 bit
443     uint8_t trans_mic_len = 4;
444     printf("Unsegmented Access message with TransMIC len 4\n");
445 
446     uint8_t   lower_transport_pdu_len = incoming_network_pdu_raw->len - 9;
447     uint8_t * upper_transport_pdu_data = &incoming_network_pdu_raw->data[10];
448     uint8_t   upper_transport_pdu_len  = lower_transport_pdu_len - 1 - trans_mic_len;
449 
450     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
451 
452     // decrypt ccm
453     crypto_active = 1;
454     uint16_t aad_len  = 0;
455     if (mesh_network_address_virtual(mesh_network_dst(incoming_network_pdu_decoded))){
456         aad_len  = 16;
457     }
458     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, trans_mic_len);
459     if (aad_len){
460         btstack_crypto_ccm_digest(&ccm, (uint8_t*) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_unsegmented_message_digest, NULL);
461     } else {
462         mesh_upper_transport_validate_unsegmented_message_digest(incoming_network_pdu_decoded);
463     }
464 }
465 
466 static void mesh_upper_transport_validate_segmented_message(void){
467     uint8_t * upper_transport_pdu_data =  incoming_transport_pdu_decoded->data;
468     uint8_t   upper_transport_pdu_len  =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
469 
470     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
471         printf("No valid transport key found\n");
472         mesh_upper_transport_process_segmented_message_done(incoming_transport_pdu_decoded);
473         return;
474     }
475     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
476     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
477 
478     if (message_key->akf){
479         transport_segmented_setup_application_nonce(application_nonce, incoming_transport_pdu_raw);
480     } else {
481         transport_segmented_setup_device_nonce(application_nonce, incoming_transport_pdu_raw);
482     }
483 
484     // store application / device key index
485     mesh_print_hex("AppOrDevKey", message_key->key, 16);
486     incoming_transport_pdu_decoded->appkey_index = message_key->appkey_index;
487 
488     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
489 
490     // decrypt ccm
491     crypto_active = 1;
492     uint16_t aad_len  = 0;
493     if (mesh_network_address_virtual(mesh_transport_dst(incoming_transport_pdu_decoded))){
494         aad_len  = 16;
495     }
496     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, incoming_transport_pdu_decoded->transmic_len);
497 
498     if (aad_len){
499         btstack_crypto_ccm_digest(&ccm, (uint8_t *) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_segmented_message_digest, NULL);
500     } else {
501         mesh_upper_transport_validate_segmented_message_digest(NULL);
502     }
503 }
504 
505 static void mesh_upper_transport_process_unsegmented_access_message(void){
506     // copy original pdu
507     incoming_network_pdu_decoded->len = incoming_network_pdu_raw->len;
508     memcpy(incoming_network_pdu_decoded->data, incoming_network_pdu_raw->data, incoming_network_pdu_decoded->len);
509 
510     //
511     uint8_t * lower_transport_pdu     = &incoming_network_pdu_raw->data[9];
512     uint8_t   lower_transport_pdu_len = incoming_network_pdu_raw->len - 9;
513 
514     mesh_print_hex("Lower Transport network pdu", &incoming_network_pdu_raw->data[9], lower_transport_pdu_len);
515 
516     uint8_t aid =  lower_transport_pdu[0] & 0x3f;
517     uint8_t akf = (lower_transport_pdu[0] & 0x40) >> 6;
518     printf("AKF: %u\n",   akf);
519     printf("AID: %02x\n", aid);
520 
521     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_network_dst(incoming_network_pdu_decoded),
522             incoming_network_pdu_decoded->netkey_index, akf, aid);
523     mesh_upper_transport_validate_unsegmented_message();
524 }
525 
526 static void mesh_upper_transport_process_message(void){
527     // copy original pdu
528     memcpy(incoming_transport_pdu_decoded, incoming_transport_pdu_raw, sizeof(mesh_transport_pdu_t));
529 
530     //
531     uint8_t * upper_transport_pdu     =  incoming_transport_pdu_decoded->data;
532     uint8_t   upper_transport_pdu_len =  incoming_transport_pdu_decoded->len - incoming_transport_pdu_decoded->transmic_len;
533     mesh_print_hex("Upper Transport pdu", upper_transport_pdu, upper_transport_pdu_len);
534 
535     uint8_t aid =  incoming_transport_pdu_decoded->akf_aid_control & 0x3f;
536     uint8_t akf = (incoming_transport_pdu_decoded->akf_aid_control & 0x40) >> 6;
537 
538     printf("AKF: %u\n",   akf);
539     printf("AID: %02x\n", aid);
540 
541     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_transport_dst(incoming_transport_pdu_decoded),
542             incoming_transport_pdu_decoded->netkey_index, akf, aid);
543     mesh_upper_transport_validate_segmented_message();
544 }
545 
546 static void mesh_upper_transport_message_received(mesh_pdu_t * pdu){
547     btstack_linked_list_add_tail(&upper_transport_incoming, (btstack_linked_item_t*) pdu);
548     mesh_upper_transport_run();
549 }
550 
551 void mesh_upper_transport_pdu_free(mesh_pdu_t * pdu){
552     mesh_network_pdu_t * network_pdu;
553     mesh_transport_pdu_t * transport_pdu;
554     switch (pdu->pdu_type) {
555         case MESH_PDU_TYPE_NETWORK:
556             network_pdu = (mesh_network_pdu_t *) pdu;
557             mesh_network_pdu_free(network_pdu);
558             break;
559         case MESH_PDU_TYPE_TRANSPORT:
560             transport_pdu = (mesh_transport_pdu_t *) pdu;
561             mesh_transport_pdu_free(transport_pdu);
562             break;
563         default:
564             break;
565     }
566 }
567 
568 static void mesh_upper_transport_pdu_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
569     switch (callback_type){
570         case MESH_TRANSPORT_PDU_RECEIVED:
571             mesh_upper_transport_message_received(pdu);
572             break;
573         case MESH_TRANSPORT_PDU_SENT:
574             // notify upper layer (or just free pdu)
575             if (higher_layer_handler){
576                 higher_layer_handler(callback_type, status, pdu);
577             } else {
578                 mesh_upper_transport_pdu_free(pdu);
579             }
580             mesh_upper_transport_run();
581             break;
582         default:
583             break;
584     }
585 }
586 static void mesh_upper_transport_send_unsegmented_access_pdu_ccm(void * arg){
587     crypto_active = 0;
588 
589     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
590     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(network_pdu) + 1;
591     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(network_pdu)  - 1;
592     mesh_print_hex("EncAccessPayload", upper_transport_pdu, upper_transport_pdu_len);
593     // store TransMIC
594     btstack_crypto_ccm_get_authentication_value(&ccm, &upper_transport_pdu[upper_transport_pdu_len]);
595     mesh_print_hex("TransMIC", &upper_transport_pdu[upper_transport_pdu_len], 4);
596     network_pdu->len        += 4;
597     upper_transport_pdu_len += 4;
598     mesh_print_hex("UpperTransportPDU", upper_transport_pdu, upper_transport_pdu_len);
599     // send network pdu
600     mesh_lower_transport_send_pdu((mesh_pdu_t*) network_pdu);
601 }
602 
603 static void mesh_upper_transport_send_segmented_access_pdu_ccm(void * arg){
604     crypto_active = 0;
605 
606     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
607     mesh_print_hex("EncAccessPayload", transport_pdu->data, transport_pdu->len);
608     // store TransMIC
609     btstack_crypto_ccm_get_authentication_value(&ccm, &transport_pdu->data[transport_pdu->len]);
610     mesh_print_hex("TransMIC", &transport_pdu->data[transport_pdu->len], transport_pdu->transmic_len);
611     transport_pdu->len += transport_pdu->transmic_len;
612     mesh_print_hex("UpperTransportPDU", transport_pdu->data, transport_pdu->len);
613     mesh_lower_transport_send_pdu((mesh_pdu_t*) transport_pdu);
614 }
615 
616 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,
617                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
618 
619     if (control_pdu_len > 11) return 1;
620 
621     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
622     if (!network_key) return 1;
623 
624     uint8_t transport_pdu_data[12];
625     transport_pdu_data[0] = opcode;
626     memcpy(&transport_pdu_data[1], control_pdu_data, control_pdu_len);
627     uint16_t transport_pdu_len = control_pdu_len + 1;
628 
629     // setup network_pdu
630     mesh_network_setup_pdu(network_pdu, netkey_index, network_key->nid, 1, ttl, 0, src, dest, transport_pdu_data, transport_pdu_len);
631 
632     return 0;
633 }
634 
635 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,
636                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
637 
638     if (control_pdu_len > 256) return 1;
639 
640     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
641     if (!network_key) return 1;
642 
643     memcpy(transport_pdu->data, control_pdu_data, control_pdu_len);
644     transport_pdu->len = control_pdu_len;
645     transport_pdu->netkey_index = netkey_index;
646     transport_pdu->akf_aid_control = opcode;
647     transport_pdu->transmic_len = 0;    // no TransMIC for control
648     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid);
649     mesh_transport_set_src(transport_pdu, src);
650     mesh_transport_set_dest(transport_pdu, dest);
651     mesh_transport_set_ctl_ttl(transport_pdu, 0x80 | ttl);
652 
653     return 0;
654 }
655 
656 uint8_t mesh_upper_transport_setup_control_pdu(mesh_pdu_t * pdu, uint16_t netkey_index,
657                                                uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode, const uint8_t * control_pdu_data, uint16_t control_pdu_len){
658     switch (pdu->pdu_type){
659         case MESH_PDU_TYPE_NETWORK:
660             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);
661         case MESH_PDU_TYPE_TRANSPORT:
662             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);
663         default:
664             return 1;
665     }
666 }
667 
668 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu_header(mesh_network_pdu_t * network_pdu, uint16_t netkey_index,
669         uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest){
670 
671     // get app or device key
672     const mesh_transport_key_t * appkey;
673     appkey = mesh_transport_key_get(appkey_index);
674     if (appkey == NULL){
675         printf("appkey_index %x unknown\n", appkey_index);
676         return 1;
677     }
678     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
679 
680     // lookup network by netkey_index
681     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
682     if (!network_key) return 1;
683 
684     network_pdu->data[9] = akf_aid;
685     // setup network_pdu
686     mesh_network_setup_pdu_header(network_pdu, netkey_index, network_key->nid, 0, ttl, 0, src, dest);
687     network_pdu->appkey_index = appkey_index;
688     return 0;
689 }
690 
691 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
692                                                        const uint8_t * access_pdu_data, uint8_t access_pdu_len){
693 
694     int status = mesh_upper_transport_setup_unsegmented_access_pdu_header(network_pdu, netkey_index, appkey_index, ttl, src, dest);
695     if (status) return status;
696 
697     // store in transport pdu
698     memcpy(&network_pdu->data[10], access_pdu_data, access_pdu_len);
699     network_pdu->len = 10 + access_pdu_len;
700     return 0;
701 }
702 
703 static uint8_t mesh_upper_transport_setup_segmented_access_pdu_header(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index,
704     uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
705 
706     // get app or device key
707     const mesh_transport_key_t *appkey;
708     appkey = mesh_transport_key_get(appkey_index);
709     if (appkey == NULL) {
710         printf("[!] Upper transport, setup segmented Access PDU - appkey_index %x unknown\n", appkey_index);
711         return 1;
712     }
713     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
714 
715     // lookup network by netkey_index
716     const mesh_network_key_t *network_key = mesh_network_key_list_get(netkey_index);
717     if (!network_key) return 1;
718     if (network_key == NULL) {
719         printf("[!] Upper transport, setup segmented Access PDU - netkey_index %x unknown\n", appkey_index);
720         return 1;
721     }
722 
723     const uint8_t trans_mic_len = szmic ? 8 : 4;
724 
725     // store in transport pdu
726     transport_pdu->transmic_len = trans_mic_len;
727     transport_pdu->netkey_index = netkey_index;
728     transport_pdu->appkey_index = appkey_index;
729     transport_pdu->akf_aid_control = akf_aid;
730     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid | ((mesh_get_iv_index_for_tx() & 1) << 7));
731     mesh_transport_set_src(transport_pdu, src);
732     mesh_transport_set_dest(transport_pdu, dest);
733     mesh_transport_set_ctl_ttl(transport_pdu, ttl);
734     return 0;
735 }
736 
737 
738 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,
739                           uint8_t szmic, const uint8_t * access_pdu_data, uint8_t access_pdu_len){
740     int status = mesh_upper_transport_setup_segmented_access_pdu_header(transport_pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
741     if (status) return status;
742 
743     // store in transport pdu
744     memcpy(transport_pdu->data, access_pdu_data, access_pdu_len);
745     transport_pdu->len = access_pdu_len;
746     return 0;
747 }
748 uint8_t mesh_upper_transport_setup_access_pdu_header(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
749                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
750     switch (pdu->pdu_type){
751         case MESH_PDU_TYPE_NETWORK:
752             return mesh_upper_transport_setup_unsegmented_access_pdu_header((mesh_network_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest);
753         case MESH_PDU_TYPE_TRANSPORT:
754             return mesh_upper_transport_setup_segmented_access_pdu_header((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
755         default:
756             return 1;
757     }
758 }
759 
760 uint8_t mesh_upper_transport_setup_access_pdu(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
761                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic,
762                                               const uint8_t * access_pdu_data, uint8_t access_pdu_len){
763     switch (pdu->pdu_type){
764         case MESH_PDU_TYPE_NETWORK:
765             return mesh_upper_transport_setup_unsegmented_access_pdu((mesh_network_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, access_pdu_data, access_pdu_len);
766         case MESH_PDU_TYPE_TRANSPORT:
767             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);
768         default:
769             return 1;
770     }
771 }
772 
773 static void mesh_upper_transport_send_unsegmented_access_pdu_digest(void * arg){
774     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
775     uint8_t * access_pdu_data = mesh_network_pdu_data(network_pdu) + 1;
776     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
777     btstack_crypto_ccm_encrypt_block(&ccm, access_pdu_len, access_pdu_data, access_pdu_data, &mesh_upper_transport_send_unsegmented_access_pdu_ccm, network_pdu);
778 }
779 
780 static mesh_transport_key_t * mesh_upper_transport_get_outgoing_appkey(uint16_t netkey_index, uint16_t appkey_index){
781     // Device Key is fixed
782     if (appkey_index == MESH_DEVICE_KEY_INDEX) {
783         return mesh_transport_key_get(appkey_index);
784     }
785 
786     // Get key refresh state from subnet
787     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
788     if (subnet == NULL) return NULL;
789 
790     // identify old and new app keys for given appkey_index
791     mesh_transport_key_t * old_key = NULL;
792     mesh_transport_key_t * new_key = NULL;
793     mesh_transport_key_iterator_t it;
794     mesh_transport_key_iterator_init(&it, netkey_index);
795     while (mesh_transport_key_iterator_has_more(&it)){
796         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
797         if (transport_key->appkey_index != appkey_index) continue;
798         if (transport_key->old_key == 0) {
799             new_key = transport_key;
800         } else {
801             old_key = transport_key;
802         }
803     }
804 
805     // if no key is marked as old, just use the current one
806     if (old_key == NULL) return new_key;
807 
808     // use new key if it exists in phase two
809     if ((subnet->key_refresh == MESH_KEY_REFRESH_SECOND_PHASE) && (new_key != NULL)){
810         return new_key;
811     } else {
812         return old_key;
813     }
814 }
815 
816 static void mesh_upper_transport_send_unsegmented_access_pdu(mesh_network_pdu_t * network_pdu){
817 
818     // if dst is virtual address, lookup label uuid and hash
819     uint16_t aad_len = 0;
820     mesh_virtual_address_t * virtual_address = NULL;
821     uint16_t dst = mesh_network_dst(network_pdu);
822     if (mesh_network_address_virtual(dst)){
823         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
824         if (!virtual_address){
825             printf("No virtual address register for pseudo dst %4x\n", dst);
826             btstack_memory_mesh_network_pdu_free(network_pdu);
827             return;
828         }
829         aad_len = 16;
830         big_endian_store_16(network_pdu->data, 7, virtual_address->hash);
831     }
832 
833     // reserve slot
834     mesh_lower_transport_reserve_slot();
835 
836     // Nonce for Access Payload based on Network Sequence number: needs to be fixed now and lower layers need to send packet in right order
837     uint32_t seq = mesh_sequence_number_next();
838     mesh_network_pdu_set_seq(network_pdu, seq);
839 
840     // Dump PDU
841     printf("[+] Upper transport, send unsegmented Access PDU - dest %04x, seq %06x\n", dst, mesh_network_seq(network_pdu));
842     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
843 
844     // setup nonce
845     uint16_t appkey_index = network_pdu->appkey_index;
846     if (appkey_index == MESH_DEVICE_KEY_INDEX){
847         transport_unsegmented_setup_device_nonce(application_nonce, network_pdu);
848     } else {
849         transport_unsegmented_setup_application_nonce(application_nonce, network_pdu);
850     }
851 
852     // get app or device key
853     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(network_pdu->netkey_index, appkey_index);
854     mesh_print_hex("AppOrDevKey", appkey->key, 16);
855 
856     // encrypt ccm
857     uint8_t   trans_mic_len = 4;
858     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
859     crypto_active = 1;
860 
861     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, trans_mic_len);
862     if (virtual_address){
863         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
864         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_unsegmented_access_pdu_digest, network_pdu);
865     } else {
866         mesh_upper_transport_send_unsegmented_access_pdu_digest(network_pdu);
867     }
868 }
869 
870 static void mesh_upper_transport_send_segmented_access_pdu_digest(void *arg){
871     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
872     uint16_t  access_pdu_len  = transport_pdu->len;
873     uint8_t * access_pdu_data = transport_pdu->data;
874     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);
875 }
876 
877 static void mesh_upper_transport_send_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu){
878 
879     // if dst is virtual address, lookup label uuid and hash
880     uint16_t aad_len = 0;
881     mesh_virtual_address_t * virtual_address = NULL;
882     uint16_t dst = mesh_transport_dst(transport_pdu);
883     if (mesh_network_address_virtual(dst)){
884         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
885         if (!virtual_address){
886             printf("No virtual address register for pseudo dst %4x\n", dst);
887             btstack_memory_mesh_transport_pdu_free(transport_pdu);
888             return;
889         }
890         // printf("Using hash %4x with LabelUUID: ", virtual_address->hash);
891         // printf_hexdump(virtual_address->label_uuid, 16);
892         aad_len = 16;
893         big_endian_store_16(transport_pdu->network_header, 7, virtual_address->hash);
894     }
895 
896     // get app or device key
897     uint16_t appkey_index = transport_pdu->appkey_index;
898     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(transport_pdu->netkey_index, appkey_index);
899     if (appkey == NULL){
900         printf("AppKey %04x not found, drop message\n", appkey_index);
901         btstack_memory_mesh_transport_pdu_free(transport_pdu);
902         return;
903     }
904 
905     // reserve slot
906     mesh_lower_transport_reserve_slot();
907 
908     // reserve one sequence number, which is also used to encrypt access payload
909     uint32_t seq = mesh_sequence_number_next();
910     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
911     mesh_transport_set_seq(transport_pdu, seq);
912 
913     // Dump PDU
914     printf("[+] Upper transport, send segmented Access PDU - dest %04x, seq %06x\n", dst, mesh_transport_seq(transport_pdu));
915     mesh_print_hex("Access Payload", transport_pdu->data, transport_pdu->len);
916 
917     // setup nonce - uses dst, so after pseudo address translation
918     if (appkey_index == MESH_DEVICE_KEY_INDEX){
919         transport_segmented_setup_device_nonce(application_nonce, transport_pdu);
920     } else {
921         transport_segmented_setup_application_nonce(application_nonce, transport_pdu);
922     }
923 
924     // Dump key
925     mesh_print_hex("AppOrDevKey", appkey->key, 16);
926 
927     // encrypt ccm
928     uint8_t   transmic_len    = transport_pdu->transmic_len;
929     uint16_t  access_pdu_len  = transport_pdu->len;
930     crypto_active = 1;
931     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, transmic_len);
932     if (virtual_address){
933         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
934         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_segmented_access_pdu_digest, transport_pdu);
935     } else {
936         mesh_upper_transport_send_segmented_access_pdu_digest(transport_pdu);
937     }
938 }
939 
940 static void mesh_upper_transport_send_unsegmented_control_pdu(mesh_network_pdu_t * network_pdu){
941     // reserve slot
942     mesh_lower_transport_reserve_slot();
943     // reserve sequence number
944     uint32_t seq = mesh_sequence_number_next();
945     mesh_network_pdu_set_seq(network_pdu, seq);
946     // Dump PDU
947     uint8_t opcode = network_pdu->data[9];
948     printf("[+] Upper transport, send unsegmented Control PDU %p - seq %06x opcode %02x\n", network_pdu, seq, opcode);
949     mesh_print_hex("Access Payload", &network_pdu->data[10], network_pdu->len - 10);
950     // send
951     mesh_lower_transport_send_pdu((mesh_pdu_t *) network_pdu);
952 }
953 
954 static void mesh_upper_transport_send_segmented_control_pdu(mesh_transport_pdu_t * transport_pdu){
955     // reserve slot
956     mesh_lower_transport_reserve_slot();
957     // reserve sequence number
958     uint32_t seq = mesh_sequence_number_next();
959     transport_pdu->flags |= MESH_TRANSPORT_FLAG_SEQ_RESERVED;
960     mesh_transport_set_seq(transport_pdu, seq);
961     // Dump PDU
962     uint8_t opcode = transport_pdu->data[0];
963     printf("[+] Upper transport, send segmented Control PDU %p - seq %06x opcode %02x\n", transport_pdu, seq, opcode);
964     mesh_print_hex("Access Payload", &transport_pdu->data[1], transport_pdu->len - 1);
965     // send
966     mesh_lower_transport_send_pdu((mesh_pdu_t *) transport_pdu);
967 }
968 
969 static void mesh_upper_transport_run(void){
970 
971     while(!btstack_linked_list_empty(&upper_transport_incoming)){
972 
973         if (crypto_active) return;
974 
975         // peek at next message
976         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_incoming);
977         mesh_transport_pdu_t * transport_pdu;
978         mesh_network_pdu_t   * network_pdu;
979         switch (pdu->pdu_type){
980             case MESH_PDU_TYPE_NETWORK:
981                 network_pdu = (mesh_network_pdu_t *) pdu;
982                 // control?
983                 if (mesh_network_control(network_pdu)) {
984                     (void) btstack_linked_list_pop(&upper_transport_incoming);
985                     mesh_upper_unsegmented_control_message_received(network_pdu);
986                 } else {
987                     incoming_network_pdu_decoded = mesh_network_pdu_get();
988                     if (!incoming_network_pdu_decoded) return;
989                     // get encoded network pdu and start processing
990                     incoming_network_pdu_raw = network_pdu;
991                     (void) btstack_linked_list_pop(&upper_transport_incoming);
992                     mesh_upper_transport_process_unsegmented_access_message();
993                 }
994                 break;
995             case MESH_PDU_TYPE_TRANSPORT:
996                 transport_pdu = (mesh_transport_pdu_t *) pdu;
997                 uint8_t ctl = mesh_transport_ctl(transport_pdu);
998                 if (ctl){
999                     printf("Ignoring Segmented Control Message\n");
1000                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1001                     mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) transport_pdu);
1002                 } else {
1003                     incoming_transport_pdu_decoded = mesh_transport_pdu_get();
1004                     if (!incoming_transport_pdu_decoded) return;
1005                     // get encoded transport pdu and start processing
1006                     incoming_transport_pdu_raw = transport_pdu;
1007                     (void) btstack_linked_list_pop(&upper_transport_incoming);
1008                     mesh_upper_transport_process_message();
1009                 }
1010                 break;
1011             default:
1012                 break;
1013         }
1014     }
1015 
1016     while (!btstack_linked_list_empty(&upper_transport_outgoing)){
1017 
1018         if (crypto_active) break;
1019 
1020         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_outgoing);
1021         if (mesh_lower_transport_can_send_to_dest(mesh_pdu_dst(pdu)) == 0) break;
1022 
1023         (void) btstack_linked_list_pop(&upper_transport_outgoing);
1024 
1025         if (mesh_pdu_ctl(pdu)){
1026             switch (pdu->pdu_type){
1027                 case MESH_PDU_TYPE_NETWORK:
1028                     mesh_upper_transport_send_unsegmented_control_pdu((mesh_network_pdu_t *) pdu);
1029                     break;
1030                 case MESH_PDU_TYPE_TRANSPORT:
1031                     mesh_upper_transport_send_segmented_control_pdu((mesh_transport_pdu_t *) pdu);
1032                     break;
1033                 default:
1034                     break;
1035             }
1036         } else {
1037             switch (pdu->pdu_type){
1038                 case MESH_PDU_TYPE_NETWORK:
1039                     mesh_upper_transport_send_unsegmented_access_pdu((mesh_network_pdu_t *) pdu);
1040                     break;
1041                 case MESH_PDU_TYPE_TRANSPORT:
1042                     mesh_upper_transport_send_segmented_access_pdu((mesh_transport_pdu_t *) pdu);
1043                     break;
1044                 default:
1045                     break;
1046             }
1047         }
1048     }
1049 }
1050 
1051 void mesh_upper_transport_register_access_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1052     mesh_access_message_handler = callback;
1053 }
1054 
1055 void mesh_upper_transport_register_control_message_handler(void (*callback)(mesh_pdu_t *pdu)){
1056     mesh_control_message_handler = callback;
1057 }
1058 
1059 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)){
1060     higher_layer_handler = pdu_handler;
1061 }
1062 
1063 void mesh_upper_transport_init(){
1064     mesh_lower_transport_set_higher_layer_handler(&mesh_upper_transport_pdu_handler);
1065 }
1066 
1067 // TODO: higher layer define used for assert
1068 #define MESH_ACCESS_OPCODE_NOT_SET 0xFFFFFFFEu
1069 
1070 void mesh_upper_transport_send_access_pdu(mesh_pdu_t *pdu){
1071     btstack_assert(pdu->ack_opcode != MESH_ACCESS_OPCODE_NOT_SET);
1072 
1073     if (pdu->pdu_type == MESH_PDU_TYPE_NETWORK){
1074         btstack_assert( ((mesh_network_pdu_t *) pdu)->len >= 9);
1075     }
1076 
1077     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
1078     mesh_upper_transport_run();
1079 }
1080 
1081 void mesh_upper_transport_send_control_pdu(mesh_pdu_t * pdu){
1082     if (pdu->pdu_type == MESH_PDU_TYPE_NETWORK){
1083         btstack_assert( ((mesh_network_pdu_t *) pdu)->len >= 9);
1084     }
1085 
1086     btstack_linked_list_add_tail(&upper_transport_outgoing, (btstack_linked_item_t*) pdu);
1087     mesh_upper_transport_run();
1088 }
1089