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