1 /*  Bluetooth Mesh */
2 
3 /*
4  * SPDX-FileCopyrightText: 2017 Intel Corporation
5  * SPDX-FileContributor: 2018-2024 Espressif Systems (Shanghai) CO LTD
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  */
9 
10 #include <string.h>
11 #include <errno.h>
12 
13 #include "crypto.h"
14 #include "adv.h"
15 #include "mesh.h"
16 #include "lpn.h"
17 #include "friend.h"
18 #include "access.h"
19 #include "foundation.h"
20 #include "settings.h"
21 #include "transport.h"
22 #include "mesh_main.h"
23 #include "mesh_common.h"
24 #include "cfg_srv.h"
25 
26 /* The transport layer needs at least three buffers for itself to avoid
27  * deadlocks. Ensure that there are a sufficient number of advertising
28  * buffers available compared to the maximum supported outgoing segment
29  * count.
30  */
31 _Static_assert(CONFIG_BLE_MESH_ADV_BUF_COUNT >= (CONFIG_BLE_MESH_TX_SEG_MAX + 3),
32                "Too small BLE Mesh adv buffer count");
33 
34 #define AID_MASK                    ((uint8_t)(BIT_MASK(6)))
35 
36 #define SEG(data)                   ((data)[0] >> 7)
37 #define AKF(data)                   (((data)[0] >> 6) & 0x01)
38 #define AID(data)                   ((data)[0] & AID_MASK)
39 #define ASZMIC(data)                (((data)[1] >> 7) & 1)
40 
41 #define APP_MIC_LEN(aszmic)         ((aszmic) ? BLE_MESH_MIC_LONG : BLE_MESH_MIC_SHORT)
42 
43 #define UNSEG_HDR(akf, aid)         ((akf << 6) | (aid & AID_MASK))
44 #define SEG_HDR(akf, aid)           (UNSEG_HDR(akf, aid) | 0x80)
45 
46 #define BLOCK_COMPLETE(seg_n)       (uint32_t)(((uint64_t)1 << (seg_n + 1)) - 1)
47 
48 #define SEQ_AUTH(iv_index, seq)     (((uint64_t)iv_index) << 24 | (uint64_t)seq)
49 
50 /* Number of retransmit attempts (after the initial transmit) per segment */
51 #define SEG_RETRANSMIT_ATTEMPTS     4
52 
53 /* "This timer shall be set to a minimum of 200 + 50 * TTL milliseconds.".
54  * We use 400 since 300 is a common send duration for standard HCI, and we
55  * need to have a timeout that's bigger than that.
56  */
57 #define SEG_RETRANSMIT_TIMEOUT_UNICAST(tx)  (K_MSEC(400) + 50 * (tx)->ttl)
58 /* When sending to a group, the messages are not acknowledged, and there's no
59  * reason to delay the repetitions significantly. Delaying by more than 0 ms
60  * to avoid flooding the network.
61  */
62 #define SEG_RETRANSMIT_TIMEOUT_GROUP        K_MSEC(50)
63 
64 #define SEG_RETRANSMIT_TIMEOUT(tx)                  \
65             (BLE_MESH_ADDR_IS_UNICAST((tx)->dst) ?  \
66             SEG_RETRANSMIT_TIMEOUT_UNICAST(tx) :    \
67             SEG_RETRANSMIT_TIMEOUT_GROUP)
68 
69 /* How long to wait for available buffers before giving up */
70 #define BUF_TIMEOUT                 K_NO_WAIT
71 
72 static struct seg_tx {
73     struct bt_mesh_subnet *sub;
74     struct net_buf        *seg[CONFIG_BLE_MESH_TX_SEG_MAX];
75     uint64_t               seq_auth;
76     uint16_t               dst;
77     uint8_t                seg_n:5,     /* Last segment index */
78                            new_key:1;   /* New/old key */
79     uint8_t                nack_count;  /* Number of unacked segs */
80     uint8_t                ttl;
81     uint8_t                seg_pending; /* Number of segments pending */
82     uint8_t                attempts;    /* Transmit attempts */
83     const struct bt_mesh_send_cb *cb;
84     void                  *cb_data;
85     struct k_delayed_work  retransmit;  /* Retransmit timer */
86 } seg_tx[CONFIG_BLE_MESH_TX_SEG_MSG_COUNT];
87 
88 static struct seg_rx {
89     struct bt_mesh_subnet *sub;
90     uint64_t               seq_auth;
91     uint8_t                seg_n:5,
92                            ctl:1,
93                            in_use:1,
94                            obo:1;
95     uint8_t                hdr;
96     uint8_t                ttl;
97     uint16_t               src;
98     uint16_t               dst;
99     uint32_t               block;
100     uint32_t               last;
101     struct k_delayed_work  ack;
102     struct net_buf_simple  buf;
103 } seg_rx[CONFIG_BLE_MESH_RX_SEG_MSG_COUNT] = {
104     [0 ... (CONFIG_BLE_MESH_RX_SEG_MSG_COUNT - 1)] = {
105         .buf.size = CONFIG_BLE_MESH_RX_SDU_MAX,
106     },
107 };
108 
109 static uint8_t seg_rx_buf_data[(CONFIG_BLE_MESH_RX_SEG_MSG_COUNT *
110                                 CONFIG_BLE_MESH_RX_SDU_MAX)];
111 
112 static uint16_t hb_sub_dst = BLE_MESH_ADDR_UNASSIGNED;
113 
114 static bt_mesh_mutex_t tx_seg_lock;
115 static bt_mesh_mutex_t rx_seg_lock;
116 
bt_mesh_tx_seg_mutex_new(void)117 static inline void bt_mesh_tx_seg_mutex_new(void)
118 {
119     if (!tx_seg_lock.mutex) {
120         bt_mesh_mutex_create(&tx_seg_lock);
121     }
122 }
123 
124 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_tx_seg_mutex_free(void)125 static inline void bt_mesh_tx_seg_mutex_free(void)
126 {
127     bt_mesh_mutex_free(&tx_seg_lock);
128 }
129 #endif /* CONFIG_BLE_MESH_DEINIT */
130 
bt_mesh_tx_seg_lock(void)131 static inline void bt_mesh_tx_seg_lock(void)
132 {
133     bt_mesh_mutex_lock(&tx_seg_lock);
134 }
135 
bt_mesh_tx_seg_unlock(void)136 static inline void bt_mesh_tx_seg_unlock(void)
137 {
138     bt_mesh_mutex_unlock(&tx_seg_lock);
139 }
140 
bt_mesh_rx_seg_mutex_new(void)141 static inline void bt_mesh_rx_seg_mutex_new(void)
142 {
143     if (!rx_seg_lock.mutex) {
144         bt_mesh_mutex_create(&rx_seg_lock);
145     }
146 }
147 
148 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_rx_seg_mutex_free(void)149 static inline void bt_mesh_rx_seg_mutex_free(void)
150 {
151     bt_mesh_mutex_free(&rx_seg_lock);
152 }
153 #endif /* CONFIG_BLE_MESH_DEINIT */
154 
bt_mesh_rx_seg_lock(void)155 static inline void bt_mesh_rx_seg_lock(void)
156 {
157     bt_mesh_mutex_lock(&rx_seg_lock);
158 }
159 
bt_mesh_rx_seg_unlock(void)160 static inline void bt_mesh_rx_seg_unlock(void)
161 {
162     bt_mesh_mutex_unlock(&rx_seg_lock);
163 }
164 
bt_mesh_get_seg_retrans_num(void)165 uint8_t bt_mesh_get_seg_retrans_num(void)
166 {
167     return SEG_RETRANSMIT_ATTEMPTS;
168 }
169 
bt_mesh_get_seg_retrans_timeout(uint8_t ttl)170 int32_t bt_mesh_get_seg_retrans_timeout(uint8_t ttl)
171 {
172     /* This function will be used when a client model sending an
173      * acknowledged message. And if the dst of a message is not
174      * a unicast address, the function will not be invoked.
175      * So we can directly use the SEG_RETRANSMIT_TIMEOUT_UNICAST
176      * macro here.
177      */
178     struct seg_tx tx = {
179         .ttl = ttl,
180     };
181     return SEG_RETRANSMIT_TIMEOUT_UNICAST(&tx);
182 }
183 
bt_mesh_set_hb_sub_dst(uint16_t addr)184 void bt_mesh_set_hb_sub_dst(uint16_t addr)
185 {
186     hb_sub_dst = addr;
187 }
188 
send_unseg(struct bt_mesh_net_tx * tx,struct net_buf_simple * sdu,const struct bt_mesh_send_cb * cb,void * cb_data)189 static int send_unseg(struct bt_mesh_net_tx *tx, struct net_buf_simple *sdu,
190                       const struct bt_mesh_send_cb *cb, void *cb_data)
191 {
192     struct net_buf *buf = NULL;
193 
194     BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x sdu_len %u",
195            tx->src, tx->ctx->addr, tx->ctx->app_idx, sdu->len);
196 
197     buf = bt_mesh_adv_create(BLE_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT);
198     if (!buf) {
199         BT_ERR("Out of network buffers");
200         return -ENOBUFS;
201     }
202 
203     net_buf_reserve(buf, BLE_MESH_NET_HDR_LEN);
204 
205     if (tx->ctx->app_idx == BLE_MESH_KEY_DEV) {
206         net_buf_add_u8(buf, UNSEG_HDR(0, 0));
207     } else {
208         net_buf_add_u8(buf, UNSEG_HDR(1, tx->aid));
209     }
210 
211     net_buf_add_mem(buf, sdu->data, sdu->len);
212 
213     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
214         if (!bt_mesh_friend_queue_has_space(tx->sub->net_idx,
215                                             tx->src, tx->ctx->addr,
216                                             NULL, 1)) {
217             if (BLE_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
218                 BT_ERR("Not enough space in Friend Queue");
219                 net_buf_unref(buf);
220                 return -ENOBUFS;
221             } else {
222                 BT_WARN("No space in Friend Queue");
223                 goto send;
224             }
225         }
226 
227         if (bt_mesh_friend_enqueue_tx(tx, BLE_MESH_FRIEND_PDU_SINGLE,
228                                       NULL, 1, &buf->b) &&
229                 BLE_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
230             /* PDUs for a specific Friend should only go
231              * out through the Friend Queue.
232              */
233             net_buf_unref(buf);
234             send_cb_finalize(cb, cb_data);
235             return 0;
236         }
237     }
238 
239 send:
240     return bt_mesh_net_send(tx, buf, cb, cb_data);
241 }
242 
bt_mesh_tx_in_progress(void)243 bool bt_mesh_tx_in_progress(void)
244 {
245     int i;
246 
247     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
248         if (seg_tx[i].nack_count) {
249             return true;
250         }
251     }
252 
253     return false;
254 }
255 
seg_tx_done(struct seg_tx * tx,uint8_t seg_idx)256 static void seg_tx_done(struct seg_tx *tx, uint8_t seg_idx)
257 {
258     bt_mesh_adv_buf_ref_debug(__func__, tx->seg[seg_idx], 3U, BLE_MESH_BUF_REF_SMALL);
259 
260     /**
261      * When cancelling a segment that is still in the adv sending queue, `tx->seg_pending`
262      * must else be decremented by one. More detailed information
263      * can be found in BLEMESH24-26.
264      */
265     if (bt_mesh_atomic_cas(&BLE_MESH_ADV_BUSY(tx->seg[seg_idx]), 1, 0)) {
266         tx->seg_pending--;
267     }
268 
269     net_buf_unref(tx->seg[seg_idx]);
270     tx->seg[seg_idx] = NULL;
271     tx->nack_count--;
272 }
273 
seg_tx_reset(struct seg_tx * tx)274 static void seg_tx_reset(struct seg_tx *tx)
275 {
276     int i;
277 
278     bt_mesh_tx_seg_lock();
279 
280     k_delayed_work_cancel(&tx->retransmit);
281 
282     tx->cb = NULL;
283     tx->cb_data = NULL;
284     tx->seq_auth = 0U;
285     tx->sub = NULL;
286     tx->dst = BLE_MESH_ADDR_UNASSIGNED;
287 
288     for (i = 0; i <= tx->seg_n && tx->nack_count; i++) {
289         if (!tx->seg[i]) {
290             continue;
291         }
292 
293         seg_tx_done(tx, i);
294     }
295 
296     tx->nack_count = 0U;
297 
298     bt_mesh_tx_seg_unlock();
299 
300     if (bt_mesh_atomic_test_and_clear_bit(bt_mesh.flags, BLE_MESH_IVU_PENDING)) {
301         BT_DBG("Proceding with pending IV Update");
302         /* bt_mesh_net_iv_update() will re-enable the flag if this
303          * wasn't the only transfer.
304          */
305         if (bt_mesh_net_iv_update(bt_mesh.iv_index, false)) {
306             bt_mesh_net_sec_update(NULL);
307         }
308     }
309 }
310 
seg_tx_complete(struct seg_tx * tx,int err)311 static inline void seg_tx_complete(struct seg_tx *tx, int err)
312 {
313     const struct bt_mesh_send_cb *cb = tx->cb;
314     void *cb_data = tx->cb_data;
315 
316     seg_tx_reset(tx);
317 
318     if (cb && cb->end) {
319         cb->end(err, cb_data);
320     }
321 }
322 
schedule_retransmit(struct seg_tx * tx)323 static void schedule_retransmit(struct seg_tx *tx)
324 {
325     if (--tx->seg_pending) {
326         return;
327     }
328 
329     if (!BLE_MESH_ADDR_IS_UNICAST(tx->dst) && !tx->attempts) {
330         BT_INFO("Complete tx sdu to group");
331         seg_tx_complete(tx, 0);
332         return;
333     }
334 
335     k_delayed_work_submit(&tx->retransmit, SEG_RETRANSMIT_TIMEOUT(tx));
336 }
337 
seg_first_send_start(uint16_t duration,int err,void * user_data)338 static void seg_first_send_start(uint16_t duration, int err, void *user_data)
339 {
340     struct seg_tx *tx = user_data;
341 
342     if (tx->cb && tx->cb->start) {
343         tx->cb->start(duration, err, tx->cb_data);
344     }
345 }
346 
seg_send_start(uint16_t duration,int err,void * user_data)347 static void seg_send_start(uint16_t duration, int err, void *user_data)
348 {
349     struct seg_tx *tx = user_data;
350 
351     /* If there's an error in transmitting the 'sent' callback will never
352      * be called. Make sure that we kick the retransmit timer also in this
353      * case since otherwise we risk the transmission of becoming stale.
354      */
355     if (err) {
356         schedule_retransmit(tx);
357     }
358 }
359 
seg_sent(int err,void * user_data)360 static void seg_sent(int err, void *user_data)
361 {
362     struct seg_tx *tx = user_data;
363 
364     schedule_retransmit(tx);
365 }
366 
367 static const struct bt_mesh_send_cb first_sent_cb = {
368     .start = seg_first_send_start,
369     .end = seg_sent,
370 };
371 
372 static const struct bt_mesh_send_cb seg_sent_cb = {
373     .start = seg_send_start,
374     .end = seg_sent,
375 };
376 
seg_tx_send_unacked(struct seg_tx * tx)377 static void seg_tx_send_unacked(struct seg_tx *tx)
378 {
379     int i, err = 0;
380 
381     bt_mesh_tx_seg_lock();
382 
383     if (!(tx->attempts--)) {
384         BT_WARN("Ran out of retransmit attempts");
385         bt_mesh_tx_seg_unlock();
386         seg_tx_complete(tx, -ETIMEDOUT);
387         return;
388     }
389 
390     BT_INFO("Attempts: %u", tx->attempts);
391 
392     for (i = 0; i <= tx->seg_n; i++) {
393         struct net_buf *seg = tx->seg[i];
394 
395         if (!seg) {
396             continue;
397         }
398 
399         if (bt_mesh_atomic_get(&BLE_MESH_ADV_BUSY(seg))) {
400             BT_DBG("Skipping segment that's still advertising");
401             continue;
402         }
403 
404         tx->seg_pending++;
405 
406         BT_DBG("resending %u/%u", i, tx->seg_n);
407 
408         err = bt_mesh_net_resend(tx->sub, seg, tx->new_key,
409                                  &seg_sent_cb, tx);
410         if (err) {
411             BT_ERR("Sending segment failed");
412             bt_mesh_tx_seg_unlock();
413             seg_tx_complete(tx, -EIO);
414             return;
415         }
416     }
417 
418     bt_mesh_tx_seg_unlock();
419 }
420 
seg_retransmit(struct k_work * work)421 static void seg_retransmit(struct k_work *work)
422 {
423     struct seg_tx *tx = CONTAINER_OF(work, struct seg_tx, retransmit);
424 
425     seg_tx_send_unacked(tx);
426 }
427 
send_seg(struct bt_mesh_net_tx * net_tx,struct net_buf_simple * sdu,const struct bt_mesh_send_cb * cb,void * cb_data)428 static int send_seg(struct bt_mesh_net_tx *net_tx, struct net_buf_simple *sdu,
429                     const struct bt_mesh_send_cb *cb, void *cb_data)
430 {
431     uint8_t seg_hdr = 0U, seg_o = 0U;
432     uint16_t seq_zero = 0U;
433     struct seg_tx *tx = NULL;
434     int i;
435 
436     BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x aszmic %u sdu_len %u",
437            net_tx->src, net_tx->ctx->addr, net_tx->ctx->app_idx,
438            net_tx->aszmic, sdu->len);
439 
440     if (sdu->len < 1) {
441         BT_ERR("Zero-length SDU not allowed");
442         return -EINVAL;
443     }
444 
445     if (sdu->len > BLE_MESH_TX_SDU_MAX) {
446         BT_ERR("Not enough segment buffers for length %u", sdu->len);
447         return -EMSGSIZE;
448     }
449 
450     for (tx = NULL, i = 0; i < ARRAY_SIZE(seg_tx); i++) {
451         if (!seg_tx[i].nack_count) {
452             tx = &seg_tx[i];
453             break;
454         }
455     }
456 
457     if (!tx) {
458         BT_ERR("No multi-segment message contexts available");
459         return -EBUSY;
460     }
461 
462     if (net_tx->ctx->app_idx == BLE_MESH_KEY_DEV) {
463         seg_hdr = SEG_HDR(0, 0);
464     } else {
465         seg_hdr = SEG_HDR(1, net_tx->aid);
466     }
467 
468     seg_o = 0U;
469     tx->dst = net_tx->ctx->addr;
470     tx->seg_n = (sdu->len - 1) / BLE_MESH_APP_SEG_SDU_MAX;
471     tx->nack_count = tx->seg_n + 1;
472     tx->seq_auth = SEQ_AUTH(BLE_MESH_NET_IVI_TX, bt_mesh.seq);
473     tx->sub = net_tx->sub;
474     tx->new_key = net_tx->sub->kr_flag;
475     tx->attempts = SEG_RETRANSMIT_ATTEMPTS;
476     tx->seg_pending = 0;
477     tx->cb = cb;
478     tx->cb_data = cb_data;
479 
480     if (net_tx->ctx->send_ttl == BLE_MESH_TTL_DEFAULT) {
481         tx->ttl = bt_mesh_default_ttl_get();
482     } else {
483         tx->ttl = net_tx->ctx->send_ttl;
484     }
485 
486     seq_zero = tx->seq_auth & TRANS_SEQ_ZERO_MASK;
487 
488     BT_DBG("SeqZero 0x%04x", seq_zero);
489 
490     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) &&
491             !bt_mesh_friend_queue_has_space(tx->sub->net_idx, net_tx->src,
492                                             tx->dst, &tx->seq_auth,
493                                             tx->seg_n + 1) &&
494             BLE_MESH_ADDR_IS_UNICAST(tx->dst)) {
495         BT_ERR("Not enough space in Friend Queue for %u segments",
496                tx->seg_n + 1);
497         seg_tx_reset(tx);
498         return -ENOBUFS;
499     }
500 
501     for (seg_o = 0U; sdu->len; seg_o++) {
502         struct net_buf *seg = NULL;
503         uint16_t len = 0U;
504         int err = 0;
505 
506         seg = bt_mesh_adv_create(BLE_MESH_ADV_DATA, net_tx->xmit,
507                                  BUF_TIMEOUT);
508         if (!seg) {
509             BT_ERR("Out of segment buffers");
510             seg_tx_reset(tx);
511             return -ENOBUFS;
512         }
513 
514         net_buf_reserve(seg, BLE_MESH_NET_HDR_LEN);
515 
516         net_buf_add_u8(seg, seg_hdr);
517         net_buf_add_u8(seg, (net_tx->aszmic << 7) | seq_zero >> 6);
518         net_buf_add_u8(seg, (((seq_zero & 0x3f) << 2) |
519                              (seg_o >> 3)));
520         net_buf_add_u8(seg, ((seg_o & 0x07) << 5) | tx->seg_n);
521 
522         len = MIN(sdu->len, BLE_MESH_APP_SEG_SDU_MAX);
523         net_buf_add_mem(seg, sdu->data, len);
524         net_buf_simple_pull(sdu, len);
525 
526         if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
527             enum bt_mesh_friend_pdu_type type = BLE_MESH_FRIEND_PDU_PARTIAL;
528 
529             if (seg_o == tx->seg_n) {
530                 type = BLE_MESH_FRIEND_PDU_COMPLETE;
531             } else {
532                 type = BLE_MESH_FRIEND_PDU_PARTIAL;
533             }
534 
535             if (bt_mesh_friend_enqueue_tx(net_tx, type,
536                                           &tx->seq_auth,
537                                           tx->seg_n + 1,
538                                           &seg->b) &&
539                     BLE_MESH_ADDR_IS_UNICAST(net_tx->ctx->addr)) {
540                 /* PDUs for a specific Friend should only go
541                  * out through the Friend Queue.
542                  */
543                 net_buf_unref(seg);
544                 continue;
545             }
546         }
547 
548         tx->seg[seg_o] = net_buf_ref(seg);
549 
550         BT_DBG("Sending %u/%u", seg_o, tx->seg_n);
551         tx->seg_pending++;
552 
553         err = bt_mesh_net_send(net_tx, seg,
554                                seg_o ? &seg_sent_cb : &first_sent_cb,
555                                tx);
556         if (err) {
557             BT_ERR("Sending segment failed");
558             seg_tx_reset(tx);
559             return err;
560         }
561     }
562 
563     /* This can happen if segments only went into the Friend Queue */
564     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) && !tx->seg[0]) {
565         seg_tx_reset(tx);
566         /* If there was a callback notify sending immediately since
567          * there's no other way to track this (at least currently)
568          * with the Friend Queue.
569          */
570         send_cb_finalize(cb, cb_data);
571     }
572 
573     if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER) &&
574         bt_mesh_lpn_established()) {
575         bt_mesh_lpn_poll();
576     }
577 
578     return 0;
579 }
580 
bt_mesh_app_key_find(uint16_t app_idx)581 struct bt_mesh_app_key *bt_mesh_app_key_find(uint16_t app_idx)
582 {
583     int i;
584 
585     for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
586         struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
587 
588         if (key->net_idx != BLE_MESH_KEY_UNUSED &&
589                 key->app_idx == app_idx) {
590             return key;
591         }
592     }
593 
594     return NULL;
595 }
596 
bt_mesh_trans_send(struct bt_mesh_net_tx * tx,struct net_buf_simple * msg,const struct bt_mesh_send_cb * cb,void * cb_data)597 int bt_mesh_trans_send(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg,
598                        const struct bt_mesh_send_cb *cb, void *cb_data)
599 {
600     const uint8_t *key = NULL;
601     uint8_t *ad = NULL, role = 0U;
602     uint8_t aid = 0U;
603     int err = 0;
604 
605     if (net_buf_simple_tailroom(msg) < BLE_MESH_MIC_SHORT) {
606         BT_ERR("Insufficient tailroom for Transport MIC");
607         return -EINVAL;
608     }
609 
610     if (msg->len > BLE_MESH_SDU_UNSEG_MAX) {
611         tx->ctx->send_rel = 1U;
612     }
613 
614     BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->sub->net_idx,
615            tx->ctx->app_idx, tx->ctx->addr);
616     BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len));
617 
618     role = bt_mesh_get_device_role(tx->ctx->model, tx->ctx->srv_send);
619     if (role == ROLE_NVAL) {
620         BT_ERR("Failed to get model role");
621         return -EINVAL;
622     }
623 
624     err = bt_mesh_app_key_get(tx->sub, tx->ctx->app_idx, &key,
625                               &aid, role, tx->ctx->addr);
626     if (err) {
627         return err;
628     }
629 
630     tx->aid = aid;
631 
632     if (!tx->ctx->send_rel || net_buf_simple_tailroom(msg) < BLE_MESH_MIC_LONG) {
633         tx->aszmic = 0U;
634     } else {
635         tx->aszmic = 1U;
636     }
637 
638     if (BLE_MESH_ADDR_IS_VIRTUAL(tx->ctx->addr)) {
639         ad = bt_mesh_label_uuid_get(tx->ctx->addr);
640     } else {
641         ad = NULL;
642     }
643 
644     err = bt_mesh_app_encrypt(key, tx->ctx->app_idx == BLE_MESH_KEY_DEV,
645                               tx->aszmic, msg, ad, tx->src,
646                               tx->ctx->addr, bt_mesh.seq,
647                               BLE_MESH_NET_IVI_TX);
648     if (err) {
649         BT_ERR("Encrypt failed (err %d)", err);
650         return err;
651     }
652 
653     if (tx->ctx->send_rel) {
654         err = send_seg(tx, msg, cb, cb_data);
655     } else {
656         err = send_unseg(tx, msg, cb, cb_data);
657     }
658 
659     return err;
660 }
661 
update_rpl(struct bt_mesh_rpl * rpl,struct bt_mesh_net_rx * rx)662 static void update_rpl(struct bt_mesh_rpl *rpl, struct bt_mesh_net_rx *rx)
663 {
664     rpl->src = rx->ctx.addr;
665     rpl->seq = rx->seq;
666     rpl->old_iv = rx->old_iv;
667 
668     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
669         bt_mesh_store_rpl(rpl);
670     }
671 }
672 
673 /* Check the Replay Protection List for a replay attempt. If non-NULL match
674  * parameter is given the RPL slot is returned but it is not immediately
675  * updated (needed for segmented messages), whereas if a NULL match is given
676  * the RPL is immediately updated (used for unsegmented messages).
677  */
bt_mesh_rpl_check(struct bt_mesh_net_rx * rx,struct bt_mesh_rpl ** match)678 bool bt_mesh_rpl_check(struct bt_mesh_net_rx *rx, struct bt_mesh_rpl **match)
679 {
680     int i;
681 
682     /* Don't bother checking messages from ourselves */
683     if (rx->net_if == BLE_MESH_NET_IF_LOCAL) {
684         return false;
685     }
686 
687     /* The RPL is used only for the local node */
688     if (!rx->local_match) {
689         return false;
690     }
691 
692     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
693         struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
694 
695         /* Empty slot */
696         if (!rpl->src) {
697             if (match) {
698                 *match = rpl;
699             } else {
700                 update_rpl(rpl, rx);
701             }
702 
703             return false;
704         }
705 
706         /* Existing slot for given address */
707         if (rpl->src == rx->ctx.addr) {
708             if (rx->old_iv && !rpl->old_iv) {
709                 return true;
710             }
711 
712             if ((!rx->old_iv && rpl->old_iv) ||
713                     rpl->seq < rx->seq) {
714                 if (match) {
715                     *match = rpl;
716                 } else {
717                     update_rpl(rpl, rx);
718                 }
719 
720                 return false;
721             } else {
722 #if CONFIG_BLE_MESH_NOT_RELAY_REPLAY_MSG
723                 rx->replay_msg = 1;
724 #endif
725                 return true;
726             }
727         }
728     }
729 
730     BT_ERR("RPL is full!");
731     return true;
732 }
733 
sdu_recv(struct bt_mesh_net_rx * rx,uint32_t seq,uint8_t hdr,uint8_t aszmic,struct net_buf_simple * buf)734 static int sdu_recv(struct bt_mesh_net_rx *rx, uint32_t seq, uint8_t hdr,
735                     uint8_t aszmic, struct net_buf_simple *buf)
736 {
737     struct net_buf_simple *sdu = NULL;
738     size_t array_size = 0U;
739     uint8_t *ad = NULL;
740     size_t i = 0U;
741     int err = 0;
742 
743     BT_DBG("ASZMIC %u AKF %u AID 0x%02x", aszmic, AKF(&hdr), AID(&hdr));
744     BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
745 
746     if (buf->len < 1 + APP_MIC_LEN(aszmic)) {
747         BT_ERR("Too short SDU + MIC (len %u)", buf->len);
748         return -EINVAL;
749     }
750 
751     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) && !rx->local_match) {
752         BT_DBG("Ignoring PDU for LPN 0x%04x of this Friend",
753                rx->ctx.recv_dst);
754         return 0;
755     }
756 
757     if (BLE_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) {
758         ad = bt_mesh_label_uuid_get(rx->ctx.recv_dst);
759     } else {
760         ad = NULL;
761     }
762 
763     /* Adjust the length to not contain the MIC at the end */
764     buf->len -= APP_MIC_LEN(aszmic);
765 
766     /* Use bt_mesh_alloc_buf() instead of NET_BUF_SIMPLE_DEFINE to avoid
767      * causing btu task stackoverflow.
768      */
769     sdu = bt_mesh_alloc_buf(CONFIG_BLE_MESH_RX_SDU_MAX - BLE_MESH_MIC_SHORT);
770     if (!sdu) {
771         BT_ERR("%s, Out of memory", __func__);
772         return -ENOMEM;
773     }
774 
775     if (!AKF(&hdr)) {
776         array_size = bt_mesh_rx_devkey_size();
777 
778         for (i = 0U; i < array_size; i++) {
779             const uint8_t *dev_key = NULL;
780 
781             dev_key = bt_mesh_rx_devkey_get(i, rx->ctx.addr);
782             if (!dev_key) {
783                 BT_DBG("DevKey not found");
784                 continue;
785             }
786 
787             net_buf_simple_reset(sdu);
788             err = bt_mesh_app_decrypt(dev_key, true, aszmic, buf,
789                                       sdu, ad, rx->ctx.addr,
790                                       rx->ctx.recv_dst, seq,
791                                       BLE_MESH_NET_IVI_RX(rx));
792             if (err) {
793                 continue;
794             }
795 
796             BT_BQB(BLE_MESH_BQB_TEST_LOG_LEVEL_PRIMARY_ID_NODE | BLE_MESH_BQB_TEST_LOG_LEVEL_SUB_ID_TNPT,
797                    "\nTNPTRecv: ctl: 0x%04x, ttl: 0x%04x, src: 0x%04x, dst: 0x%04x, payload: 0x%s",
798                    rx->ctl, rx->ctx.recv_ttl, rx->ctx.addr, rx->ctx.recv_dst,
799                    bt_hex(sdu->data, sdu->len));
800 
801             rx->ctx.app_idx = BLE_MESH_KEY_DEV;
802             bt_mesh_model_recv(rx, sdu);
803 
804             bt_mesh_free_buf(sdu);
805             return 0;
806         }
807 
808         BT_WARN("Unable to decrypt with DevKey");
809         bt_mesh_free_buf(sdu);
810         return -ENODEV;
811     }
812 
813     array_size = bt_mesh_rx_appkey_size();
814 
815     for (i = 0U; i < array_size; i++) {
816         struct bt_mesh_app_keys *keys = NULL;
817         struct bt_mesh_app_key *key = NULL;
818 
819         key = bt_mesh_rx_appkey_get(i);
820         if (!key) {
821             BT_DBG("AppKey not found");
822             continue;
823         }
824 
825         /* Make sure that this AppKey matches received net_idx */
826         if (key->net_idx != rx->sub->net_idx) {
827             continue;
828         }
829 
830         if (rx->new_key && key->updated) {
831             keys = &key->keys[1];
832         } else {
833             keys = &key->keys[0];
834         }
835 
836         /* Check that the AppKey ID matches */
837         if (AID(&hdr) != keys->id) {
838             continue;
839         }
840 
841         net_buf_simple_reset(sdu);
842         err = bt_mesh_app_decrypt(keys->val, false, aszmic, buf,
843                                   sdu, ad, rx->ctx.addr,
844                                   rx->ctx.recv_dst, seq,
845                                   BLE_MESH_NET_IVI_RX(rx));
846 
847         BT_BQB(BLE_MESH_BQB_TEST_LOG_LEVEL_PRIMARY_ID_NODE | BLE_MESH_BQB_TEST_LOG_LEVEL_SUB_ID_TNPT,
848                "\nTNPTRecv: ctl: 0x%04x, ttl: 0x%04x, src: 0x%04x, dst: 0x%04x, payload: 0x%s",
849                rx->ctl, rx->ctx.recv_ttl, rx->ctx.addr, rx->ctx.recv_dst,
850                bt_hex(sdu->data, sdu->len));
851 
852         if (err) {
853             BT_DBG("Unable to decrypt with AppKey 0x%03x",
854                    key->app_idx);
855             continue;
856         }
857 
858         rx->ctx.app_idx = key->app_idx;
859         bt_mesh_model_recv(rx, sdu);
860 
861         bt_mesh_free_buf(sdu);
862         return 0;
863     }
864 
865     if (rx->local_match) {
866         BT_WARN("No matching AppKey");
867     }
868     bt_mesh_free_buf(sdu);
869     return 0;
870 }
871 
seg_tx_lookup(uint16_t seq_zero,uint8_t obo,uint16_t addr)872 static struct seg_tx *seg_tx_lookup(uint16_t seq_zero, uint8_t obo, uint16_t addr)
873 {
874     struct seg_tx *tx = NULL;
875     int i;
876 
877     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
878         tx = &seg_tx[i];
879 
880         if ((tx->seq_auth & TRANS_SEQ_ZERO_MASK) != seq_zero) {
881             continue;
882         }
883 
884         if (tx->dst == addr) {
885             return tx;
886         }
887 
888         /* If the expected remote address doesn't match,
889          * but the OBO flag is set and this is the first
890          * acknowledgement, assume it's a Friend that's
891          * responding and therefore accept the message.
892          */
893         if (obo && tx->nack_count == tx->seg_n + 1) {
894             tx->dst = addr;
895             return tx;
896         }
897     }
898 
899     return NULL;
900 }
901 
trans_ack(struct bt_mesh_net_rx * rx,uint8_t hdr,struct net_buf_simple * buf,uint64_t * seq_auth)902 static int trans_ack(struct bt_mesh_net_rx *rx, uint8_t hdr,
903                      struct net_buf_simple *buf, uint64_t *seq_auth)
904 {
905     struct seg_tx *tx = NULL;
906     unsigned int bit = 0;
907     uint32_t ack = 0U;
908     uint16_t seq_zero = 0U;
909     uint8_t obo = 0U;
910 
911     if (buf->len < 6) {
912         BT_ERR("Too short ack message (len %u)", buf->len);
913         return -EINVAL;
914     }
915 
916     seq_zero = net_buf_simple_pull_be16(buf);
917     obo = seq_zero >> 15;
918     seq_zero = (seq_zero >> 2) & TRANS_SEQ_ZERO_MASK;
919 
920     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) && rx->friend_match) {
921         BT_DBG("Ack for LPN 0x%04x of this Friend", rx->ctx.recv_dst);
922         /* Best effort - we don't have enough info for true SeqAuth */
923         *seq_auth = SEQ_AUTH(BLE_MESH_NET_IVI_RX(rx), seq_zero);
924         return 0;
925     }
926 
927     ack = net_buf_simple_pull_be32(buf);
928 
929     BT_DBG("OBO %u seq_zero 0x%04x ack 0x%08x", obo, seq_zero, ack);
930 
931     tx = seg_tx_lookup(seq_zero, obo, rx->ctx.addr);
932     if (!tx) {
933         BT_WARN("No matching TX context for ack");
934         return -EINVAL;
935     }
936 
937     if (!BLE_MESH_ADDR_IS_UNICAST(tx->dst)) {
938         BT_WARN("Received ack for segments to group");
939         return -EINVAL;
940     }
941 
942     *seq_auth = tx->seq_auth;
943 
944     if (!ack) {
945         BT_WARN("SDU canceled");
946         seg_tx_complete(tx, -ECANCELED);
947         return 0;
948     }
949 
950     if (find_msb_set(ack) - 1 > tx->seg_n) {
951         BT_ERR("Too large segment number in ack");
952         return -EINVAL;
953     }
954 
955     k_delayed_work_cancel(&tx->retransmit);
956 
957     while ((bit = find_lsb_set(ack))) {
958         if (tx->seg[bit - 1]) {
959             BT_DBG("seg %u/%u acked", bit - 1, tx->seg_n);
960             bt_mesh_tx_seg_lock();
961             seg_tx_done(tx, bit - 1);
962             bt_mesh_tx_seg_unlock();
963         }
964 
965         ack &= ~BIT(bit - 1);
966     }
967 
968     if (tx->nack_count) {
969         seg_tx_send_unacked(tx);
970     } else {
971         BT_DBG("SDU TX complete");
972         seg_tx_complete(tx, 0);
973     }
974 
975     return 0;
976 }
977 
trans_heartbeat(struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)978 static int trans_heartbeat(struct bt_mesh_net_rx *rx,
979                            struct net_buf_simple *buf)
980 {
981     uint8_t init_ttl = 0U, hops = 0U;
982     uint16_t feat = 0U;
983 
984     if (buf->len < 3) {
985         BT_ERR("Too short heartbeat message (len %u)", buf->len);
986         return -EINVAL;
987     }
988 
989     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned() &&
990         rx->ctx.recv_dst != hb_sub_dst) {
991         BT_WARN("Ignoring heartbeat to non-subscribed destination");
992         return 0;
993     }
994 
995     init_ttl = (net_buf_simple_pull_u8(buf) & 0x7f);
996     feat = net_buf_simple_pull_be16(buf);
997 
998     hops = (init_ttl - rx->ctx.recv_ttl + 1);
999 
1000     BT_INFO("src 0x%04x TTL %u InitTTL %u (%u hop%s) feat 0x%04x",
1001            rx->ctx.addr, rx->ctx.recv_ttl, init_ttl, hops,
1002            (hops == 1U) ? "" : "s", feat);
1003 
1004     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned()) {
1005         bt_mesh_heartbeat(rx->ctx.addr, rx->ctx.recv_dst, hops, feat);
1006     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER_RECV_HB) && bt_mesh_is_provisioner_en()) {
1007         bt_mesh_provisioner_heartbeat(rx->ctx.addr, rx->ctx.recv_dst,
1008                                       init_ttl, rx->ctx.recv_ttl,
1009                                       hops, feat, rx->ctx.recv_rssi);
1010     }
1011 
1012     return 0;
1013 }
1014 
ctl_recv(struct bt_mesh_net_rx * rx,uint8_t hdr,struct net_buf_simple * buf,uint64_t * seq_auth)1015 static int ctl_recv(struct bt_mesh_net_rx *rx, uint8_t hdr,
1016                     struct net_buf_simple *buf, uint64_t *seq_auth)
1017 {
1018     uint8_t ctl_op = TRANS_CTL_OP(&hdr);
1019 
1020     BT_DBG("OpCode 0x%02x len %u", ctl_op, buf->len);
1021 
1022     BT_BQB(BLE_MESH_BQB_TEST_LOG_LEVEL_PRIMARY_ID_NODE | BLE_MESH_BQB_TEST_LOG_LEVEL_SUB_ID_TNPT,
1023            "\nTNPTRecv: ctl: 0x%04x, ttl: 0x%04x, src: 0x%04x, dst: 0x%04x, payload: 0x%s",
1024            rx->ctl, rx->ctx.recv_ttl, rx->ctx.addr, rx->ctx.recv_dst,
1025            bt_hex(buf->data, buf->len));
1026 
1027     switch (ctl_op) {
1028     case TRANS_CTL_OP_ACK:
1029         return trans_ack(rx, hdr, buf, seq_auth);
1030     case TRANS_CTL_OP_HEARTBEAT:
1031         return trans_heartbeat(rx, buf);
1032     }
1033 
1034     /* Only acks and heartbeats may need processing without local_match */
1035     if (!rx->local_match) {
1036         return 0;
1037     }
1038 
1039     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) && !bt_mesh_lpn_established()) {
1040         switch (ctl_op) {
1041         case TRANS_CTL_OP_FRIEND_POLL:
1042             return bt_mesh_friend_poll(rx, buf);
1043         case TRANS_CTL_OP_FRIEND_REQ:
1044             return bt_mesh_friend_req(rx, buf);
1045         case TRANS_CTL_OP_FRIEND_CLEAR:
1046             return bt_mesh_friend_clear(rx, buf);
1047         case TRANS_CTL_OP_FRIEND_CLEAR_CFM:
1048             return bt_mesh_friend_clear_cfm(rx, buf);
1049         case TRANS_CTL_OP_FRIEND_SUB_ADD:
1050             return bt_mesh_friend_sub_add(rx, buf);
1051         case TRANS_CTL_OP_FRIEND_SUB_REM:
1052             return bt_mesh_friend_sub_rem(rx, buf);
1053         }
1054     }
1055 
1056 #if defined(CONFIG_BLE_MESH_LOW_POWER)
1057     if (ctl_op == TRANS_CTL_OP_FRIEND_OFFER) {
1058         return bt_mesh_lpn_friend_offer(rx, buf);
1059     }
1060 
1061     if (rx->ctx.addr == bt_mesh.lpn.frnd) {
1062         if (ctl_op == TRANS_CTL_OP_FRIEND_CLEAR_CFM) {
1063             return bt_mesh_lpn_friend_clear_cfm(rx, buf);
1064         }
1065 
1066         if (!rx->friend_cred) {
1067             BT_WARN("Message from friend with wrong credentials");
1068             return -EINVAL;
1069         }
1070 
1071         switch (ctl_op) {
1072         case TRANS_CTL_OP_FRIEND_UPDATE:
1073             return bt_mesh_lpn_friend_update(rx, buf);
1074         case TRANS_CTL_OP_FRIEND_SUB_CFM:
1075             return bt_mesh_lpn_friend_sub_cfm(rx, buf);
1076         }
1077     }
1078 #endif /* CONFIG_BLE_MESH_LOW_POWER */
1079 
1080     BT_WARN("Unhandled TransOpCode 0x%02x", ctl_op);
1081 
1082     return -ENOENT;
1083 }
1084 
trans_unseg(struct net_buf_simple * buf,struct bt_mesh_net_rx * rx,uint64_t * seq_auth)1085 static int trans_unseg(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx,
1086                        uint64_t *seq_auth)
1087 {
1088     uint8_t hdr = 0U;
1089 
1090     BT_DBG("AFK %u AID 0x%02x", AKF(buf->data), AID(buf->data));
1091 
1092     if (buf->len < 1) {
1093         BT_ERR("Too small unsegmented PDU");
1094         return -EINVAL;
1095     }
1096 
1097     if (bt_mesh_rpl_check(rx, NULL)) {
1098         BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x",
1099                 rx->ctx.addr, rx->ctx.recv_dst, rx->seq);
1100         return -EINVAL;
1101     }
1102 
1103     hdr = net_buf_simple_pull_u8(buf);
1104 
1105     if (rx->ctl) {
1106         return ctl_recv(rx, hdr, buf, seq_auth);
1107     } else {
1108         /* SDUs must match a local element or an LPN of this Friend. */
1109         if (!rx->local_match && !rx->friend_match) {
1110             return 0;
1111         }
1112 
1113         return sdu_recv(rx, rx->seq, hdr, 0, buf);
1114     }
1115 }
1116 
ack_timeout(struct seg_rx * rx)1117 static inline int32_t ack_timeout(struct seg_rx *rx)
1118 {
1119     int32_t to = 0;
1120     uint8_t ttl = 0U;
1121 
1122     if (rx->ttl == BLE_MESH_TTL_DEFAULT) {
1123         ttl = bt_mesh_default_ttl_get();
1124     } else {
1125         ttl = rx->ttl;
1126     }
1127 
1128     /* The acknowledgment timer shall be set to a minimum of
1129      * 150 + 50 * TTL milliseconds.
1130      */
1131     to = K_MSEC(150 + (ttl * 50U));
1132 
1133     /* 100 ms for every not yet received segment */
1134     to += K_MSEC(((rx->seg_n + 1) - popcount(rx->block)) * 100U);
1135 
1136     /* Make sure we don't send more frequently than the duration for
1137      * each packet (default is 300ms).
1138      */
1139     return MAX(to, K_MSEC(400));
1140 }
1141 
ctl_send_unseg(struct bt_mesh_net_tx * tx,uint8_t ctl_op,void * data,size_t data_len,const struct bt_mesh_send_cb * cb,void * cb_data)1142 static int ctl_send_unseg(struct bt_mesh_net_tx *tx, uint8_t ctl_op, void *data,
1143                           size_t data_len, const struct bt_mesh_send_cb *cb,
1144                           void *cb_data)
1145 {
1146     struct net_buf *buf = NULL;
1147 
1148     buf = bt_mesh_adv_create(BLE_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT);
1149     if (!buf) {
1150         BT_ERR("Out of transport buffers");
1151         return -ENOBUFS;
1152     }
1153 
1154     net_buf_reserve(buf, BLE_MESH_NET_HDR_LEN);
1155 
1156     net_buf_add_u8(buf, TRANS_CTL_HDR(ctl_op, 0));
1157 
1158     net_buf_add_mem(buf, data, data_len);
1159 
1160     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
1161         if (bt_mesh_friend_enqueue_tx(tx, BLE_MESH_FRIEND_PDU_SINGLE,
1162                                       NULL, 1, &buf->b) &&
1163                 BLE_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
1164             /* PDUs for a specific Friend should only go
1165              * out through the Friend Queue.
1166              */
1167             net_buf_unref(buf);
1168             return 0;
1169         }
1170     }
1171 
1172     return bt_mesh_net_send(tx, buf, cb, cb_data);
1173 }
1174 
ctl_send_seg(struct bt_mesh_net_tx * tx,uint8_t ctl_op,void * data,size_t data_len,const struct bt_mesh_send_cb * cb,void * cb_data)1175 static int ctl_send_seg(struct bt_mesh_net_tx *tx, uint8_t ctl_op, void *data,
1176                         size_t data_len, const struct bt_mesh_send_cb *cb,
1177                         void *cb_data)
1178 {
1179     struct seg_tx *tx_seg = NULL;
1180     uint16_t unsent = data_len;
1181     uint16_t seq_zero = 0;
1182     uint8_t seg_o = 0;
1183     int i;
1184 
1185     for (tx_seg = NULL, i = 0; i < ARRAY_SIZE(seg_tx); i++) {
1186         if (!seg_tx[i].nack_count) {
1187             tx_seg = &seg_tx[i];
1188             break;
1189         }
1190     }
1191 
1192     if (!tx_seg) {
1193         BT_ERR("No multi-segment message contexts available");
1194         return -EBUSY;
1195     }
1196 
1197     tx_seg->dst = tx->ctx->addr;
1198     tx_seg->seg_n = (data_len - 1) / BLE_MESH_CTL_SEG_SDU_MAX;
1199     tx_seg->nack_count = tx_seg->seg_n + 1;
1200     tx_seg->seq_auth = SEQ_AUTH(BLE_MESH_NET_IVI_TX, bt_mesh.seq);
1201     tx_seg->sub = tx->sub;
1202     tx_seg->new_key = tx->sub->kr_flag;
1203     tx_seg->attempts = SEG_RETRANSMIT_ATTEMPTS;
1204     tx_seg->seg_pending = 0;
1205     tx_seg->cb = cb;
1206     tx_seg->cb_data = cb_data;
1207 
1208     if (tx->ctx->send_ttl == BLE_MESH_TTL_DEFAULT) {
1209         tx_seg->ttl = bt_mesh_default_ttl_get();
1210     } else {
1211         tx_seg->ttl = tx->ctx->send_ttl;
1212     }
1213 
1214     seq_zero = tx_seg->seq_auth & TRANS_SEQ_ZERO_MASK;
1215 
1216     BT_DBG("SeqZero 0x%04x", seq_zero);
1217 
1218     for (seg_o = 0; seg_o <= tx_seg->seg_n; seg_o++) {
1219         struct net_buf *seg = NULL;
1220         uint16_t len = 0;
1221         int err = 0;
1222 
1223         seg = bt_mesh_adv_create(BLE_MESH_ADV_DATA, tx->xmit,
1224                                  BUF_TIMEOUT);
1225         if (!seg) {
1226             BT_ERR("Out of segment buffers");
1227             seg_tx_reset(tx_seg);
1228             return -ENOBUFS;
1229         }
1230 
1231         net_buf_reserve(seg, BLE_MESH_NET_HDR_LEN);
1232 
1233         net_buf_add_u8(seg, TRANS_CTL_HDR(ctl_op, 1));
1234         net_buf_add_u8(seg, (tx->aszmic << 7) | seq_zero >> 6);
1235         net_buf_add_u8(seg, (((seq_zero & 0x3f) << 2) | (seg_o >> 3)));
1236         net_buf_add_u8(seg, ((seg_o & 0x07) << 5) | tx_seg->seg_n);
1237 
1238         len = MIN(unsent, BLE_MESH_CTL_SEG_SDU_MAX);
1239         net_buf_add_mem(seg, (uint8_t *)data + (data_len - unsent), len);
1240         unsent -= len;
1241 
1242         tx_seg->seg[seg_o] = net_buf_ref(seg);
1243 
1244         BT_DBG("Sending %u/%u", seg_o, tx_seg->seg_n);
1245         tx_seg->seg_pending++;
1246 
1247         err = bt_mesh_net_send(tx, seg,
1248                                seg_o ? &seg_sent_cb : &first_sent_cb,
1249                                tx_seg);
1250         if (err) {
1251             BT_ERR("Sending segment failed (err %d)", err);
1252             seg_tx_reset(tx_seg);
1253             return err;
1254         }
1255     }
1256 
1257     return 0;
1258 }
1259 
bt_mesh_ctl_send(struct bt_mesh_net_tx * tx,uint8_t ctl_op,void * data,size_t data_len,const struct bt_mesh_send_cb * cb,void * cb_data)1260 int bt_mesh_ctl_send(struct bt_mesh_net_tx *tx, uint8_t ctl_op, void *data,
1261                      size_t data_len, const struct bt_mesh_send_cb *cb,
1262                      void *cb_data)
1263 {
1264     BT_DBG("src 0x%04x dst 0x%04x ttl 0x%02x ctl 0x%02x", tx->src,
1265             tx->ctx->addr, tx->ctx->send_ttl, ctl_op);
1266     BT_DBG("len %zu: %s", data_len, bt_hex(data, data_len));
1267 
1268     if (data_len <= BLE_MESH_SDU_UNSEG_MAX) {
1269         return ctl_send_unseg(tx, ctl_op, data, data_len,
1270                               cb, cb_data);
1271     } else {
1272         return ctl_send_seg(tx, ctl_op, data, data_len,
1273                             cb, cb_data);
1274     }
1275 }
1276 
send_ack(struct bt_mesh_subnet * sub,uint16_t src,uint16_t dst,uint8_t ttl,uint64_t * seq_auth,uint32_t block,uint8_t obo)1277 static int send_ack(struct bt_mesh_subnet *sub, uint16_t src, uint16_t dst,
1278                     uint8_t ttl, uint64_t *seq_auth, uint32_t block, uint8_t obo)
1279 {
1280     struct bt_mesh_msg_ctx ctx = {
1281         .net_idx = sub->net_idx,
1282         .app_idx = BLE_MESH_KEY_UNUSED,
1283         .addr = dst,
1284         .send_ttl = ttl,
1285     };
1286     struct bt_mesh_net_tx tx = {
1287         .sub = sub,
1288         .ctx = &ctx,
1289         .src = obo ? bt_mesh_primary_addr() : src,
1290         .xmit = bt_mesh_net_transmit_get(),
1291     };
1292     uint16_t seq_zero = *seq_auth & TRANS_SEQ_ZERO_MASK;
1293     uint8_t buf[6] = {0};
1294 
1295     BT_DBG("SeqZero 0x%04x Block 0x%08x OBO %u", seq_zero, block, obo);
1296 
1297     if (bt_mesh_lpn_established()) {
1298         BT_WARN("Not sending ack when LPN is enabled");
1299         return 0;
1300     }
1301 
1302     /* This can happen if the segmented message was destined for a group
1303      * or virtual address.
1304      */
1305     if (!BLE_MESH_ADDR_IS_UNICAST(src)) {
1306         BT_INFO("Not sending ack for non-unicast address");
1307         return 0;
1308     }
1309 
1310     sys_put_be16(((seq_zero << 2) & 0x7ffc) | (obo << 15), buf);
1311     sys_put_be32(block, &buf[2]);
1312 
1313     return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_ACK, buf, sizeof(buf),
1314                             NULL, NULL);
1315 }
1316 
seg_rx_reset(struct seg_rx * rx,bool full_reset)1317 static void seg_rx_reset(struct seg_rx *rx, bool full_reset)
1318 {
1319     BT_DBG("rx %p", rx);
1320 
1321     bt_mesh_rx_seg_lock();
1322 
1323     k_delayed_work_cancel(&rx->ack);
1324 
1325     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) && rx->obo &&
1326             rx->block != BLOCK_COMPLETE(rx->seg_n)) {
1327         BT_WARN("Clearing incomplete buffers from Friend queue");
1328         bt_mesh_friend_clear_incomplete(rx->sub, rx->src, rx->dst,
1329                                         &rx->seq_auth);
1330     }
1331 
1332     rx->in_use = 0U;
1333 
1334     /* We don't always reset these values since we need to be able to
1335      * send an ack if we receive a segment after we've already received
1336      * the full SDU.
1337      */
1338     if (full_reset) {
1339         rx->seq_auth = 0U;
1340         rx->sub = NULL;
1341         rx->src = BLE_MESH_ADDR_UNASSIGNED;
1342         rx->dst = BLE_MESH_ADDR_UNASSIGNED;
1343     }
1344 
1345     bt_mesh_rx_seg_unlock();
1346 }
1347 
incomplete_timeout(struct seg_rx * rx)1348 static uint32_t incomplete_timeout(struct seg_rx *rx)
1349 {
1350     uint32_t timeout = 0U;
1351     uint8_t ttl = 0U;
1352 
1353     if (rx->ttl == BLE_MESH_TTL_DEFAULT) {
1354         ttl = bt_mesh_default_ttl_get();
1355     } else {
1356         ttl = rx->ttl;
1357     }
1358 
1359     /* "The incomplete timer shall be set to a minimum of 10 seconds." */
1360     timeout = K_SECONDS(10);
1361 
1362     /* The less segments being received, the shorter timeout will be used. */
1363     timeout += K_MSEC(ttl * popcount(rx->block) * 100U);
1364 
1365     return MIN(timeout, K_SECONDS(60));
1366 }
1367 
seg_ack(struct k_work * work)1368 static void seg_ack(struct k_work *work)
1369 {
1370     struct seg_rx *rx = CONTAINER_OF(work, struct seg_rx, ack);
1371 
1372     BT_DBG("rx %p", rx);
1373 
1374     bt_mesh_rx_seg_lock();
1375 
1376     if (k_uptime_get_32() - rx->last > incomplete_timeout(rx)) {
1377         BT_WARN("Incomplete timer expired");
1378         bt_mesh_rx_seg_unlock();
1379         seg_rx_reset(rx, false);
1380         return;
1381     }
1382 
1383     /* Add this check in case the timeout handler is just executed
1384      * after the seg_rx_reset() which may reset rx->sub to NULL.
1385      */
1386     if (rx->sub == NULL) {
1387         bt_mesh_rx_seg_unlock();
1388         return;
1389     }
1390 
1391     send_ack(rx->sub, rx->dst, rx->src, rx->ttl, &rx->seq_auth,
1392              rx->block, rx->obo);
1393 
1394     k_delayed_work_submit(&rx->ack, ack_timeout(rx));
1395 
1396     bt_mesh_rx_seg_unlock();
1397 }
1398 
seg_len(bool ctl)1399 static inline uint8_t seg_len(bool ctl)
1400 {
1401     if (ctl) {
1402         return BLE_MESH_CTL_SEG_SDU_MAX;
1403     } else {
1404         return BLE_MESH_APP_SEG_SDU_MAX;
1405     }
1406 }
1407 
sdu_len_is_ok(bool ctl,uint8_t seg_n)1408 static inline bool sdu_len_is_ok(bool ctl, uint8_t seg_n)
1409 {
1410     return ((seg_n * seg_len(ctl) + 1) <= CONFIG_BLE_MESH_RX_SDU_MAX);
1411 }
1412 
seg_rx_find(struct bt_mesh_net_rx * net_rx,const uint64_t * seq_auth)1413 static struct seg_rx *seg_rx_find(struct bt_mesh_net_rx *net_rx,
1414                                   const uint64_t *seq_auth)
1415 {
1416     int i;
1417 
1418     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1419         struct seg_rx *rx = &seg_rx[i];
1420 
1421         if (rx->src != net_rx->ctx.addr ||
1422                 rx->dst != net_rx->ctx.recv_dst) {
1423             continue;
1424         }
1425 
1426         /* When ">=" is used, return newer RX context in addition to an exact match,
1427          * so the calling function can properly discard an old SeqAuth.
1428          */
1429 #if CONFIG_BLE_MESH_DISCARD_OLD_SEQ_AUTH
1430         if (rx->seq_auth >= *seq_auth) {
1431 #else
1432         if (rx->seq_auth == *seq_auth) {
1433 #endif
1434             return rx;
1435         }
1436 
1437         if (rx->in_use) {
1438             BT_WARN("Duplicate SDU from src 0x%04x",
1439                     net_rx->ctx.addr);
1440 
1441             /* Clear out the old context since the sender
1442              * has apparently started sending a new SDU.
1443              */
1444             seg_rx_reset(rx, true);
1445 
1446             /* Return non-match so caller can re-allocate */
1447             return NULL;
1448         }
1449     }
1450 
1451     return NULL;
1452 }
1453 
1454 static bool seg_rx_is_valid(struct seg_rx *rx, struct bt_mesh_net_rx *net_rx,
1455                             const uint8_t *hdr, uint8_t seg_n)
1456 {
1457     if (rx->hdr != *hdr || rx->seg_n != seg_n) {
1458         BT_ERR("Invalid segment for ongoing session");
1459         return false;
1460     }
1461 
1462     if (rx->src != net_rx->ctx.addr || rx->dst != net_rx->ctx.recv_dst) {
1463         BT_ERR("Invalid source or destination for segment");
1464         return false;
1465     }
1466 
1467     if (rx->ctl != net_rx->ctl) {
1468         BT_ERR("Inconsistent CTL in segment");
1469         return false;
1470     }
1471 
1472     return true;
1473 }
1474 
1475 static struct seg_rx *seg_rx_alloc(struct bt_mesh_net_rx *net_rx,
1476                                    const uint8_t *hdr, const uint64_t *seq_auth,
1477                                    uint8_t seg_n)
1478 {
1479     int i;
1480 
1481     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1482         struct seg_rx *rx = &seg_rx[i];
1483 
1484         if (rx->in_use) {
1485             continue;
1486         }
1487 
1488         rx->in_use = 1U;
1489         net_buf_simple_reset(&rx->buf);
1490         rx->sub = net_rx->sub;
1491         rx->ctl = net_rx->ctl;
1492         rx->seq_auth = *seq_auth;
1493         rx->seg_n = seg_n;
1494         rx->hdr = *hdr;
1495         rx->ttl = net_rx->ctx.send_ttl;
1496         rx->src = net_rx->ctx.addr;
1497         rx->dst = net_rx->ctx.recv_dst;
1498         rx->block = 0U;
1499 
1500         BT_DBG("New RX context. Block Complete 0x%08x",
1501                BLOCK_COMPLETE(seg_n));
1502 
1503         return rx;
1504     }
1505 
1506     return NULL;
1507 }
1508 
1509 static int trans_seg(struct net_buf_simple *buf, struct bt_mesh_net_rx *net_rx,
1510                      enum bt_mesh_friend_pdu_type *pdu_type, uint64_t *seq_auth,
1511                      uint8_t *seg_count)
1512 {
1513     struct bt_mesh_rpl *rpl = NULL;
1514     struct seg_rx *rx = NULL;
1515     uint8_t *hdr = buf->data;
1516     uint16_t seq_zero = 0U;
1517     uint8_t seg_n = 0U;
1518     uint8_t seg_o = 0U;
1519     int err = 0;
1520 
1521     if (buf->len < 5) {
1522         BT_ERR("Too short segmented message (len %u)", buf->len);
1523         return -EINVAL;
1524     }
1525 
1526     if (bt_mesh_rpl_check(net_rx, &rpl)) {
1527         BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x",
1528                 net_rx->ctx.addr, net_rx->ctx.recv_dst, net_rx->seq);
1529         return -EINVAL;
1530     }
1531 
1532     BT_DBG("ASZMIC %u AKF %u AID 0x%02x", ASZMIC(hdr), AKF(hdr), AID(hdr));
1533 
1534     net_buf_simple_pull(buf, 1);
1535 
1536     seq_zero = net_buf_simple_pull_be16(buf);
1537     seg_o = (seq_zero & 0x03) << 3;
1538     seq_zero = (seq_zero >> 2) & TRANS_SEQ_ZERO_MASK;
1539     seg_n = net_buf_simple_pull_u8(buf);
1540     seg_o |= seg_n >> 5;
1541     seg_n &= 0x1f;
1542 
1543     BT_DBG("SeqZero 0x%04x SegO %u SegN %u", seq_zero, seg_o, seg_n);
1544 
1545     if (seg_o > seg_n) {
1546         BT_ERR("SegO greater than SegN (%u > %u)", seg_o, seg_n);
1547         return -EINVAL;
1548     }
1549 
1550     /* According to Mesh 1.0 specification:
1551      * "The SeqAuth is composed of the IV Index and the sequence number
1552      *  (SEQ) of the first segment"
1553      *
1554      * Therefore we need to calculate very first SEQ in order to find
1555      * seqAuth. We can calculate as below:
1556      *
1557      * SEQ(0) = SEQ(n) - (delta between seqZero and SEQ(n) by looking into
1558      * 14 least significant bits of SEQ(n))
1559      *
1560      * Mentioned delta shall be >= 0, if it is not then seq_auth will
1561      * be broken and it will be verified by the code below.
1562      */
1563     *seq_auth = SEQ_AUTH(BLE_MESH_NET_IVI_RX(net_rx),
1564                          (net_rx->seq -
1565                           ((((net_rx->seq & BIT_MASK(14)) - seq_zero)) &
1566                            BIT_MASK(13))));
1567 
1568     *seg_count = seg_n + 1;
1569 
1570     /* Look for old RX sessions */
1571     rx = seg_rx_find(net_rx, seq_auth);
1572     if (rx) {
1573         /* Discard old SeqAuth packet */
1574         if (rx->seq_auth > *seq_auth) {
1575             BT_WARN("Ignoring old SeqAuth");
1576             return -EINVAL;
1577         }
1578 
1579         if (!seg_rx_is_valid(rx, net_rx, hdr, seg_n)) {
1580             return -EINVAL;
1581         }
1582 
1583         if (rx->in_use) {
1584             BT_DBG("Existing RX context. Block 0x%08x", rx->block);
1585             goto found_rx;
1586         }
1587 
1588         if (rx->block == BLOCK_COMPLETE(rx->seg_n)) {
1589             BT_INFO("Got segment for already complete SDU");
1590             send_ack(net_rx->sub, net_rx->ctx.recv_dst,
1591                      net_rx->ctx.addr, net_rx->ctx.send_ttl,
1592                      seq_auth, rx->block, rx->obo);
1593 
1594             if (rpl) {
1595                 update_rpl(rpl, net_rx);
1596             }
1597 
1598             return -EALREADY;
1599         }
1600 
1601         /* We ignore instead of sending block ack 0 since the
1602          * ack timer is always smaller than the incomplete
1603          * timer, i.e. the sender is misbehaving.
1604          */
1605         BT_WARN("Got segment for canceled SDU");
1606         return -EINVAL;
1607     }
1608 
1609     /* Bail out early if we're not ready to receive such a large SDU */
1610     if (!sdu_len_is_ok(net_rx->ctl, seg_n)) {
1611         BT_ERR("Too big incoming SDU length");
1612         send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr,
1613                  net_rx->ctx.send_ttl, seq_auth, 0,
1614                  net_rx->friend_match);
1615         return -EMSGSIZE;
1616     }
1617 
1618     /* Verify early that there will be space in the Friend Queue(s) in
1619      * case this message is destined to an LPN of ours.
1620      */
1621     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) &&
1622             net_rx->friend_match && !net_rx->local_match &&
1623             !bt_mesh_friend_queue_has_space(net_rx->sub->net_idx,
1624                                             net_rx->ctx.addr,
1625                                             net_rx->ctx.recv_dst, seq_auth,
1626                                             *seg_count)) {
1627         BT_ERR("No space in Friend Queue for %u segments", *seg_count);
1628         send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr,
1629                  net_rx->ctx.send_ttl, seq_auth, 0,
1630                  net_rx->friend_match);
1631         return -ENOBUFS;
1632     }
1633 
1634     /* Look for free slot for a new RX session */
1635     rx = seg_rx_alloc(net_rx, hdr, seq_auth, seg_n);
1636     if (!rx) {
1637         /* Warn but don't cancel since the existing slots will
1638          * eventually be freed up and we'll be able to process
1639          * this one.
1640          */
1641         BT_WARN("No free slots for new incoming segmented messages");
1642         return -ENOMEM;
1643     }
1644 
1645     rx->obo = net_rx->friend_match;
1646 
1647 found_rx:
1648     if (BIT(seg_o) & rx->block) {
1649         BT_WARN("Received already received fragment");
1650         return -EALREADY;
1651     }
1652 
1653     /* All segments, except the last one, must either have 8 bytes of
1654      * payload (for 64bit Net MIC) or 12 bytes of payload (for 32bit
1655      * Net MIC).
1656      */
1657     if (seg_o == seg_n) {
1658         /* Set the expected final buffer length */
1659         rx->buf.len = seg_n * seg_len(rx->ctl) + buf->len;
1660         BT_DBG("Target len %u * %u + %u = %u", seg_n, seg_len(rx->ctl),
1661                buf->len, rx->buf.len);
1662 
1663         if (rx->buf.len > CONFIG_BLE_MESH_RX_SDU_MAX) {
1664             BT_ERR("Too large SDU len");
1665             send_ack(net_rx->sub, net_rx->ctx.recv_dst,
1666                      net_rx->ctx.addr, net_rx->ctx.send_ttl,
1667                      seq_auth, 0, rx->obo);
1668             seg_rx_reset(rx, true);
1669             return -EMSGSIZE;
1670         }
1671     } else {
1672         if (buf->len != seg_len(rx->ctl)) {
1673             BT_ERR("Incorrect segment size for message type");
1674             return -EINVAL;
1675         }
1676     }
1677 
1678     /* Reset the Incomplete Timer */
1679     rx->last = k_uptime_get_32();
1680 
1681     if (!k_delayed_work_remaining_get(&rx->ack) &&
1682             !bt_mesh_lpn_established()) {
1683         k_delayed_work_submit(&rx->ack, ack_timeout(rx));
1684     }
1685 
1686     /* Location in buffer can be calculated based on seg_o & rx->ctl */
1687     memcpy(rx->buf.data + (seg_o * seg_len(rx->ctl)), buf->data, buf->len);
1688 
1689     BT_INFO("Received %u/%u", seg_o, seg_n);
1690 
1691     /* Mark segment as received */
1692     rx->block |= BIT(seg_o);
1693 
1694     if (rx->block != BLOCK_COMPLETE(seg_n)) {
1695         *pdu_type = BLE_MESH_FRIEND_PDU_PARTIAL;
1696         return 0;
1697     }
1698 
1699     BT_DBG("Complete SDU");
1700 
1701     if (rpl) {
1702         update_rpl(rpl, net_rx);
1703     }
1704 
1705     *pdu_type = BLE_MESH_FRIEND_PDU_COMPLETE;
1706 
1707     k_delayed_work_cancel(&rx->ack);
1708     send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr,
1709              net_rx->ctx.send_ttl, seq_auth, rx->block, rx->obo);
1710 
1711     if (net_rx->ctl) {
1712         err = ctl_recv(net_rx, *hdr, &rx->buf, seq_auth);
1713     } else {
1714         err = sdu_recv(net_rx, (rx->seq_auth & 0xffffff), *hdr,
1715                        ASZMIC(hdr), &rx->buf);
1716     }
1717 
1718     seg_rx_reset(rx, false);
1719 
1720     return err;
1721 }
1722 
1723 int bt_mesh_trans_recv(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx)
1724 {
1725     uint64_t seq_auth = TRANS_SEQ_AUTH_NVAL;
1726     enum bt_mesh_friend_pdu_type pdu_type = BLE_MESH_FRIEND_PDU_SINGLE;
1727     struct net_buf_simple_state state = {0};
1728     uint8_t seg_count = 0U;
1729     int err = 0;
1730 
1731     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
1732         rx->friend_match = bt_mesh_friend_match(rx->sub->net_idx,
1733                                                 rx->ctx.recv_dst);
1734     } else {
1735         rx->friend_match = false;
1736     }
1737 
1738     BT_DBG("src 0x%04x dst 0x%04x seq 0x%08x friend_match %u",
1739            rx->ctx.addr, rx->ctx.recv_dst, rx->seq, rx->friend_match);
1740 
1741     /* Remove network headers */
1742     net_buf_simple_pull(buf, BLE_MESH_NET_HDR_LEN);
1743 
1744     BT_DBG("Payload %s", bt_hex(buf->data, buf->len));
1745 
1746     /* If LPN mode is enabled messages are only accepted when we've
1747      * requested the Friend to send them. The messages must also
1748      * be encrypted using the Friend Credentials.
1749      */
1750     if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER) &&
1751         bt_mesh_lpn_established() && rx->net_if == BLE_MESH_NET_IF_ADV &&
1752         (!bt_mesh_lpn_waiting_update() || !rx->friend_cred)) {
1753         BT_WARN("Ignoring unexpected message in Low Power mode");
1754         return -EAGAIN;
1755     }
1756 
1757     /* Save the app-level state so the buffer can later be placed in
1758      * the Friend Queue.
1759      */
1760     net_buf_simple_save(buf, &state);
1761 
1762     if (SEG(buf->data)) {
1763         /* Segmented messages must match a local element or an
1764          * LPN of this Friend.
1765          */
1766         if (!rx->local_match && !rx->friend_match) {
1767             return 0;
1768         }
1769 
1770         err = trans_seg(buf, rx, &pdu_type, &seq_auth, &seg_count);
1771     } else {
1772         seg_count = 1U;
1773         err = trans_unseg(buf, rx, &seq_auth);
1774     }
1775 
1776     /* Notify LPN state machine so a Friend Poll will be sent. If the
1777      * message was a Friend Update it's possible that a Poll was already
1778      * queued for sending, however that's fine since then the
1779      * bt_mesh_lpn_waiting_update() function will return false:
1780      * we still need to go through the actual sending to the bearer and
1781      * wait for ReceiveDelay before transitioning to WAIT_UPDATE state.
1782      * Another situation where we want to notify the LPN state machine
1783      * is if it's configured to use an automatic Friendship establishment
1784      * timer, in which case we want to reset the timer at this point.
1785      *
1786      */
1787     if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER) &&
1788         (bt_mesh_lpn_timer() ||
1789         (bt_mesh_lpn_established() && bt_mesh_lpn_waiting_update()))) {
1790         bt_mesh_lpn_msg_received(rx);
1791     }
1792 
1793     net_buf_simple_restore(buf, &state);
1794 
1795     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND) && rx->friend_match && !err) {
1796         if (seq_auth == TRANS_SEQ_AUTH_NVAL) {
1797             bt_mesh_friend_enqueue_rx(rx, pdu_type, NULL,
1798                                       seg_count, buf);
1799         } else {
1800             bt_mesh_friend_enqueue_rx(rx, pdu_type, &seq_auth,
1801                                       seg_count, buf);
1802         }
1803     }
1804 
1805     return err;
1806 }
1807 
1808 void bt_mesh_rx_reset(bool erase)
1809 {
1810     int i;
1811 
1812     BT_DBG("%s", __func__);
1813 
1814     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1815         seg_rx_reset(&seg_rx[i], true);
1816     }
1817 
1818     (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
1819 
1820     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS) && erase) {
1821         bt_mesh_clear_rpl();
1822     }
1823 }
1824 
1825 void bt_mesh_tx_reset(void)
1826 {
1827     int i;
1828 
1829     BT_DBG("%s", __func__);
1830 
1831     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
1832         seg_tx_reset(&seg_tx[i]);
1833     }
1834 }
1835 
1836 #if CONFIG_BLE_MESH_PROVISIONER
1837 void bt_mesh_rx_reset_single(uint16_t src)
1838 {
1839     int i;
1840 
1841     if (!BLE_MESH_ADDR_IS_UNICAST(src)) {
1842         return;
1843     }
1844 
1845     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1846         struct seg_rx *rx = &seg_rx[i];
1847         if (src == rx->src) {
1848             seg_rx_reset(rx, true);
1849         }
1850     }
1851 
1852     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
1853         struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
1854         if (src == rpl->src) {
1855             memset(rpl, 0, sizeof(struct bt_mesh_rpl));
1856             if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1857                 bt_mesh_clear_rpl_single(src);
1858             }
1859         }
1860     }
1861 }
1862 
1863 void bt_mesh_tx_reset_single(uint16_t dst)
1864 {
1865     int i;
1866 
1867     if (!BLE_MESH_ADDR_IS_UNICAST(dst)) {
1868         return;
1869     }
1870 
1871     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
1872         struct seg_tx *tx = &seg_tx[i];
1873         if (dst == tx->dst) {
1874             seg_tx_reset(tx);
1875         }
1876     }
1877 }
1878 #endif /* CONFIG_BLE_MESH_PROVISIONER */
1879 
1880 void bt_mesh_trans_init(void)
1881 {
1882     int i;
1883 
1884     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
1885         k_delayed_work_init(&seg_tx[i].retransmit, seg_retransmit);
1886     }
1887 
1888     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1889         k_delayed_work_init(&seg_rx[i].ack, seg_ack);
1890         seg_rx[i].buf.__buf = (seg_rx_buf_data +
1891                                (i * CONFIG_BLE_MESH_RX_SDU_MAX));
1892         seg_rx[i].buf.data = seg_rx[i].buf.__buf;
1893     }
1894 
1895     bt_mesh_tx_seg_mutex_new();
1896     bt_mesh_rx_seg_mutex_new();
1897 }
1898 
1899 #if CONFIG_BLE_MESH_DEINIT
1900 void bt_mesh_trans_deinit(bool erase)
1901 {
1902     int i;
1903 
1904     bt_mesh_rx_reset(erase);
1905     bt_mesh_tx_reset();
1906 
1907     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
1908         k_delayed_work_free(&seg_tx[i].retransmit);
1909     }
1910 
1911     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1912         k_delayed_work_free(&seg_rx[i].ack);
1913     }
1914 
1915     bt_mesh_tx_seg_mutex_free();
1916     bt_mesh_rx_seg_mutex_free();
1917 }
1918 #endif /* CONFIG_BLE_MESH_DEINIT */
1919 
1920 void bt_mesh_heartbeat_send(void)
1921 {
1922     struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get();
1923     uint16_t feat = 0U;
1924     struct __packed {
1925         uint8_t  init_ttl;
1926         uint16_t feat;
1927     } hb;
1928     struct bt_mesh_msg_ctx ctx = {
1929         .net_idx = cfg->hb_pub.net_idx,
1930         .app_idx = BLE_MESH_KEY_UNUSED,
1931         .addr = cfg->hb_pub.dst,
1932         .send_ttl = cfg->hb_pub.ttl,
1933     };
1934     struct bt_mesh_net_tx tx = {
1935         .sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx),
1936         .ctx = &ctx,
1937         .src = bt_mesh_model_elem(cfg->model)->addr,
1938         .xmit = bt_mesh_net_transmit_get(),
1939     };
1940 
1941     /* Do nothing if heartbeat publication is not enabled */
1942     if (cfg->hb_pub.dst == BLE_MESH_ADDR_UNASSIGNED) {
1943         return;
1944     }
1945 
1946     hb.init_ttl = cfg->hb_pub.ttl;
1947 
1948     if (bt_mesh_relay_get() == BLE_MESH_RELAY_ENABLED) {
1949         feat |= BLE_MESH_FEAT_RELAY;
1950     }
1951 
1952     if (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_ENABLED) {
1953         feat |= BLE_MESH_FEAT_PROXY;
1954     }
1955 
1956     if (bt_mesh_friend_get() == BLE_MESH_FRIEND_ENABLED) {
1957         feat |= BLE_MESH_FEAT_FRIEND;
1958     }
1959 
1960     if (bt_mesh_lpn_established()) {
1961         feat |= BLE_MESH_FEAT_LOW_POWER;
1962     }
1963 
1964     hb.feat = sys_cpu_to_be16(feat);
1965 
1966     BT_INFO("InitTTL %u feat 0x%04x", cfg->hb_pub.ttl, feat);
1967 
1968     bt_mesh_ctl_send(&tx, TRANS_CTL_OP_HEARTBEAT, &hb, sizeof(hb),
1969                      NULL, NULL);
1970 }
1971 
1972 int bt_mesh_app_key_get(const struct bt_mesh_subnet *subnet, uint16_t app_idx,
1973                         const uint8_t **key, uint8_t *aid, uint8_t role, uint16_t dst)
1974 {
1975     struct bt_mesh_app_key *app_key = NULL;
1976 
1977     if (app_idx == BLE_MESH_KEY_DEV) {
1978         *key = bt_mesh_tx_devkey_get(role, dst);
1979         if (!*key) {
1980             BT_ERR("DevKey not found");
1981             return -EINVAL;
1982         }
1983 
1984         *aid = 0U;
1985         return 0;
1986     }
1987 
1988     if (!subnet) {
1989         BT_ERR("Invalid subnet");
1990         return -EINVAL;
1991     }
1992 
1993     app_key = bt_mesh_tx_appkey_get(role, app_idx);
1994     if (!app_key) {
1995         BT_ERR("Invalid AppKeyIndex 0x%04x", app_idx);
1996         return -ENOENT;
1997     }
1998 
1999     if (subnet->kr_phase == BLE_MESH_KR_PHASE_2 && app_key->updated) {
2000         *key = app_key->keys[1].val;
2001         *aid = app_key->keys[1].id;
2002     } else {
2003         *key = app_key->keys[0].val;
2004         *aid = app_key->keys[0].id;
2005     }
2006 
2007     return 0;
2008 }
2009