xref: /btstack/src/mesh/mesh_lower_transport.c (revision 6f3fd12d2666a6213f4b3282f2093a091e66963a)
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_lower_transport.c"
39 
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "btstack_memory.h"
45 #include "btstack_util.h"
46 
47 #include "mesh/beacon.h"
48 #include "mesh/mesh_iv_index_seq_number.h"
49 #include "mesh/mesh_lower_transport.h"
50 #include "mesh/mesh_node.h"
51 #include "mesh/mesh_peer.h"
52 
53 #define LOG_LOWER_TRANSPORT
54 
55 static void (*higher_layer_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu);
56 
57 static void mesh_print_hex(const char * name, const uint8_t * data, uint16_t len){
58     printf("%-20s ", name);
59     printf_hexdump(data, len);
60 }
61 // static void mesh_print_x(const char * name, uint32_t value){
62 //     printf("%20s: 0x%x", name, (int) value);
63 // }
64 
65 // utility
66 
67 // Transport PDU Getter
68 uint16_t mesh_transport_nid(mesh_transport_pdu_t * transport_pdu){
69     return transport_pdu->network_header[0] & 0x7f;
70 }
71 uint16_t mesh_transport_ctl(mesh_transport_pdu_t * transport_pdu){
72     return transport_pdu->network_header[1] >> 7;
73 }
74 uint16_t mesh_transport_ttl(mesh_transport_pdu_t * transport_pdu){
75     return transport_pdu->network_header[1] & 0x7f;
76 }
77 uint32_t mesh_transport_seq(mesh_transport_pdu_t * transport_pdu){
78     return big_endian_read_24(transport_pdu->network_header, 2);
79 }
80 uint32_t mesh_transport_seq_zero(mesh_transport_pdu_t * transport_pdu){
81     return transport_pdu->seq_zero;
82 }
83 uint16_t mesh_transport_src(mesh_transport_pdu_t * transport_pdu){
84     return big_endian_read_16(transport_pdu->network_header, 5);
85 }
86 uint16_t mesh_transport_dst(mesh_transport_pdu_t * transport_pdu){
87     return big_endian_read_16(transport_pdu->network_header, 7);
88 }
89 uint8_t  mesh_transport_control_opcode(mesh_transport_pdu_t * transport_pdu){
90     return transport_pdu->akf_aid_control & 0x7f;
91 }
92 void mesh_transport_set_nid_ivi(mesh_transport_pdu_t * transport_pdu, uint8_t nid_ivi){
93     transport_pdu->network_header[0] = nid_ivi;
94 }
95 void mesh_transport_set_ctl_ttl(mesh_transport_pdu_t * transport_pdu, uint8_t ctl_ttl){
96     transport_pdu->network_header[1] = ctl_ttl;
97 }
98 void mesh_transport_set_seq(mesh_transport_pdu_t * transport_pdu, uint32_t seq){
99     big_endian_store_24(transport_pdu->network_header, 2, seq);
100 }
101 void mesh_transport_set_src(mesh_transport_pdu_t * transport_pdu, uint16_t src){
102     big_endian_store_16(transport_pdu->network_header, 5, src);
103 }
104 void mesh_transport_set_dest(mesh_transport_pdu_t * transport_pdu, uint16_t dest){
105     big_endian_store_16(transport_pdu->network_header, 7, dest);
106 }
107 
108 // lower transport
109 
110 // prototypes
111 
112 static void mesh_lower_transport_run(void);
113 static void mesh_lower_transport_outgoing_complete(void);
114 static void mesh_lower_transport_network_pdu_sent(mesh_network_pdu_t *network_pdu);
115 static void mesh_lower_transport_segment_transmission_timeout(btstack_timer_source_t * ts);
116 
117 // state
118 static int                    lower_transport_retry_count;
119 
120 // lower transport incoming
121 static btstack_linked_list_t  lower_transport_incoming;
122 
123 // lower transport ougoing
124 static btstack_linked_list_t lower_transport_outgoing;
125 
126 static mesh_transport_pdu_t * lower_transport_outgoing_pdu;
127 static mesh_network_pdu_t   * lower_transport_outgoing_segment;
128 static uint16_t               lower_transport_outgoing_seg_o;
129 
130 static void mesh_lower_transport_process_segment_acknowledgement_message(mesh_network_pdu_t *network_pdu){
131     if (lower_transport_outgoing_pdu == NULL) return;
132 
133     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
134     uint16_t seq_zero_pdu = big_endian_read_16(lower_transport_pdu, 1) >> 2;
135     uint16_t seq_zero_out = mesh_transport_seq(lower_transport_outgoing_pdu) & 0x1fff;
136     uint32_t block_ack = big_endian_read_32(lower_transport_pdu, 3);
137 
138 #ifdef LOG_LOWER_TRANSPORT
139     printf("[+] Segment Acknowledgment message with seq_zero %06x, block_ack %08x - outgoing seq %06x, block_ack %08x\n",
140            seq_zero_pdu, block_ack, seq_zero_out, lower_transport_outgoing_pdu->block_ack);
141 #endif
142 
143     if (block_ack == 0){
144         // If a Segment Acknowledgment message with the BlockAck field set to 0x00000000 is received,
145         // then the Upper Transport PDU shall be immediately cancelled and the higher layers shall be notified that
146         // the Upper Transport PDU has been cancelled.
147 #ifdef LOG_LOWER_TRANSPORT
148         printf("[+] Block Ack == 0 => Abort\n");
149 #endif
150         mesh_lower_transport_outgoing_complete();
151         return;
152     }
153     if (seq_zero_pdu != seq_zero_out){
154 
155 #ifdef LOG_LOWER_TRANSPORT
156         printf("[!] Seq Zero doesn't match\n");
157 #endif
158         return;
159     }
160 
161     lower_transport_outgoing_pdu->block_ack &= ~block_ack;
162 #ifdef LOG_LOWER_TRANSPORT
163     printf("[+] Updated block_ack %08x\n", lower_transport_outgoing_pdu->block_ack);
164 #endif
165 
166     if (lower_transport_outgoing_pdu->block_ack == 0){
167 #ifdef LOG_LOWER_TRANSPORT
168         printf("[+] Sent complete\n");
169 #endif
170         mesh_lower_transport_outgoing_complete();
171     }
172 }
173 
174 static void mesh_lower_transport_process_unsegmented_control_message(mesh_network_pdu_t *network_pdu){
175     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
176     uint8_t  opcode = lower_transport_pdu[0];
177 
178 #ifdef LOG_LOWER_TRANSPORT
179     printf("Unsegmented Control message, outgoing message %p, opcode %x\n", lower_transport_outgoing_pdu, opcode);
180 #endif
181 
182     switch (opcode){
183         case 0:
184             mesh_lower_transport_process_segment_acknowledgement_message(network_pdu);
185             mesh_network_message_processed_by_higher_layer(network_pdu);
186             break;
187         default:
188             higher_layer_handler(MESH_TRANSPORT_PDU_RECEIVED, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t *) network_pdu);
189             break;
190     }
191 }
192 
193 // ack / incomplete message
194 
195 static void mesh_lower_transport_setup_segmented_acknowledge_message(uint8_t * data, uint8_t obo, uint16_t seq_zero, uint32_t block_ack){
196     // printf("ACK Upper Transport, seq_zero %x\n", seq_zero);
197     data[0] = 0;    // SEG = 0, Opcode = 0
198     big_endian_store_16( data, 1, (obo << 15) | (seq_zero << 2) | 0);    // OBO, SeqZero, RFU
199     big_endian_store_32( data, 3, block_ack);
200 #ifdef LOG_LOWER_TRANSPORT
201     mesh_print_hex("ACK Upper Transport", data, 7);
202 #endif
203 }
204 
205 static void mesh_lower_transport_send_ack(uint16_t netkey_index, uint8_t ttl, uint16_t dest, uint16_t seq_zero, uint32_t block_ack){
206     // setup ack message
207     uint8_t  ack_msg[7];
208     mesh_lower_transport_setup_segmented_acknowledge_message(ack_msg, 0, seq_zero, block_ack);
209     //
210     // "3.4.5.2: The output filter of the interface connected to advertising or GATT bearers shall drop all messages with TTL value set to 1."
211     // if (ttl <= 1) return 0;
212 
213     // TODO: check transport_pdu_len depending on ctl
214 
215     // lookup network by netkey_index
216     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
217     if (!network_key) return;
218 
219     // allocate network_pdu
220     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
221     if (!network_pdu) return;
222 
223     // setup network_pdu
224     mesh_network_setup_pdu(network_pdu, netkey_index, network_key->nid, 1, ttl, mesh_sequence_number_next(), mesh_node_get_primary_element_address(), dest, ack_msg, sizeof(ack_msg));
225 
226     // send network_pdu
227     mesh_network_send_pdu(network_pdu);
228 }
229 
230 static void mesh_lower_transport_send_ack_for_transport_pdu(mesh_transport_pdu_t *transport_pdu){
231     uint16_t seq_zero = mesh_transport_seq_zero(transport_pdu);
232     uint8_t ttl = mesh_transport_ttl(transport_pdu);
233     uint16_t dest = mesh_transport_src(transport_pdu);
234     uint16_t netkey_index = transport_pdu->netkey_index;
235 #ifdef LOG_LOWER_TRANSPORT
236     printf("mesh_transport_send_ack_for_transport_pdu %p with netkey_index %x, TTL = %u, SeqZero = %x, SRC = %x, DST = %x\n",
237            transport_pdu, netkey_index, ttl, seq_zero, mesh_node_get_primary_element_address(), dest);
238 #endif
239     mesh_lower_transport_send_ack(netkey_index, ttl, dest, seq_zero, transport_pdu->block_ack);
240 }
241 
242 static void mesh_lower_transport_send_ack_for_network_pdu(mesh_network_pdu_t *network_pdu, uint16_t seq_zero, uint32_t block_ack) {
243     uint8_t ttl = mesh_network_ttl(network_pdu);
244     uint16_t dest = mesh_network_src(network_pdu);
245     uint16_t netkey_index = network_pdu->netkey_index;
246 #ifdef LOG_LOWER_TRANSPORT
247     printf("mesh_transport_send_ack_for_network_pdu %p with netkey_index %x, TTL = %u, SeqZero = %x, SRC = %x, DST = %x\n",
248            network_pdu, netkey_index, ttl, seq_zero, mesh_node_get_primary_element_address(), dest);
249 #endif
250     mesh_lower_transport_send_ack(netkey_index, ttl, dest, seq_zero, block_ack);
251 }
252 
253 static void mesh_lower_transport_stop_acknowledgment_timer(mesh_transport_pdu_t *transport_pdu){
254     if (!transport_pdu->acknowledgement_timer_active) return;
255     transport_pdu->acknowledgement_timer_active = 0;
256     btstack_run_loop_remove_timer(&transport_pdu->acknowledgement_timer);
257 }
258 
259 static void mesh_lower_transport_stop_incomplete_timer(mesh_transport_pdu_t *transport_pdu){
260     if (!transport_pdu->incomplete_timer_active) return;
261     transport_pdu->incomplete_timer_active = 0;
262     btstack_run_loop_remove_timer(&transport_pdu->incomplete_timer);
263 }
264 
265 // stops timers and updates reassembly engine
266 static void mesh_lower_transport_rx_segmented_message_complete(mesh_transport_pdu_t *transport_pdu){
267     // set flag
268     transport_pdu->message_complete = 1;
269     // stop timers
270     mesh_lower_transport_stop_acknowledgment_timer(transport_pdu);
271     mesh_lower_transport_stop_incomplete_timer(transport_pdu);
272     // stop reassembly
273     mesh_peer_t * peer = mesh_peer_for_addr(mesh_transport_src(transport_pdu));
274     if (peer){
275         peer->transport_pdu = NULL;
276     }
277 }
278 
279 static void mesh_lower_transport_rx_ack_timeout(btstack_timer_source_t *ts){
280     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) btstack_run_loop_get_timer_context(ts);
281 #ifdef LOG_LOWER_TRANSPORT
282     printf("ACK: acknowledgement timer fired for %p, send ACK\n", transport_pdu);
283 #endif
284     transport_pdu->acknowledgement_timer_active = 0;
285     mesh_lower_transport_send_ack_for_transport_pdu(transport_pdu);
286 }
287 
288 static void mesh_lower_transport_rx_incomplete_timeout(btstack_timer_source_t *ts){
289     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) btstack_run_loop_get_timer_context(ts);
290 #ifdef LOG_LOWER_TRANSPORT
291     printf("mesh_transport_rx_incomplete_timeout for %p - give up\n", transport_pdu);
292 #endif
293     mesh_lower_transport_rx_segmented_message_complete(transport_pdu);
294     // free message
295     btstack_memory_mesh_transport_pdu_free(transport_pdu);
296 }
297 
298 static void mesh_lower_transport_start_rx_acknowledgment_timer(mesh_transport_pdu_t *transport_pdu, uint32_t timeout){
299 #ifdef LOG_LOWER_TRANSPORT
300     printf("ACK: start rx ack timer for %p, timeout %u ms\n", transport_pdu, (int) timeout);
301 #endif
302     btstack_run_loop_set_timer(&transport_pdu->acknowledgement_timer, timeout);
303     btstack_run_loop_set_timer_handler(&transport_pdu->acknowledgement_timer, &mesh_lower_transport_rx_ack_timeout);
304     btstack_run_loop_set_timer_context(&transport_pdu->acknowledgement_timer, transport_pdu);
305     btstack_run_loop_add_timer(&transport_pdu->acknowledgement_timer);
306     transport_pdu->acknowledgement_timer_active = 1;
307 }
308 
309 static void mesh_lower_transport_tx_restart_segment_transmission_timer(void){
310     // restart segment transmission timer for unicast dst
311     // - "This timer shall be set to a minimum of 200 + 50 * TTL milliseconds."
312     uint32_t timeout = 200 + 50 * mesh_transport_ttl(lower_transport_outgoing_pdu);
313     if (lower_transport_outgoing_pdu->acknowledgement_timer_active){
314         btstack_run_loop_remove_timer(&lower_transport_outgoing_pdu->acknowledgement_timer);
315     }
316 
317 #ifdef LOG_LOWER_TRANSPORT
318     printf("ACK: start segment transmission timer for %p, timeout %u ms\n", lower_transport_outgoing_pdu, (int) timeout);
319 #endif
320 
321     btstack_run_loop_set_timer(&lower_transport_outgoing_pdu->acknowledgement_timer, timeout);
322     btstack_run_loop_set_timer_handler(&lower_transport_outgoing_pdu->acknowledgement_timer, &mesh_lower_transport_segment_transmission_timeout);
323     btstack_run_loop_add_timer(&lower_transport_outgoing_pdu->acknowledgement_timer);
324     lower_transport_outgoing_pdu->acknowledgement_timer_active = 1;
325 }
326 
327 static void mesh_lower_transport_restart_incomplete_timer(mesh_transport_pdu_t *transport_pdu, uint32_t timeout,
328                                                           void (*callback)(btstack_timer_source_t *ts)){
329 #ifdef LOG_LOWER_TRANSPORT
330     printf("RX-(re)start incomplete timer for %p, timeout %u ms\n", transport_pdu, (int) timeout);
331 #endif
332     if (transport_pdu->incomplete_timer_active){
333         btstack_run_loop_remove_timer(&transport_pdu->incomplete_timer);
334     }
335     btstack_run_loop_set_timer(&transport_pdu->incomplete_timer, timeout);
336     btstack_run_loop_set_timer_handler(&transport_pdu->incomplete_timer, callback);
337     btstack_run_loop_set_timer_context(&transport_pdu->incomplete_timer, transport_pdu);
338     btstack_run_loop_add_timer(&transport_pdu->incomplete_timer);
339     transport_pdu->incomplete_timer_active = 1;
340 }
341 
342 static void mesh_lower_transport_outgoing_complete(void){
343 #ifdef LOG_LOWER_TRANSPORT
344     printf("mesh_lower_transport_outgoing_complete %p, ack timer active %u, incomplete active %u\n", lower_transport_outgoing_pdu,
345         lower_transport_outgoing_pdu->acknowledgement_timer_active, lower_transport_outgoing_pdu->incomplete_timer_active);
346 #endif
347     // stop timers
348     mesh_lower_transport_stop_acknowledgment_timer(lower_transport_outgoing_pdu);
349     mesh_lower_transport_stop_incomplete_timer(lower_transport_outgoing_pdu);
350     // notify upper transport
351     mesh_transport_pdu_t * pdu   = lower_transport_outgoing_pdu;
352     lower_transport_outgoing_pdu = NULL;
353     higher_layer_handler(MESH_TRANSPORT_PDU_SENT, MESH_TRANSPORT_STATUS_SEND_ABORT_BY_REMOTE, (mesh_pdu_t *) pdu);
354 }
355 
356 static mesh_transport_pdu_t * mesh_lower_transport_pdu_for_segmented_message(mesh_network_pdu_t *network_pdu){
357     uint16_t src = mesh_network_src(network_pdu);
358     uint16_t seq_zero = ( big_endian_read_16(mesh_network_pdu_data(network_pdu), 1) >> 2) & 0x1fff;
359 #ifdef LOG_LOWER_TRANSPORT
360     printf("mesh_transport_pdu_for_segmented_message: seq_zero %x\n", seq_zero);
361 #endif
362     mesh_peer_t * peer = mesh_peer_for_addr(src);
363     if (!peer) {
364         return NULL;
365     }
366 #ifdef LOG_LOWER_TRANSPORT
367     printf("mesh_seq_zero_validate(%x, %x) -- last (%x, %x)\n", src, seq_zero, peer->address, peer->seq_zero);
368 #endif
369 
370     // reception of transport message ongoing
371     if (peer->transport_pdu){
372         // check if segment for same seq zero
373         uint16_t active_seq_zero = mesh_transport_seq_zero(peer->transport_pdu);
374         if (active_seq_zero == seq_zero) {
375 #ifdef LOG_LOWER_TRANSPORT
376             printf("mesh_transport_pdu_for_segmented_message: segment for current transport pdu with SeqZero %x\n", active_seq_zero);
377 #endif
378             return peer->transport_pdu;
379         } else {
380             // seq zero differs from current transport pdu, but current pdu is not complete
381 #ifdef LOG_LOWER_TRANSPORT
382             printf("mesh_transport_pdu_for_segmented_message: drop segment. current transport pdu SeqZero %x, now %x\n", active_seq_zero, seq_zero);
383 #endif
384             return NULL;
385         }
386     }
387 
388     // send ACK if segment for previously completed transport pdu (no ongoing reception, block ack is cleared)
389     if ((seq_zero == peer->seq_zero) && (peer->block_ack != 0)){
390 #ifdef LOG_LOWER_TRANSPORT
391         printf("mesh_transport_pdu_for_segmented_message: segment for last completed message. send ack\n");
392 #endif
393         mesh_lower_transport_send_ack_for_network_pdu(network_pdu, seq_zero, peer->block_ack);
394         return NULL;
395     }
396 
397     // reconstruct lowest 24 bit of SeqAuth
398     uint32_t seq = mesh_network_seq(network_pdu);
399     uint32_t seq_auth = (seq & 0xffe000) | seq_zero;
400     if (seq_auth > seq){
401         seq_auth -= 0x2000;
402     }
403 
404     // no transport pdu active, check new message: seq auth is greater OR seq auth is same but no segments
405     if (seq_auth > peer->seq_auth || (seq_auth == peer->seq_auth && peer->block_ack == 0)){
406         mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
407         if (!pdu) return NULL;
408 
409         // cache network pdu header
410         memcpy(pdu->network_header, network_pdu->data, 9);
411         // store lower 24 bit of SeqAuth for App / Device Nonce
412         big_endian_store_24(pdu->network_header, 2, seq_auth);
413 
414         // store meta data in new pdu
415         pdu->netkey_index = network_pdu->netkey_index;
416         pdu->block_ack = 0;
417         pdu->acknowledgement_timer_active = 0;
418         pdu->message_complete = 0;
419         pdu->seq_zero = seq_zero;
420 
421         // update peer info
422         peer->transport_pdu = pdu;
423         peer->seq_zero      = seq_zero;
424         peer->seq_auth      = seq_auth;
425         peer->block_ack     = 0;
426 
427 #ifdef LOG_LOWER_TRANSPORT
428         printf("mesh_transport_pdu_for_segmented_message: setup transport pdu %p for src %x, seq %06x, seq_zero %x\n", pdu, src, mesh_transport_seq(pdu), seq_zero);
429 #endif
430         return peer->transport_pdu;
431     }  else {
432         // seq zero differs from current transport pdu
433 #ifdef LOG_LOWER_TRANSPORT
434         printf("mesh_transport_pdu_for_segmented_message: drop segment for old seq %x\n", seq_zero);
435 #endif
436         return NULL;
437     }
438 }
439 
440 static void mesh_lower_transport_process_segment( mesh_transport_pdu_t * transport_pdu, mesh_network_pdu_t * network_pdu){
441 
442     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
443     uint8_t   lower_transport_pdu_len = mesh_network_pdu_len(network_pdu);
444 
445     // get akf_aid & transmic
446     transport_pdu->akf_aid_control = lower_transport_pdu[0] & 0x7f;
447     transport_pdu->transmic_len    = lower_transport_pdu[1] & 0x80 ? 8 : 4;
448 
449     // get seq_zero
450     uint16_t seq_zero =  ( big_endian_read_16(lower_transport_pdu, 1) >> 2) & 0x1fff;
451 
452     // get seg fields
453     uint8_t  seg_o    =  ( big_endian_read_16(lower_transport_pdu, 2) >> 5) & 0x001f;
454     uint8_t  seg_n    =  lower_transport_pdu[3] & 0x1f;
455     uint8_t   segment_len  =  lower_transport_pdu_len - 4;
456     uint8_t * segment_data = &lower_transport_pdu[4];
457 
458 #ifdef LOG_LOWER_TRANSPORT
459     printf("mesh_lower_transport_process_segment: seq zero %04x, seg_o %02x, seg_n %02x, transmic len: %u\n", seq_zero, seg_o, seg_n, transport_pdu->transmic_len * 8);
460     mesh_print_hex("Segment", segment_data, segment_len);
461 #endif
462 
463     // store segment
464     memcpy(&transport_pdu->data[seg_o * 12], segment_data, 12);
465     // mark as received
466     transport_pdu->block_ack |= (1<<seg_o);
467     // last segment -> store len
468     if (seg_o == seg_n){
469         transport_pdu->len = (seg_n * 12) + segment_len;
470 #ifdef LOG_LOWER_TRANSPORT
471         printf("Assembled payload len %u\n", transport_pdu->len);
472 #endif
473     }
474 
475     // check for complete
476     int i;
477     for (i=0;i<=seg_n;i++){
478         if ( (transport_pdu->block_ack & (1<<i)) == 0) return;
479     }
480 
481 #ifdef LOG_LOWER_TRANSPORT
482     mesh_print_hex("Assembled payload", transport_pdu->data, transport_pdu->len);
483 #endif
484 
485     // mark as done
486     mesh_lower_transport_rx_segmented_message_complete(transport_pdu);
487 
488     // store block ack in peer info
489     mesh_peer_t * peer = mesh_peer_for_addr(mesh_transport_src(transport_pdu));
490     // TODO: check if NULL check can be removed
491     if (peer){
492         peer->block_ack = transport_pdu->block_ack;
493     }
494 
495     // send ack
496     mesh_lower_transport_send_ack_for_transport_pdu(transport_pdu);
497 
498     // forward to upper transport
499     higher_layer_handler(MESH_TRANSPORT_PDU_RECEIVED, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t*) transport_pdu);
500 }
501 
502 void mesh_lower_transport_message_processed_by_higher_layer(mesh_pdu_t * pdu){
503     switch (pdu->pdu_type){
504         case MESH_PDU_TYPE_NETWORK:
505             mesh_network_message_processed_by_higher_layer((mesh_network_pdu_t *) pdu);
506             break;
507         case MESH_PDU_TYPE_TRANSPORT:
508             mesh_transport_pdu_free((mesh_transport_pdu_t *) pdu);
509             break;
510         default:
511             break;
512     }
513 }
514 
515 void mesh_lower_transport_received_message(mesh_network_callback_type_t callback_type, mesh_network_pdu_t *network_pdu){
516     mesh_peer_t * peer;
517     uint16_t src;
518     uint16_t seq;
519     switch (callback_type){
520         case MESH_NETWORK_PDU_RECEIVED:
521             src = mesh_network_src(network_pdu);
522             seq = mesh_network_seq(network_pdu);
523             peer = mesh_peer_for_addr(src);
524 #ifdef LOG_LOWER_TRANSPORT
525             printf("Transport: received message. SRC %x, SEQ %x\n", src, seq);
526 #endif
527             // validate seq
528             if (peer && seq > peer->seq){
529                 // track seq
530                 peer->seq = seq;
531                 // add to list and go
532                 btstack_linked_list_add_tail(&lower_transport_incoming, (btstack_linked_item_t *) network_pdu);
533                 mesh_lower_transport_run();
534             } else {
535                 // drop packet
536 #ifdef LOG_LOWER_TRANSPORT
537                 printf("Transport: drop packet - src/seq auth failed\n");
538 #endif
539                 mesh_network_message_processed_by_higher_layer(network_pdu);
540             }
541             break;
542         case MESH_NETWORK_PDU_SENT:
543             mesh_lower_transport_network_pdu_sent(network_pdu);
544             break;
545         default:
546             break;
547     }
548 }
549 
550 static void mesh_lower_transport_setup_segment(mesh_transport_pdu_t *transport_pdu, uint8_t seg_o, mesh_network_pdu_t *network_pdu){
551 
552     int ctl = mesh_transport_ctl(transport_pdu);
553     uint16_t max_segment_len = ctl ? 8 : 12;    // control 8 bytes (64 bit NetMic), access 12 bytes (32 bit NetMIC)
554 
555     uint32_t seq      = mesh_sequence_number_next();
556     uint16_t seq_zero = mesh_transport_seq(transport_pdu) & 0x01fff;
557     uint8_t  seg_n    = (transport_pdu->len - 1) / max_segment_len;
558     uint8_t  szmic    = ((!ctl) && (transport_pdu->transmic_len == 8)) ? 1 : 0; // only 1 for access messages with 64 bit TransMIC
559     uint8_t  nid      = mesh_transport_nid(transport_pdu);
560     uint8_t  ttl      = mesh_transport_ttl(transport_pdu);
561     uint16_t src      = mesh_transport_src(transport_pdu);
562     uint16_t dest     = mesh_transport_dst(transport_pdu);
563 
564     // current segment.
565     uint16_t seg_offset = seg_o * max_segment_len;
566 
567     uint8_t lower_transport_pdu_data[16];
568     lower_transport_pdu_data[0] = 0x80 |  transport_pdu->akf_aid_control;
569     big_endian_store_24(lower_transport_pdu_data, 1, (szmic << 23) | (seq_zero << 10) | (seg_o << 5) | seg_n);
570     uint16_t segment_len = btstack_min(transport_pdu->len - seg_offset, max_segment_len);
571     memcpy(&lower_transport_pdu_data[4], &transport_pdu->data[seg_offset], segment_len);
572     uint16_t lower_transport_pdu_len = 4 + segment_len;
573 
574     mesh_network_setup_pdu(network_pdu, transport_pdu->netkey_index, nid, 0, ttl, seq, src, dest, lower_transport_pdu_data, lower_transport_pdu_len);
575 }
576 
577 static void mesh_lower_transport_send_next_segment(void){
578     if (!lower_transport_outgoing_pdu) return;
579 
580     int ctl = mesh_transport_ctl(lower_transport_outgoing_pdu);
581     uint16_t max_segment_len = ctl ? 8 : 12;    // control 8 bytes (64 bit NetMic), access 12 bytes (32 bit NetMIC)
582     uint8_t  seg_n = (lower_transport_outgoing_pdu->len - 1) / max_segment_len;
583 
584     // find next unacknowledged segement
585     while ((lower_transport_outgoing_seg_o <= seg_n) && ((lower_transport_outgoing_pdu->block_ack & (1 << lower_transport_outgoing_seg_o)) == 0)){
586         lower_transport_outgoing_seg_o++;
587     }
588 
589     if (lower_transport_outgoing_seg_o > seg_n){
590 #ifdef LOG_LOWER_TRANSPORT
591         printf("[+] Lower Transport, send segmented pdu complete (dst %x)\n", mesh_transport_dst(lower_transport_outgoing_pdu));
592 #endif
593         lower_transport_outgoing_seg_o   = 0;
594 
595         // done for unicast, ack timer already set, too
596         if (mesh_network_address_unicast(mesh_transport_dst(lower_transport_outgoing_pdu))) return;
597 
598         // done, more?
599         if (lower_transport_retry_count == 0){
600 #ifdef LOG_LOWER_TRANSPORT
601             printf("[+] Lower Transport, message unacknowledged -> free\n");
602 #endif
603             // notify upper transport
604             mesh_lower_transport_outgoing_complete();
605             return;
606         }
607 
608         // start retry
609 #ifdef LOG_LOWER_TRANSPORT
610         printf("[+] Lower Transport, message unacknowledged retry count %u\n", lower_transport_retry_count);
611 #endif
612         lower_transport_retry_count--;
613     }
614 
615     // restart segment transmission timer for unicast dst
616     if (mesh_network_address_unicast(mesh_transport_dst(lower_transport_outgoing_pdu))){
617         mesh_lower_transport_tx_restart_segment_transmission_timer();
618     }
619 
620     mesh_lower_transport_setup_segment(lower_transport_outgoing_pdu, lower_transport_outgoing_seg_o,
621                                        lower_transport_outgoing_segment);
622 
623 #ifdef LOG_LOWER_TRANSPORT
624     printf("[+] Lower Transport, send segmented pdu: seg_o %x, seg_n %x\n", lower_transport_outgoing_seg_o, seg_n);
625     mesh_print_hex("LowerTransportPDU", &lower_transport_outgoing_segment->data[9], lower_transport_outgoing_segment->len-9);
626 #endif
627 
628     // next segment
629     lower_transport_outgoing_seg_o++;
630 
631     // send network pdu
632     mesh_network_send_pdu(lower_transport_outgoing_segment);
633 }
634 
635 static void mesh_lower_transport_network_pdu_sent(mesh_network_pdu_t *network_pdu){
636     // figure out what pdu was sent
637 
638     // single segment of segmented message?
639     if (lower_transport_outgoing_segment == network_pdu){
640         mesh_lower_transport_send_next_segment();
641         return;
642     }
643 
644     // Segment Acknowledgment message sent by us?
645     if (mesh_network_control(network_pdu) && network_pdu->data[0] == 0){
646         btstack_memory_mesh_network_pdu_free(network_pdu);
647         return;
648     }
649 
650     // other
651     higher_layer_handler(MESH_TRANSPORT_PDU_SENT, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t *) network_pdu);
652 }
653 
654 static void mesh_lower_transport_setup_block_ack(mesh_transport_pdu_t *transport_pdu){
655     // setup block ack - set bit for segment to send, will be cleared on ack
656     int      ctl = mesh_transport_ctl(transport_pdu);
657     uint16_t max_segment_len = ctl ? 8 : 12;    // control 8 bytes (64 bit NetMic), access 12 bytes (32 bit NetMIC)
658     uint8_t  seg_n = (transport_pdu->len - 1) / max_segment_len;
659     if (seg_n < 31){
660         transport_pdu->block_ack = (1 << (seg_n+1)) - 1;
661     } else {
662         transport_pdu->block_ack = 0xffffffff;
663     }
664 }
665 
666 static void mesh_lower_transport_send_current_segmented_pdu_once(void){
667     printf("[+] Lower Transport, send segmented pdu (retry count %u)\n", lower_transport_retry_count);
668     lower_transport_retry_count--;
669 
670     // start sending
671     lower_transport_outgoing_seg_o   = 0;
672     mesh_lower_transport_send_next_segment();
673 }
674 
675 void mesh_lower_transport_send_pdu(mesh_pdu_t *pdu){
676     if (pdu->pdu_type == MESH_PDU_TYPE_NETWORK){
677         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) pdu;
678         // network pdu without payload = 9 bytes
679         if (network_pdu->len < 9){
680             printf("too short, %u\n", network_pdu->len);
681             while(1);
682         }
683     }
684     btstack_linked_list_add_tail(&lower_transport_outgoing, (btstack_linked_item_t*) pdu);
685     mesh_lower_transport_run();
686 }
687 
688 static void mesh_lower_transport_segment_transmission_timeout(btstack_timer_source_t * ts){
689     UNUSED(ts);
690 #ifdef LOG_LOWER_TRANSPORT
691     printf("[+] Lower transport, segment transmission timer fired for %p\n", lower_transport_outgoing_pdu);
692 #endif
693     lower_transport_outgoing_pdu->acknowledgement_timer_active = 0;
694 
695     // once more?
696     if (lower_transport_retry_count == 0){
697         printf("[!] Lower transport, send segmented pdu failed, retries exhausted\n");
698         mesh_lower_transport_outgoing_complete();
699         return;
700     }
701 
702     // send remaining segments again
703     mesh_lower_transport_send_current_segmented_pdu_once();
704 }
705 
706 static void mesh_lower_transport_run(void){
707     while(!btstack_linked_list_empty(&lower_transport_incoming)){
708         // get next message
709         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&lower_transport_incoming);
710         // segmented?
711         if (mesh_network_segmented(network_pdu)){
712             mesh_transport_pdu_t * transport_pdu = mesh_lower_transport_pdu_for_segmented_message(network_pdu);
713             if (transport_pdu) {
714                 // start acknowledgment timer if inactive
715                 if (transport_pdu->acknowledgement_timer_active == 0){
716                     // - "The acknowledgment timer shall be set to a minimum of 150 + 50 * TTL milliseconds"
717                     uint32_t timeout = 150 + 50 * mesh_network_ttl(network_pdu);
718                     mesh_lower_transport_start_rx_acknowledgment_timer(transport_pdu, timeout);
719                 }
720                 // restart incomplete timer
721                 mesh_lower_transport_restart_incomplete_timer(transport_pdu, 10000, &mesh_lower_transport_rx_incomplete_timeout);
722                 mesh_lower_transport_process_segment(transport_pdu, network_pdu);
723             }
724             mesh_network_message_processed_by_higher_layer(network_pdu);
725         } else {
726             // control?
727             if (mesh_network_control(network_pdu)){
728                 // unsegmented control message (not encrypted)
729                 mesh_lower_transport_process_unsegmented_control_message(network_pdu);
730             } else {
731                 // unsegmented access message (encrypted)
732                 higher_layer_handler(MESH_TRANSPORT_PDU_RECEIVED, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t *) network_pdu);
733             }
734         }
735     }
736 
737     // check if outgoing segmented pdu is active
738     if (lower_transport_outgoing_pdu) return;
739 
740     while(!btstack_linked_list_empty(&lower_transport_outgoing)) {
741         // get next message
742         mesh_transport_pdu_t * transport_pdu;
743         mesh_network_pdu_t   * network_pdu;
744         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_pop(&lower_transport_outgoing);
745         switch (pdu->pdu_type) {
746             case MESH_PDU_TYPE_NETWORK:
747                 network_pdu = (mesh_network_pdu_t *) pdu;
748                 mesh_network_send_pdu(network_pdu);
749                 break;
750             case MESH_PDU_TYPE_TRANSPORT:
751                 transport_pdu = (mesh_transport_pdu_t *) pdu;
752                 // start sending segmented pdu
753                 lower_transport_retry_count = 2;
754                 lower_transport_outgoing_pdu = transport_pdu;
755                 mesh_lower_transport_setup_block_ack(transport_pdu);
756                 mesh_lower_transport_send_current_segmented_pdu_once();
757                 return;
758             default:
759                 break;
760         }
761     }
762 }
763 
764 static void mesh_lower_transport_dump_network_pdus(const char *name, btstack_linked_list_t *list){
765     printf("List: %s:\n", name);
766     btstack_linked_list_iterator_t it;
767     btstack_linked_list_iterator_init(&it, list);
768     while (btstack_linked_list_iterator_has_next(&it)){
769         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
770         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
771     }
772 }
773 static void mesh_lower_transport_reset_network_pdus(btstack_linked_list_t *list){
774     while (!btstack_linked_list_empty(list)){
775         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
776         btstack_memory_mesh_network_pdu_free(pdu);
777     }
778 }
779 
780 void mesh_lower_transport_dump(void){
781     mesh_lower_transport_dump_network_pdus("lower_transport_incoming", &lower_transport_incoming);
782 }
783 
784 void mesh_lower_transport_reset(void){
785     mesh_lower_transport_reset_network_pdus(&lower_transport_incoming);
786     if (lower_transport_outgoing_pdu){
787         mesh_transport_pdu_free(lower_transport_outgoing_pdu);
788         lower_transport_outgoing_pdu = NULL;
789     }
790     mesh_network_pdu_free(lower_transport_outgoing_segment);
791     lower_transport_outgoing_segment = NULL;
792 }
793 
794 void mesh_lower_transport_init(){
795     // register with network layer
796     mesh_network_set_higher_layer_handler(&mesh_lower_transport_received_message);
797     // allocate network_pdu for segmentation
798     lower_transport_outgoing_segment = mesh_network_pdu_get();
799 }
800 
801 void mesh_lower_transport_set_higher_layer_handler(void (*pdu_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu)){
802     higher_layer_handler = pdu_handler;
803 }
804 
805 // buffer pool
806 mesh_transport_pdu_t * mesh_transport_pdu_get(void){
807     mesh_transport_pdu_t * transport_pdu = btstack_memory_mesh_transport_pdu_get();
808     if (transport_pdu) {
809         memset(transport_pdu, 0, sizeof(mesh_transport_pdu_t));
810         transport_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_TRANSPORT;
811     }
812     return transport_pdu;
813 }
814 
815 void mesh_transport_pdu_free(mesh_transport_pdu_t * transport_pdu){
816     btstack_memory_mesh_transport_pdu_free(transport_pdu);
817 }
818