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