1 /*  Bluetooth Mesh */
2 
3 /*
4  * Copyright (c) 2017 Intel Corporation
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include <ble_os.h>
10 #include <bt_errno.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <misc/util.h>
14 #include <misc/byteorder.h>
15 
16 #include <net/buf.h>
17 
18 #include <bluetooth/hci.h>
19 #include <api/mesh.h>
20 
21 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_TRANS)
22 #include "common/log.h"
23 
24 #include "host/testing.h"
25 
26 #include "crypto.h"
27 #include "adv.h"
28 #include "mesh.h"
29 #include "net.h"
30 #include "lpn.h"
31 #include "friend.h"
32 #include "access.h"
33 #include "foundation.h"
34 #include "settings.h"
35 #include "ble_transport.h"
36 
37 #ifdef CONFIG_BT_MESH_PROVISIONER
38 #include "provisioner_prov.h"
39 #include "provisioner_main.h"
40 #include "provisioner_proxy.h"
41 #endif
42 
43 #ifdef CONFIG_BT_MESH_EVENT_CALLBACK
44 #include "mesh_event_port.h"
45 #endif
46 
47 /* The transport layer needs at least three buffers for itself to avoid
48  * deadlocks. Ensure that there are a sufficient number of advertising
49  * buffers available compared to the maximum supported outgoing segment
50  * count.
51  */
52 BUILD_ASSERT(CONFIG_BT_MESH_ADV_BUF_COUNT >= (CONFIG_BT_MESH_TX_SEG_MAX + 3));
53 
54 #define AID_MASK ((u8_t)(BIT_MASK(6)))
55 
56 #define SEG(data) ((data)[0] >> 7)
57 #define AKF(data) (((data)[0] >> 6) & 0x01)
58 #define AID(data) ((data)[0] & AID_MASK)
59 #define ASZMIC(data) (((data)[1] >> 7) & 1)
60 
61 #define APP_MIC_LEN(aszmic) ((aszmic) ? 8 : 4)
62 
63 #define UNSEG_HDR(akf, aid) ((akf << 6) | (aid & AID_MASK))
64 #define SEG_HDR(akf, aid) (UNSEG_HDR(akf, aid) | 0x80)
65 
66 #define BLOCK_COMPLETE(seg_n) (bt_u32_t)(((u64_t)1 << (seg_n + 1)) - 1)
67 
68 #define SEQ_AUTH(iv_index, seq) (((u64_t)iv_index) << 24 | (u64_t)seq)
69 
70 #ifndef CONFIG_BT_MESH_SEG_RETRANSMIT_ATTEMPTS
71 #define CONFIG_BT_MESH_SEG_RETRANSMIT_ATTEMPTS 4
72 #endif
73 /* Number of retransmit attempts (after the initial transmit) per segment */
74 #define SEG_RETRANSMIT_ATTEMPTS CONFIG_BT_MESH_SEG_RETRANSMIT_ATTEMPTS
75 #ifndef CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT
76 
77 #define CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT 400
78 /* "This timer shall be set to a minimum of 200 + 50 * TTL milliseconds.".
79  * We use 400 since 300 is a common send duration for standard HCI, and we
80  * need to have a timeout that's bigger than that.
81  */
82 #define SEG_RETRANSMIT_TIMEOUT(tx) (K_MSEC(CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT) + 50 * (tx)->ttl)
83 #else
84 #define SEG_RETRANSMIT_TIMEOUT(tx) K_MSEC(CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT)
85 #endif
86 
87 /* How long to wait for available buffers before giving up */
88 #define BUF_TIMEOUT K_NO_WAIT
89 
90 static struct seg_tx {
91     struct bt_mesh_subnet *sub;
92     struct net_buf *seg[CONFIG_BT_MESH_TX_SEG_MAX];
93     u64_t seq_auth;
94     u16_t dst;
95     u8_t seg_n:5, /* Last segment index */
96         new_key:1; /* New/old key */
97     u8_t nack_count; /* Number of unacked segs */
98     u8_t ttl;
99     const struct bt_mesh_send_cb *cb;
100     void *cb_data;
101     struct k_delayed_work retransmit; /* Retransmit timer */
102 } seg_tx[CONFIG_BT_MESH_TX_SEG_MSG_COUNT];
103 
104 static struct seg_rx {
105     struct bt_mesh_subnet *sub;
106     u64_t seq_auth;
107     u8_t seg_n:5, ctl:1, in_use:1, obo:1;
108     u8_t hdr;
109     u8_t ttl;
110     u16_t src;
111     u16_t dst;
112     bt_u32_t block;
113     bt_u32_t last;
114     struct k_delayed_work ack;
115     struct net_buf_simple buf;
116 } seg_rx[CONFIG_BT_MESH_RX_SEG_MSG_COUNT] = {
117 	[0 ... (CONFIG_BT_MESH_RX_SEG_MSG_COUNT - 1)] = {
118 		.buf.size = CONFIG_BT_MESH_RX_SDU_MAX,
119 	},
120 };
121 
122 static u8_t __noinit seg_rx_buf_data[(CONFIG_BT_MESH_RX_SEG_MSG_COUNT * CONFIG_BT_MESH_RX_SDU_MAX)];
123 
124 static u16_t hb_sub_dst = BT_MESH_ADDR_UNASSIGNED;
125 
bt_mesh_set_hb_sub_dst(u16_t addr)126 void bt_mesh_set_hb_sub_dst(u16_t addr)
127 {
128     hb_sub_dst = addr;
129 }
130 
send_unseg(struct bt_mesh_net_tx * tx,struct net_buf_simple * sdu,const struct bt_mesh_send_cb * cb,void * cb_data)131 static int send_unseg(struct bt_mesh_net_tx *tx, struct net_buf_simple *sdu, const struct bt_mesh_send_cb *cb,
132                       void *cb_data)
133 {
134     struct net_buf *buf;
135 
136     BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x sdu_len %u", tx->src, tx->ctx->addr, tx->ctx->app_idx, sdu->len);
137 
138     buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT);
139     if (!buf) {
140         BT_ERR("Out of network buffers");
141         return -ENOBUFS;
142     }
143 
144     net_buf_reserve(buf, BT_MESH_NET_HDR_LEN);
145 
146     if (tx->ctx->app_idx == BT_MESH_KEY_DEV) {
147         net_buf_add_u8(buf, UNSEG_HDR(0, 0));
148     } else {
149         net_buf_add_u8(buf, UNSEG_HDR(1, tx->aid));
150     }
151 
152     net_buf_add_mem(buf, sdu->data, sdu->len);
153 
154     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
155         if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, NULL, &buf->b) &&
156             BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
157             /* PDUs for a specific Friend should only go
158 			 * out through the Friend Queue.
159 			 */
160             net_buf_unref(buf);
161             return 0;
162         }
163     }
164 
165     return bt_mesh_net_send(tx, buf, cb, cb_data);
166 }
167 
bt_mesh_tx_in_progress(void)168 bool bt_mesh_tx_in_progress(void)
169 {
170     int i;
171 
172     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
173         if (seg_tx[i].nack_count) {
174             return true;
175         }
176     }
177 
178     return false;
179 }
180 
seg_tx_reset(struct seg_tx * tx)181 static void seg_tx_reset(struct seg_tx *tx)
182 {
183     int i;
184 
185     k_delayed_work_cancel(&tx->retransmit);
186 
187     tx->cb = NULL;
188     tx->cb_data = NULL;
189     tx->seq_auth = 0;
190     tx->sub = NULL;
191     tx->dst = BT_MESH_ADDR_UNASSIGNED;
192 
193     if (!tx->nack_count) {
194         return;
195     }
196 
197     for (i = 0; i <= tx->seg_n; i++) {
198         if (!tx->seg[i]) {
199             continue;
200         }
201 
202         net_buf_unref(tx->seg[i]);
203         tx->seg[i] = NULL;
204     }
205 
206     tx->nack_count = 0;
207 
208     if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_IVU_PENDING)) {
209         BT_DBG("Proceding with pending IV Update");
210         /* bt_mesh_net_iv_update() will re-enable the flag if this
211 		 * wasn't the only transfer.
212 		 */
213         if (bt_mesh_net_iv_update(bt_mesh.iv_index, false)) {
214             bt_mesh_net_sec_update(NULL);
215         }
216     }
217 }
218 
seg_tx_complete(struct seg_tx * tx,int err)219 static inline void seg_tx_complete(struct seg_tx *tx, int err)
220 {
221     if (tx->cb && tx->cb->end) {
222         tx->cb->end(err, tx->cb_data);
223     }
224 
225     seg_tx_reset(tx);
226 }
227 
seg_first_send_start(u16_t duration,int err,void * user_data)228 static void seg_first_send_start(u16_t duration, int err, void *user_data)
229 {
230     struct seg_tx *tx = user_data;
231 
232     if (tx->cb && tx->cb->start) {
233         tx->cb->start(duration, err, tx->cb_data);
234     }
235 }
236 
seg_send_start(u16_t duration,int err,void * user_data)237 static void seg_send_start(u16_t duration, int err, void *user_data)
238 {
239     struct seg_tx *tx = user_data;
240 
241     /* If there's an error in transmitting the 'sent' callback will never
242 	 * be called. Make sure that we kick the retransmit timer also in this
243 	 * case since otherwise we risk the transmission of becoming stale.
244 	 */
245     if (err && BT_MESH_ADDR_IS_UNICAST(tx->dst)) {
246         k_delayed_work_submit(&tx->retransmit, SEG_RETRANSMIT_TIMEOUT(tx));
247     }
248 }
249 
seg_sent(int err,void * user_data)250 static void seg_sent(int err, void *user_data)
251 {
252     struct seg_tx *tx = user_data;
253     /*[Genie begin] add by lgy at 2020-09-14*/
254     /*Don't retransmit if dst addr is not unicast*/
255     if (!BT_MESH_ADDR_IS_UNICAST(tx->dst)) {
256         seg_tx_complete(tx, -ENOPROTOOPT);
257     } else {
258         k_delayed_work_submit(&tx->retransmit, SEG_RETRANSMIT_TIMEOUT(tx));
259     }
260     /*[Genie end]*/
261 }
262 
263 static const struct bt_mesh_send_cb first_sent_cb = {
264     .start = seg_first_send_start,
265     .end = seg_sent,
266 };
267 
268 static const struct bt_mesh_send_cb seg_sent_cb = {
269     .start = seg_send_start,
270     .end = seg_sent,
271 };
272 
seg_tx_send_unacked(struct seg_tx * tx)273 static void seg_tx_send_unacked(struct seg_tx *tx)
274 {
275     int i, err;
276 
277     for (i = 0; i <= tx->seg_n; i++) {
278         struct net_buf *seg = tx->seg[i];
279 
280         if (!seg) {
281             continue;
282         }
283 
284         if (BT_MESH_ADV(seg)->busy) {
285             BT_DBG("Skipping segment that's still advertising");
286             continue;
287         }
288 
289         if (!(BT_MESH_ADV(seg)->seg.attempts--)) {
290             BT_WARN("Ran out of retransmit attempts");
291             seg_tx_complete(tx, -ETIMEDOUT);
292             return;
293         }
294 
295         if (!tx->nack_count) {
296             return;
297         }
298 
299         BT_DBG("resending %u/%u", i, tx->seg_n);
300 
301         err = bt_mesh_net_resend(tx->sub, seg, tx->new_key, &seg_sent_cb, tx);
302         if (err) {
303             BT_WARN("ReSending segment failed");
304             seg_tx_complete(tx, -EIO);
305             return;
306         }
307     }
308 }
309 
seg_retransmit(struct k_work * work)310 static void seg_retransmit(struct k_work *work)
311 {
312     struct seg_tx *tx = CONTAINER_OF(work, struct seg_tx, retransmit);
313 
314     seg_tx_send_unacked(tx);
315 }
316 
send_seg(struct bt_mesh_net_tx * net_tx,struct net_buf_simple * sdu,const struct bt_mesh_send_cb * cb,void * cb_data)317 static int send_seg(struct bt_mesh_net_tx *net_tx, struct net_buf_simple *sdu, const struct bt_mesh_send_cb *cb,
318                     void *cb_data)
319 {
320     u8_t seg_hdr, seg_o;
321     u16_t seq_zero;
322     struct seg_tx *tx;
323     int i;
324 
325     BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x aszmic %u sdu_len %u", net_tx->src, net_tx->ctx->addr,
326            net_tx->ctx->app_idx, net_tx->aszmic, sdu->len);
327 
328     if (sdu->len < 1) {
329         BT_ERR("Zero-length SDU not allowed");
330         return -EINVAL;
331     }
332 
333     if (((sdu->len + 11) / 12) > CONFIG_BT_MESH_TX_SEG_MAX) {
334         BT_ERR("Not enough segment buffers for length %u", sdu->len);
335         return -EMSGSIZE;
336     }
337 
338     for (tx = NULL, i = 0; i < ARRAY_SIZE(seg_tx); i++) {
339         if (!seg_tx[i].nack_count) {
340             tx = &seg_tx[i];
341             break;
342         }
343     }
344 
345     if (!tx) {
346         BT_ERR("No multi-segment message contexts available");
347         return -EBUSY;
348     }
349 
350     if (net_tx->ctx->app_idx == BT_MESH_KEY_DEV) {
351         seg_hdr = SEG_HDR(0, 0);
352     } else {
353         seg_hdr = SEG_HDR(1, net_tx->aid);
354     }
355 
356     seg_o = 0;
357     tx->dst = net_tx->ctx->addr;
358     tx->seg_n = (sdu->len - 1) / 12;
359     tx->nack_count = tx->seg_n + 1;
360     tx->seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_TX, bt_mesh.seq);
361     tx->sub = net_tx->sub;
362     tx->new_key = net_tx->sub->kr_flag;
363     tx->cb = cb;
364     tx->cb_data = cb_data;
365 
366     if (net_tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) {
367         tx->ttl = bt_mesh_default_ttl_get();
368     } else {
369         tx->ttl = net_tx->ctx->send_ttl;
370     }
371 
372     seq_zero = tx->seq_auth & 0x1fff;
373 
374     BT_DBG("SeqZero 0x%04x", seq_zero);
375 
376     for (seg_o = 0; sdu->len; seg_o++) {
377         struct net_buf *seg;
378         u16_t len;
379         int err;
380 
381         seg = bt_mesh_adv_create(BT_MESH_ADV_DATA, net_tx->xmit, BUF_TIMEOUT);
382         if (!seg) {
383             BT_ERR("Out of segment buffers");
384             seg_tx_reset(tx);
385             return -ENOBUFS;
386         }
387 
388         BT_MESH_ADV(seg)->seg.attempts = SEG_RETRANSMIT_ATTEMPTS;
389 
390         net_buf_reserve(seg, BT_MESH_NET_HDR_LEN);
391 
392         net_buf_add_u8(seg, seg_hdr);
393         net_buf_add_u8(seg, (net_tx->aszmic << 7) | seq_zero >> 6);
394         net_buf_add_u8(seg, (((seq_zero & 0x3f) << 2) | (seg_o >> 3)));
395         net_buf_add_u8(seg, ((seg_o & 0x07) << 5) | tx->seg_n);
396 
397         len = MIN(sdu->len, 12);
398         net_buf_add_mem(seg, sdu->data, len);
399         net_buf_simple_pull(sdu, len);
400 
401         tx->seg[seg_o] = net_buf_ref(seg);
402 
403         if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
404             enum bt_mesh_friend_pdu_type type;
405 
406             if (seg_o == tx->seg_n) {
407                 type = BT_MESH_FRIEND_PDU_COMPLETE;
408             } else {
409                 type = BT_MESH_FRIEND_PDU_PARTIAL;
410             }
411 
412             if (bt_mesh_friend_enqueue_tx(net_tx, type, &tx->seq_auth, &seg->b) &&
413                 BT_MESH_ADDR_IS_UNICAST(net_tx->ctx->addr)) {
414                 /* PDUs for a specific Friend should only go
415 				 * out through the Friend Queue.
416 				 */
417                 net_buf_unref(seg);
418                 return 0;
419             }
420         }
421 
422         BT_DBG("Sending %u/%u", seg_o, tx->seg_n);
423         err = bt_mesh_net_send(net_tx, seg, seg_o ? &seg_sent_cb : &first_sent_cb, tx);
424         if (err) {
425             BT_ERR("Sending segment failed");
426             seg_tx_reset(tx);
427             return err;
428         }
429     }
430 
431     if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && bt_mesh_lpn_established()) {
432         bt_mesh_lpn_poll();
433     }
434 
435     return 0;
436 }
437 
bt_mesh_app_key_find(u16_t app_idx)438 struct bt_mesh_app_key *bt_mesh_app_key_find(u16_t app_idx)
439 {
440     int i;
441 
442     for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
443         struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
444 
445         if (key->net_idx != BT_MESH_KEY_UNUSED && key->app_idx == app_idx) {
446             return key;
447         }
448     }
449 
450     return NULL;
451 }
452 
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)453 int bt_mesh_trans_send(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg, const struct bt_mesh_send_cb *cb,
454                        void *cb_data)
455 {
456     const u8_t *key;
457     u8_t *ad;
458     int err;
459 
460     if (net_buf_simple_tailroom(msg) < 4) {
461         BT_ERR("Insufficient tailroom for Transport MIC");
462         return -EINVAL;
463     }
464 
465     if (msg->len > 11) {
466         tx->ctx->send_rel = 1;
467         /*reduce packect when send large packet to unicast addr to avoid network storm*/
468         if (BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
469             tx->xmit = 0;
470         }
471     }
472 
473     BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->sub->net_idx, tx->ctx->app_idx, tx->ctx->addr);
474     BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len));
475 
476     if (tx->ctx->app_idx == BT_MESH_KEY_DEV) {
477 #ifdef CONFIG_BT_MESH_PROVISIONER
478         // if (bt_mesh_is_provisioner_en() && tx->ctx->addr != bt_mesh_primary_addr()) {
479         key = provisioner_get_device_key(tx->ctx->addr);
480         // } else {
481         if (!key) {
482             key = bt_mesh.dev_key;
483         }
484         // }
485 #else
486         key = bt_mesh.dev_key;
487 #endif
488         tx->aid = 0;
489     } else {
490         struct bt_mesh_app_key *app_key = NULL;
491         // #ifdef CONFIG_BT_MESH_PROVISIONER
492         //    if (bt_mesh_is_provisioner_en()) {
493         //        app_key = provisioner_app_key_find(tx->ctx->app_idx);
494         //    }
495         // #else
496         app_key = bt_mesh_app_key_find(tx->ctx->app_idx);
497         // #endif
498         if (!app_key) {
499             return -EINVAL;
500         }
501 
502         if (tx->sub->kr_phase == BT_MESH_KR_PHASE_2 && app_key->updated) {
503             key = app_key->keys[1].val;
504             tx->aid = app_key->keys[1].id;
505         } else {
506             key = app_key->keys[0].val;
507             tx->aid = app_key->keys[0].id;
508         }
509     }
510 
511     if (!tx->ctx->send_rel || net_buf_simple_tailroom(msg) < 8) {
512         tx->aszmic = 0;
513     } else {
514         tx->aszmic = 1;
515     }
516 
517     if (BT_MESH_ADDR_IS_VIRTUAL(tx->ctx->addr)) {
518         ad = bt_mesh_label_uuid_get(tx->ctx->addr);
519     } else {
520         ad = NULL;
521     }
522 
523     err = bt_mesh_app_encrypt(key, tx->ctx->app_idx == BT_MESH_KEY_DEV, tx->aszmic, msg, ad, tx->src, tx->ctx->addr,
524                               bt_mesh.seq, BT_MESH_NET_IVI_TX);
525     if (err) {
526         return err;
527     }
528 
529     if (tx->ctx->send_rel) {
530         err = send_seg(tx, msg, cb, cb_data);
531     } else {
532         err = send_unseg(tx, msg, cb, cb_data);
533     }
534 
535     return err;
536 }
537 
bt_mesh_trans_resend(struct bt_mesh_net_tx * tx,struct net_buf_simple * msg,const struct bt_mesh_send_cb * cb,void * cb_data)538 int bt_mesh_trans_resend(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg, const struct bt_mesh_send_cb *cb,
539                          void *cb_data)
540 {
541     struct net_buf_simple_state state;
542     int err;
543 
544     net_buf_simple_save(msg, &state);
545 
546     if (tx->ctx->send_rel || msg->len > 15) {
547         err = send_seg(tx, msg, cb, cb_data);
548     } else {
549         err = send_unseg(tx, msg, cb, cb_data);
550     }
551 
552     net_buf_simple_restore(msg, &state);
553 
554     return err;
555 }
556 
is_replay(struct bt_mesh_net_rx * rx)557 static bool is_replay(struct bt_mesh_net_rx *rx)
558 {
559     static uint8_t index = 0;
560     int i = 0;
561     struct bt_mesh_rpl *rpl = NULL;
562 
563     /* Don't bother checking messages from ourselves */
564     if (rx->net_if == BT_MESH_NET_IF_LOCAL) {
565         return false;
566     }
567 
568     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
569         rpl = &bt_mesh.rpl[i];
570 
571         /* Empty slot */
572         if (!rpl->src) {
573             rpl->src = rx->ctx.addr;
574             rpl->seq = rx->seq;
575             rpl->old_iv = rx->old_iv;
576 
577             if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
578                 bt_mesh_store_rpl(rpl);
579             }
580 
581             return false;
582         }
583 
584         /* Existing slot for given address */
585         if (rpl->src == rx->ctx.addr) {
586             if (rx->old_iv && !rpl->old_iv) {
587                 return true;
588             }
589 
590             if ((!rx->old_iv && rpl->old_iv) || rpl->seq < rx->seq) {
591                 rpl->seq = rx->seq;
592                 rpl->old_iv = rx->old_iv;
593 
594                 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
595                     bt_mesh_store_rpl(rpl);
596                 }
597 
598                 return false;
599             } else {
600                 return true;
601             }
602         }
603     }
604 
605     /*[genie begin] changed by lgy at 2020-12-09*/
606     // overlap rpl when it is full
607     BT_WARN("RPL is full:%d", index);
608 
609     rpl = &bt_mesh.rpl[index];
610     rpl->src = rx->ctx.addr;
611     rpl->seq = rx->seq;
612     rpl->old_iv = rx->old_iv;
613 
614     if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
615         bt_mesh_store_rpl(rpl);
616     }
617 
618     index++;
619     index = index % CONFIG_BT_MESH_CRPL;
620 
621 #ifdef CONFIG_BT_MESH_EVENT_CALLBACK
622     mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
623     if (event_cb) {
624         event_cb(BT_MESH_MODEL_EVT_RPL_IS_FULL, NULL);
625     }
626 #endif
627 
628     return false;
629     /*[genie end] changed by lgy at 2020-12-09*/
630 }
631 
sdu_recv(struct bt_mesh_net_rx * rx,bt_u32_t seq,u8_t hdr,u8_t aszmic,struct net_buf_simple * buf)632 static int sdu_recv(struct bt_mesh_net_rx *rx, bt_u32_t seq, u8_t hdr, u8_t aszmic, struct net_buf_simple *buf)
633 {
634     NET_BUF_SIMPLE_DEFINE(sdu, CONFIG_BT_MESH_RX_SDU_MAX - 4);
635     u8_t *ad;
636     u16_t i;
637     int err;
638 
639     BT_DBG("ASZMIC %u AKF %u AID 0x%02x", aszmic, AKF(&hdr), AID(&hdr));
640     BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
641 
642     if (buf->len < 1 + APP_MIC_LEN(aszmic)) {
643         BT_ERR("Too short SDU + MIC");
644         return -EINVAL;
645     }
646 
647     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !rx->local_match) {
648         BT_DBG("Ignoring PDU for LPN 0x%04x of this Friend", rx->ctx.recv_dst);
649         return 0;
650     }
651 
652     if (BT_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) {
653         ad = bt_mesh_label_uuid_get(rx->ctx.recv_dst);
654     } else {
655         ad = NULL;
656     }
657 
658     /* Adjust the length to not contain the MIC at the end */
659     buf->len -= APP_MIC_LEN(aszmic);
660 
661     if (!AKF(&hdr)) {
662         const u8_t *dev_key = NULL;
663 #ifdef CONFIG_BT_MESH_PROVISIONER
664         dev_key = provisioner_get_device_key(rx->ctx.addr);
665         if (!dev_key) {
666             dev_key = bt_mesh.dev_key;
667         }
668 #else
669         dev_key = bt_mesh.dev_key;
670 #endif
671         if (!dev_key) {
672             BT_DBG("%s: get NULL dev_key", __func__);
673             return -EINVAL;
674         }
675         err = bt_mesh_app_decrypt(dev_key, true, aszmic, buf, &sdu, ad, rx->ctx.addr, rx->ctx.recv_dst, seq,
676                                   BT_MESH_NET_IVI_RX(rx));
677         if (err) {
678             BT_ERR("Unable to decrypt with DevKey %d", err);
679             return -EINVAL;
680         }
681 
682         rx->ctx.app_idx = BT_MESH_KEY_DEV;
683         bt_mesh_model_recv(rx, &sdu);
684         return 0;
685     }
686 
687     bt_u32_t array_size = 0;
688     array_size = ARRAY_SIZE(bt_mesh.app_keys);
689 
690     for (i = 0; i < array_size; i++) {
691         struct bt_mesh_app_key *key;
692         struct bt_mesh_app_keys *keys;
693 
694         key = &bt_mesh.app_keys[i];
695 
696         /* Check that this AppKey matches received net_idx */
697         if (key->net_idx != rx->sub->net_idx) {
698             continue;
699         }
700 
701         if (rx->new_key && key->updated) {
702             keys = &key->keys[1];
703         } else {
704             keys = &key->keys[0];
705         }
706 
707         /* Check that the AppKey ID matches */
708         if (AID(&hdr) != keys->id) {
709             continue;
710         }
711 
712         net_buf_simple_reset(&sdu);
713         err = bt_mesh_app_decrypt(keys->val, false, aszmic, buf, &sdu, ad, rx->ctx.addr, rx->ctx.recv_dst, seq,
714                                   BT_MESH_NET_IVI_RX(rx));
715         if (err) {
716             BT_WARN("Unable to decrypt with AppKey 0x%03x", key->app_idx);
717             continue;
718         }
719 
720         rx->ctx.app_idx = key->app_idx;
721 
722         bt_mesh_model_recv(rx, &sdu);
723         return 0;
724     }
725 
726     BT_WARN("No matching AppKey");
727 
728     return -EINVAL;
729 }
730 
seg_tx_lookup(u16_t seq_zero,u8_t obo,u16_t addr)731 static struct seg_tx *seg_tx_lookup(u16_t seq_zero, u8_t obo, u16_t addr)
732 {
733     struct seg_tx *tx;
734     int i;
735 
736     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
737         tx = &seg_tx[i];
738 
739         if ((tx->seq_auth & 0x1fff) != seq_zero) {
740             continue;
741         }
742 
743         if (tx->dst == addr) {
744             return tx;
745         }
746 
747         /* If the expected remote address doesn't match,
748 		 * but the OBO flag is set and this is the first
749 		 * acknowledgement, assume it's a Friend that's
750 		 * responding and therefore accept the message.
751 		 */
752         if (obo && tx->nack_count == tx->seg_n + 1) {
753             tx->dst = addr;
754             return tx;
755         }
756     }
757 
758     return NULL;
759 }
760 
trans_ack(struct bt_mesh_net_rx * rx,u8_t hdr,struct net_buf_simple * buf,u64_t * seq_auth)761 static int trans_ack(struct bt_mesh_net_rx *rx, u8_t hdr, struct net_buf_simple *buf, u64_t *seq_auth)
762 {
763     struct seg_tx *tx;
764     unsigned int bit;
765     bt_u32_t ack;
766     u16_t seq_zero;
767     u8_t obo;
768 
769     if (buf->len < 6) {
770         BT_ERR("Too short ack message");
771         return -EINVAL;
772     }
773 
774     seq_zero = net_buf_simple_pull_be16(buf);
775     obo = seq_zero >> 15;
776     seq_zero = (seq_zero >> 2) & 0x1fff;
777 
778     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match) {
779         BT_DBG("Ack for LPN 0x%04x of this Friend", rx->ctx.recv_dst);
780         /* Best effort - we don't have enough info for true SeqAuth */
781         *seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(rx), seq_zero);
782         return 0;
783     }
784 
785     ack = net_buf_simple_pull_be32(buf);
786 
787     BT_DBG("OBO %u seq_zero 0x%04x ack 0x%08x", obo, seq_zero, ack);
788 
789     tx = seg_tx_lookup(seq_zero, obo, rx->ctx.addr);
790     if (!tx) {
791         BT_WARN("No matching TX context for ack");
792         return -EINVAL;
793     }
794 
795     *seq_auth = tx->seq_auth;
796 
797     if (!ack) {
798         BT_WARN("SDU canceled");
799         seg_tx_complete(tx, -ECANCELED);
800         return 0;
801     }
802 
803     if (find_msb_set(ack) - 1 > tx->seg_n) {
804         BT_ERR("Too large segment number in ack");
805         return -EINVAL;
806     }
807 
808     k_delayed_work_cancel(&tx->retransmit);
809 
810     while ((bit = find_lsb_set(ack))) {
811         if (tx->seg[bit - 1]) {
812             BT_DBG("seg %u/%u acked", bit - 1, tx->seg_n);
813             net_buf_unref(tx->seg[bit - 1]);
814             tx->seg[bit - 1] = NULL;
815             tx->nack_count--;
816         }
817 
818         ack &= ~BIT(bit - 1);
819     }
820 
821     if (tx->nack_count) {
822         // seg_tx_send_unacked(tx);
823         k_delayed_work_submit(&tx->retransmit, 0);
824     } else {
825         BT_DBG("SDU TX complete");
826         seg_tx_complete(tx, 0);
827     }
828 
829     return 0;
830 }
831 
trans_heartbeat(struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)832 static int trans_heartbeat(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
833 {
834     u8_t init_ttl, hops;
835     u16_t feat;
836 
837     if (buf->len < 3) {
838         BT_ERR("Too short heartbeat message");
839         return -EINVAL;
840     }
841 
842     if (rx->ctx.recv_dst != hb_sub_dst) {
843         BT_WARN("Ignoring heartbeat to non-subscribed destination");
844         return 0;
845     }
846 
847     init_ttl = (net_buf_simple_pull_u8(buf) & 0x7f);
848     feat = net_buf_simple_pull_be16(buf);
849 
850     hops = (init_ttl - rx->ctx.recv_ttl + 1);
851 
852     BT_DBG("src 0x%04x TTL %u InitTTL %u (%u hop%s) feat 0x%04x", rx->ctx.addr, rx->ctx.recv_ttl, init_ttl, hops,
853            (hops == 1) ? "" : "s", feat);
854 
855     bt_mesh_heartbeat(rx->ctx.addr, rx->ctx.recv_dst, hops, feat);
856 
857     return 0;
858 }
859 
ctl_recv(struct bt_mesh_net_rx * rx,u8_t hdr,struct net_buf_simple * buf,u64_t * seq_auth)860 static int ctl_recv(struct bt_mesh_net_rx *rx, u8_t hdr, struct net_buf_simple *buf, u64_t *seq_auth)
861 {
862     u8_t ctl_op = TRANS_CTL_OP(&hdr);
863 
864     BT_DBG("OpCode 0x%02x len %u", ctl_op, buf->len);
865 
866     switch (ctl_op) {
867     case TRANS_CTL_OP_ACK:
868         return trans_ack(rx, hdr, buf, seq_auth);
869     case TRANS_CTL_OP_HEARTBEAT:
870         return trans_heartbeat(rx, buf);
871 /*[Genie begin] add by wenbing.cwb at 2021-01-21*/
872 #ifdef CONFIG_BT_MESH_CTRL_RELAY
873     case TRANS_CTL_OP_CTRL_RELAY_STATUS:
874     case TRANS_CTL_OP_CTRL_RELAY_REQ:
875     case TRANS_CTL_OP_CTRL_RELAY_OPEN:
876         return ctrl_relay_msg_recv(ctl_op, rx, buf);
877 #endif
878         /*[Genie end] add by wenbing.cwb at 2021-01-21*/
879     }
880 
881     /* Only acks and heartbeats may need processing without local_match */
882     if (!rx->local_match) {
883         return 0;
884     }
885 
886     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !bt_mesh_lpn_established()) {
887         switch (ctl_op) {
888         case TRANS_CTL_OP_FRIEND_POLL:
889             return bt_mesh_friend_poll(rx, buf);
890         case TRANS_CTL_OP_FRIEND_REQ:
891             return bt_mesh_friend_req(rx, buf);
892         case TRANS_CTL_OP_FRIEND_CLEAR:
893             return bt_mesh_friend_clear(rx, buf);
894         case TRANS_CTL_OP_FRIEND_CLEAR_CFM:
895             return bt_mesh_friend_clear_cfm(rx, buf);
896         case TRANS_CTL_OP_FRIEND_SUB_ADD:
897             return bt_mesh_friend_sub_add(rx, buf);
898         case TRANS_CTL_OP_FRIEND_SUB_REM:
899             return bt_mesh_friend_sub_rem(rx, buf);
900         }
901     }
902 
903 #if defined(CONFIG_BT_MESH_LOW_POWER)
904     if (ctl_op == TRANS_CTL_OP_FRIEND_OFFER) {
905         return bt_mesh_lpn_friend_offer(rx, buf);
906     }
907 
908     if (rx->ctx.addr == bt_mesh.lpn.frnd) {
909         if (ctl_op == TRANS_CTL_OP_FRIEND_CLEAR_CFM) {
910             return bt_mesh_lpn_friend_clear_cfm(rx, buf);
911         }
912 
913         if (!rx->friend_cred) {
914             BT_WARN("Message from friend with wrong credentials");
915             return -EINVAL;
916         }
917 
918         switch (ctl_op) {
919         case TRANS_CTL_OP_FRIEND_UPDATE:
920             return bt_mesh_lpn_friend_update(rx, buf);
921         case TRANS_CTL_OP_FRIEND_SUB_CFM:
922             return bt_mesh_lpn_friend_sub_cfm(rx, buf);
923         }
924     }
925 #endif /* CONFIG_BT_MESH_LOW_POWER */
926 
927     BT_WARN("Unhandled TransOpCode 0x%02x", ctl_op);
928 
929     return -ENOENT;
930 }
931 
trans_unseg(struct net_buf_simple * buf,struct bt_mesh_net_rx * rx,u64_t * seq_auth)932 static int trans_unseg(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx, u64_t *seq_auth)
933 {
934     u8_t hdr;
935 
936     BT_DBG("AFK %u AID 0x%02x", AKF(buf->data), AID(buf->data));
937 
938     if (buf->len < 1) {
939         BT_ERR("Too small unsegmented PDU");
940         return -EINVAL;
941     }
942 
943     if (rx->local_match && is_replay(rx)) {
944         BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", rx->ctx.addr, rx->ctx.recv_dst, rx->seq);
945         return -EINVAL;
946     }
947 
948     hdr = net_buf_simple_pull_u8(buf);
949 
950     if (rx->ctl) {
951         return ctl_recv(rx, hdr, buf, seq_auth);
952     } else {
953         /* SDUs must match a local element or an LPN of this Friend. */
954         if (!rx->local_match && !rx->friend_match) {
955             return 0;
956         }
957 
958         return sdu_recv(rx, rx->seq, hdr, 0, buf);
959     }
960 }
961 
ack_timeout(struct seg_rx * rx)962 static inline bt_s32_t ack_timeout(struct seg_rx *rx)
963 {
964     bt_s32_t to;
965     u8_t ttl;
966 
967     if (rx->ttl == BT_MESH_TTL_DEFAULT) {
968         ttl = bt_mesh_default_ttl_get();
969     } else {
970         ttl = rx->ttl;
971     }
972 
973     /* The acknowledgment timer shall be set to a minimum of
974 	 * 150 + 50 * TTL milliseconds.
975 	 */
976     to = K_MSEC(150 + (50 * ttl));
977 
978     /* 100 ms for every not yet received segment */
979     to += K_MSEC(((rx->seg_n + 1) - popcount(rx->block)) * 100);
980 
981     /* Make sure we don't send more frequently than the duration for
982 	 * each packet (default is 300ms).
983 	 */
984     return MAX(to, K_MSEC(400));
985 }
986 
bt_mesh_ctl_send(struct bt_mesh_net_tx * tx,u8_t ctl_op,void * data,size_t data_len,u64_t * seq_auth,const struct bt_mesh_send_cb * cb,void * cb_data)987 int bt_mesh_ctl_send(struct bt_mesh_net_tx *tx, u8_t ctl_op, void *data, size_t data_len, u64_t *seq_auth,
988                      const struct bt_mesh_send_cb *cb, void *cb_data)
989 {
990     struct net_buf *buf;
991 
992     BT_DBG("src 0x%04x dst 0x%04x ttl 0x%02x ctl 0x%02x", tx->src, tx->ctx->addr, tx->ctx->send_ttl, ctl_op);
993     BT_DBG("len %zu: %s", data_len, bt_hex(data, data_len));
994 
995     buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT);
996     if (!buf) {
997         BT_ERR("Out of transport buffers");
998         return -ENOBUFS;
999     }
1000 
1001     net_buf_reserve(buf, BT_MESH_NET_HDR_LEN);
1002 
1003     net_buf_add_u8(buf, TRANS_CTL_HDR(ctl_op, 0));
1004 
1005     net_buf_add_mem(buf, data, data_len);
1006 
1007     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
1008         if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, seq_auth, &buf->b) &&
1009             BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
1010             /* PDUs for a specific Friend should only go
1011 			 * out through the Friend Queue.
1012 			 */
1013             net_buf_unref(buf);
1014             return 0;
1015         }
1016     }
1017 
1018     return bt_mesh_net_send(tx, buf, cb, cb_data);
1019 }
1020 
send_ack(struct bt_mesh_subnet * sub,u16_t src,u16_t dst,u8_t ttl,u64_t * seq_auth,bt_u32_t block,u8_t obo)1021 static int send_ack(struct bt_mesh_subnet *sub, u16_t src, u16_t dst, u8_t ttl, u64_t *seq_auth, bt_u32_t block,
1022                     u8_t obo)
1023 {
1024     struct bt_mesh_msg_ctx ctx = {
1025         .net_idx = sub->net_idx,
1026         .app_idx = BT_MESH_KEY_UNUSED,
1027         .addr = dst,
1028         .send_ttl = ttl,
1029     };
1030     struct bt_mesh_net_tx tx = {
1031         .sub = sub,
1032         .ctx = &ctx,
1033         .src = obo ? bt_mesh_primary_addr() : src,
1034         .xmit = bt_mesh_net_transmit_get(),
1035     };
1036     u16_t seq_zero = *seq_auth & 0x1fff;
1037     u8_t buf[6];
1038 
1039     BT_DBG("SeqZero 0x%04x Block 0x%08x OBO %u", seq_zero, block, obo);
1040 
1041     if (bt_mesh_lpn_established()) {
1042         BT_WARN("Not sending ack when LPN is enabled");
1043         return 0;
1044     }
1045 
1046     /* This can happen if the segmented message was destined for a group
1047 	 * or virtual address.
1048 	 */
1049     if (!BT_MESH_ADDR_IS_UNICAST(src)) {
1050         BT_WARN("Not sending ack for non-unicast address");
1051         return 0;
1052     }
1053 
1054     sys_put_be16(((seq_zero << 2) & 0x7ffc) | (obo << 15), buf);
1055     sys_put_be32(block, &buf[2]);
1056 
1057     return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_ACK, buf, sizeof(buf), NULL, NULL, NULL);
1058 }
1059 
seg_rx_reset(struct seg_rx * rx,bool full_reset)1060 static void seg_rx_reset(struct seg_rx *rx, bool full_reset)
1061 {
1062     BT_DBG("rx %p", rx);
1063 
1064     k_delayed_work_cancel(&rx->ack);
1065 
1066     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->obo && rx->block != BLOCK_COMPLETE(rx->seg_n)) {
1067         BT_WARN("Clearing incomplete buffers from Friend queue");
1068         bt_mesh_friend_clear_incomplete(rx->sub, rx->src, rx->dst, &rx->seq_auth);
1069     }
1070 
1071     rx->in_use = 0;
1072 
1073     /* We don't always reset these values since we need to be able to
1074 	 * send an ack if we receive a segment after we've already received
1075 	 * the full SDU.
1076 	 */
1077     if (full_reset) {
1078         rx->seq_auth = 0;
1079         rx->sub = NULL;
1080         rx->src = BT_MESH_ADDR_UNASSIGNED;
1081         rx->dst = BT_MESH_ADDR_UNASSIGNED;
1082     }
1083 }
1084 
seg_ack(struct k_work * work)1085 static void seg_ack(struct k_work *work)
1086 {
1087     struct seg_rx *rx = CONTAINER_OF(work, struct seg_rx, ack);
1088 
1089     BT_DBG("rx %p", rx);
1090 
1091     if (k_uptime_get_32() - rx->last > K_SECONDS(60)) {
1092         BT_WARN("Incomplete timer expired");
1093         seg_rx_reset(rx, false);
1094         if (IS_ENABLED(CONFIG_BT_TESTING)) {
1095             bt_test_mesh_trans_incomp_timer_exp();
1096         }
1097 
1098         return;
1099     }
1100 
1101     send_ack(rx->sub, rx->dst, rx->src, rx->ttl, &rx->seq_auth, rx->block, rx->obo);
1102 
1103     k_delayed_work_submit(&rx->ack, ack_timeout(rx));
1104 }
1105 
seg_len(bool ctl)1106 static inline u8_t seg_len(bool ctl)
1107 {
1108     if (ctl) {
1109         return 8;
1110     } else {
1111         return 12;
1112     }
1113 }
1114 
sdu_len_is_ok(bool ctl,u8_t seg_n)1115 static inline bool sdu_len_is_ok(bool ctl, u8_t seg_n)
1116 {
1117     return ((seg_n * seg_len(ctl) + 1) <= CONFIG_BT_MESH_RX_SDU_MAX);
1118 }
1119 
seg_rx_find(struct bt_mesh_net_rx * net_rx,const u64_t * seq_auth)1120 static struct seg_rx *seg_rx_find(struct bt_mesh_net_rx *net_rx, const u64_t *seq_auth)
1121 {
1122     int i;
1123 
1124     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1125         struct seg_rx *rx = &seg_rx[i];
1126 
1127         if (rx->src != net_rx->ctx.addr || rx->dst != net_rx->ctx.recv_dst) {
1128             continue;
1129         }
1130 
1131         /* Return newer RX context in addition to an exact match, so
1132 		 * the calling function can properly discard an old SeqAuth.
1133 		 */
1134         if (rx->seq_auth >= *seq_auth) {
1135             return rx;
1136         }
1137 
1138         if (rx->in_use) {
1139             BT_WARN("Duplicate SDU from src 0x%04x", net_rx->ctx.addr);
1140 
1141             /* Clear out the old context since the sender
1142 			 * has apparently started sending a new SDU.
1143 			 */
1144             seg_rx_reset(rx, true);
1145 
1146             /* Return non-match so caller can re-allocate */
1147             return NULL;
1148         }
1149     }
1150 
1151     return NULL;
1152 }
1153 
seg_rx_is_valid(struct seg_rx * rx,struct bt_mesh_net_rx * net_rx,const u8_t * hdr,u8_t seg_n)1154 static bool seg_rx_is_valid(struct seg_rx *rx, struct bt_mesh_net_rx *net_rx, const u8_t *hdr, u8_t seg_n)
1155 {
1156     if (rx->hdr != *hdr || rx->seg_n != seg_n) {
1157         BT_ERR("Invalid segment for ongoing session");
1158         return false;
1159     }
1160 
1161     if (rx->src != net_rx->ctx.addr || rx->dst != net_rx->ctx.recv_dst) {
1162         BT_ERR("Invalid source or destination for segment");
1163         return false;
1164     }
1165 
1166     if (rx->ctl != net_rx->ctl) {
1167         BT_ERR("Inconsistent CTL in segment");
1168         return false;
1169     }
1170 
1171     return true;
1172 }
1173 
seg_rx_alloc(struct bt_mesh_net_rx * net_rx,const u8_t * hdr,const u64_t * seq_auth,u8_t seg_n)1174 static struct seg_rx *seg_rx_alloc(struct bt_mesh_net_rx *net_rx, const u8_t *hdr, const u64_t *seq_auth, u8_t seg_n)
1175 {
1176     int i;
1177 
1178     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1179         struct seg_rx *rx = &seg_rx[i];
1180 
1181         if (rx->in_use) {
1182             continue;
1183         }
1184 
1185         rx->in_use = 1;
1186         net_buf_simple_reset(&rx->buf);
1187         rx->sub = net_rx->sub;
1188         rx->ctl = net_rx->ctl;
1189         rx->seq_auth = *seq_auth;
1190         rx->seg_n = seg_n;
1191         rx->hdr = *hdr;
1192         rx->ttl = net_rx->ctx.send_ttl;
1193         rx->src = net_rx->ctx.addr;
1194         rx->dst = net_rx->ctx.recv_dst;
1195         rx->block = 0;
1196 
1197         BT_DBG("New RX context. Block Complete 0x%08x", BLOCK_COMPLETE(seg_n));
1198 
1199         return rx;
1200     }
1201 
1202     return NULL;
1203 }
1204 
trans_seg(struct net_buf_simple * buf,struct bt_mesh_net_rx * net_rx,enum bt_mesh_friend_pdu_type * pdu_type,u64_t * seq_auth)1205 static int trans_seg(struct net_buf_simple *buf, struct bt_mesh_net_rx *net_rx, enum bt_mesh_friend_pdu_type *pdu_type,
1206                      u64_t *seq_auth)
1207 {
1208     struct seg_rx *rx;
1209     u8_t *hdr = buf->data;
1210     u16_t seq_zero;
1211     u8_t seg_n;
1212     u8_t seg_o;
1213     int err;
1214 
1215     if (buf->len < 5) {
1216         BT_ERR("Too short segmented message (len %u)", buf->len);
1217         return -EINVAL;
1218     }
1219 
1220     BT_DBG("ASZMIC %u AKF %u AID 0x%02x", ASZMIC(hdr), AKF(hdr), AID(hdr));
1221 
1222     net_buf_simple_pull(buf, 1);
1223 
1224     seq_zero = net_buf_simple_pull_be16(buf);
1225     seg_o = (seq_zero & 0x03) << 3;
1226     seq_zero = (seq_zero >> 2) & 0x1fff;
1227     seg_n = net_buf_simple_pull_u8(buf);
1228     seg_o |= seg_n >> 5;
1229     seg_n &= 0x1f;
1230 
1231     BT_DBG("SeqZero 0x%04x SegO %u SegN %u", seq_zero, seg_o, seg_n);
1232 
1233     if (seg_o > seg_n) {
1234         BT_ERR("SegO greater than SegN (%u > %u)", seg_o, seg_n);
1235         return -EINVAL;
1236     }
1237 
1238     /* According to Mesh 1.0 specification:
1239 	 * "The SeqAuth is composed of the IV Index and the sequence number
1240 	 *  (SEQ) of the first segment"
1241 	 *
1242 	 * Therefore we need to calculate very first SEQ in order to find
1243 	 * seqAuth. We can calculate as below:
1244 	 *
1245 	 * SEQ(0) = SEQ(n) - (delta between seqZero and SEQ(n) by looking into
1246 	 * 14 least significant bits of SEQ(n))
1247 	 *
1248 	 * Mentioned delta shall be >= 0, if it is not then seq_auth will
1249 	 * be broken and it will be verified by the code below.
1250 	 */
1251     *seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(net_rx),
1252                          (net_rx->seq - ((((net_rx->seq & BIT_MASK(14)) - seq_zero)) & BIT_MASK(13))));
1253 
1254     /* Look for old RX sessions */
1255     rx = seg_rx_find(net_rx, seq_auth);
1256     if (rx) {
1257         /* Discard old SeqAuth packet */
1258         if (rx->seq_auth > *seq_auth) {
1259             BT_WARN("Ignoring old SeqAuth");
1260             return -EINVAL;
1261         }
1262 
1263         if (!seg_rx_is_valid(rx, net_rx, hdr, seg_n)) {
1264             return -EINVAL;
1265         }
1266 
1267         if (rx->in_use) {
1268             BT_DBG("Existing RX context. Block 0x%08x", rx->block);
1269             goto found_rx;
1270         }
1271 
1272         if (rx->block == BLOCK_COMPLETE(rx->seg_n)) {
1273             BT_WARN("Got segment for already complete SDU");
1274             send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, rx->block,
1275                      rx->obo);
1276             return -EALREADY;
1277         }
1278 
1279         /* We ignore instead of sending block ack 0 since the
1280 		 * ack timer is always smaller than the incomplete
1281 		 * timer, i.e. the sender is misbehaving.
1282 		 */
1283         BT_WARN("Got segment for canceled SDU");
1284         return -EINVAL;
1285     }
1286 
1287     /* Bail out early if we're not ready to receive such a large SDU */
1288     if (!sdu_len_is_ok(net_rx->ctl, seg_n)) {
1289         BT_ERR("Too big incoming SDU length");
1290         send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, 0,
1291                  net_rx->friend_match);
1292         return -EMSGSIZE;
1293     }
1294 
1295     /* Look for free slot for a new RX session */
1296     rx = seg_rx_alloc(net_rx, hdr, seq_auth, seg_n);
1297     if (!rx) {
1298         /* Warn but don't cancel since the existing slots willl
1299 		 * eventually be freed up and we'll be able to process
1300 		 * this one.
1301 		 */
1302         BT_WARN("No free slots for new incoming segmented messages");
1303         return -ENOMEM;
1304     }
1305 
1306     rx->obo = net_rx->friend_match;
1307 
1308 found_rx:
1309     if (BIT(seg_o) & rx->block) {
1310         BT_DBG("Received already received fragment");
1311         return -EALREADY;
1312     }
1313 
1314     /* All segments, except the last one, must either have 8 bytes of
1315 	 * payload (for 64bit Net MIC) or 12 bytes of payload (for 32bit
1316 	 * Net MIC).
1317 	 */
1318     if (seg_o == seg_n) {
1319         /* Set the expected final buffer length */
1320         rx->buf.len = seg_n * seg_len(rx->ctl) + buf->len;
1321         BT_DBG("Target len %u * %u + %u = %u", seg_n, seg_len(rx->ctl), buf->len, rx->buf.len);
1322 
1323         if (rx->buf.len > CONFIG_BT_MESH_RX_SDU_MAX) {
1324             BT_ERR("Too large SDU len");
1325             send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, 0, rx->obo);
1326             seg_rx_reset(rx, true);
1327             return -EMSGSIZE;
1328         }
1329     } else {
1330         if (buf->len != seg_len(rx->ctl)) {
1331             BT_ERR("Incorrect segment size for message type");
1332             return -EINVAL;
1333         }
1334     }
1335 
1336     /* Reset the Incomplete Timer */
1337     rx->last = k_uptime_get_32();
1338 
1339     if (!k_delayed_work_remaining_get(&rx->ack) && !bt_mesh_lpn_established()) {
1340         k_delayed_work_submit(&rx->ack, ack_timeout(rx));
1341     }
1342 
1343     /* Location in buffer can be calculated based on seg_o & rx->ctl */
1344     memcpy(rx->buf.data + (seg_o * seg_len(rx->ctl)), buf->data, buf->len);
1345 
1346     BT_DBG("Received %u/%u", seg_o, seg_n);
1347 
1348     /* Mark segment as received */
1349     rx->block |= BIT(seg_o);
1350 
1351     if (rx->block != BLOCK_COMPLETE(seg_n)) {
1352         *pdu_type = BT_MESH_FRIEND_PDU_PARTIAL;
1353         return 0;
1354     }
1355 
1356     BT_DBG("Complete SDU");
1357 
1358     if (net_rx->local_match && is_replay(net_rx)) {
1359         BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", net_rx->ctx.addr, net_rx->ctx.recv_dst, net_rx->seq);
1360         /* Clear the segment's bit */
1361         rx->block &= ~BIT(seg_o);
1362         return -EINVAL;
1363     }
1364 
1365     *pdu_type = BT_MESH_FRIEND_PDU_COMPLETE;
1366 
1367     k_delayed_work_cancel(&rx->ack);
1368     send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, rx->block, rx->obo);
1369 
1370     if (net_rx->ctl) {
1371         err = ctl_recv(net_rx, *hdr, &rx->buf, seq_auth);
1372     } else {
1373         err = sdu_recv(net_rx, (rx->seq_auth & 0xffffff), *hdr, ASZMIC(hdr), &rx->buf);
1374     }
1375 
1376     seg_rx_reset(rx, false);
1377 
1378     return err;
1379 }
1380 
bt_mesh_trans_recv(struct net_buf_simple * buf,struct bt_mesh_net_rx * rx)1381 int bt_mesh_trans_recv(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx)
1382 {
1383     u64_t seq_auth = TRANS_SEQ_AUTH_NVAL;
1384     enum bt_mesh_friend_pdu_type pdu_type = BT_MESH_FRIEND_PDU_SINGLE;
1385     struct net_buf_simple_state state;
1386     int err;
1387 
1388     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
1389         rx->friend_match = bt_mesh_friend_match(rx->sub->net_idx, rx->ctx.recv_dst);
1390     } else {
1391         rx->friend_match = false;
1392     }
1393 
1394     BT_DBG("src 0x%04x dst 0x%04x seq 0x%08x friend_match %u", rx->ctx.addr, rx->ctx.recv_dst, rx->seq,
1395            rx->friend_match);
1396 
1397     /* Remove network headers */
1398     net_buf_simple_pull(buf, BT_MESH_NET_HDR_LEN);
1399 
1400     BT_DBG("Payload %s", bt_hex(buf->data, buf->len));
1401 
1402     if (IS_ENABLED(CONFIG_BT_TESTING)) {
1403         bt_test_mesh_net_recv(rx->ctx.recv_ttl, rx->ctl, rx->ctx.addr, rx->ctx.recv_dst, buf->data, buf->len);
1404     }
1405 
1406     /* If LPN mode is enabled messages are only accepted when we've
1407 	 * requested the Friend to send them. The messages must also
1408 	 * be encrypted using the Friend Credentials.
1409 	 */
1410     if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && bt_mesh_lpn_established() && rx->net_if == BT_MESH_NET_IF_ADV &&
1411         (!bt_mesh_lpn_waiting_update() || !rx->friend_cred)) {
1412         BT_WARN("Ignoring unexpected message in Low Power mode");
1413         return -EAGAIN;
1414     }
1415 
1416     /* Save the app-level state so the buffer can later be placed in
1417 	 * the Friend Queue.
1418 	 */
1419     net_buf_simple_save(buf, &state);
1420 
1421     if (SEG(buf->data)) {
1422         /* Segmented messages must match a local element or an
1423 		 * LPN of this Friend.
1424 		 */
1425         if (!rx->local_match && !rx->friend_match) {
1426             return 0;
1427         }
1428 
1429         err = trans_seg(buf, rx, &pdu_type, &seq_auth);
1430     } else {
1431         err = trans_unseg(buf, rx, &seq_auth);
1432     }
1433 
1434     /* Notify LPN state machine so a Friend Poll will be sent. If the
1435 	 * message was a Friend Update it's possible that a Poll was already
1436 	 * queued for sending, however that's fine since then the
1437 	 * bt_mesh_lpn_waiting_update() function will return false:
1438 	 * we still need to go through the actual sending to the bearer and
1439 	 * wait for ReceiveDelay before transitioning to WAIT_UPDATE state.
1440 	 * Another situation where we want to notify the LPN state machine
1441 	 * is if it's configured to use an automatic Friendship establishment
1442 	 * timer, in which case we want to reset the timer at this point.
1443 	 *
1444 	 */
1445     if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) &&
1446         (bt_mesh_lpn_timer() || (bt_mesh_lpn_established() && bt_mesh_lpn_waiting_update()))) {
1447         bt_mesh_lpn_msg_received(rx);
1448     }
1449 
1450     net_buf_simple_restore(buf, &state);
1451 
1452     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match && !err) {
1453         if (seq_auth == TRANS_SEQ_AUTH_NVAL) {
1454             bt_mesh_friend_enqueue_rx(rx, pdu_type, NULL, buf);
1455         } else {
1456             bt_mesh_friend_enqueue_rx(rx, pdu_type, &seq_auth, buf);
1457         }
1458     }
1459 
1460     return err;
1461 }
1462 
bt_mesh_rx_reset(void)1463 void bt_mesh_rx_reset(void)
1464 {
1465     int i;
1466 
1467     BT_DBG("");
1468 
1469     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1470         seg_rx_reset(&seg_rx[i], true);
1471     }
1472 
1473     if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1474         bt_mesh_clear_rpl();
1475     } else {
1476         memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
1477     }
1478 }
1479 
bt_mesh_tx_reset(void)1480 void bt_mesh_tx_reset(void)
1481 {
1482     int i;
1483 
1484     BT_DBG("");
1485 
1486     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
1487         seg_tx_reset(&seg_tx[i]);
1488     }
1489 }
1490 
bt_mesh_trans_init(void)1491 void bt_mesh_trans_init(void)
1492 {
1493     int i;
1494     BT_INFO("enter %s\n", __func__);
1495     for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
1496         k_delayed_work_init(&seg_tx[i].retransmit, seg_retransmit);
1497     }
1498 
1499     for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
1500         k_delayed_work_init(&seg_rx[i].ack, seg_ack);
1501         seg_rx[i].buf.__buf = (seg_rx_buf_data + (i * CONFIG_BT_MESH_RX_SDU_MAX));
1502         seg_rx[i].buf.data = seg_rx[i].buf.__buf;
1503     }
1504 }
1505 
bt_mesh_rpl_clear(void)1506 void bt_mesh_rpl_clear(void)
1507 {
1508     BT_DBG("");
1509     memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
1510 }
1511 
bt_mesh_rpl_clear_all(void)1512 void bt_mesh_rpl_clear_all(void)
1513 {
1514     BT_DBG("");
1515 
1516     if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1517         bt_mesh_clear_all_node_rpl();
1518     }
1519     memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
1520 }
1521 
bt_mesh_rpl_clear_node(uint16_t unicast_addr,uint8_t elem_num)1522 void bt_mesh_rpl_clear_node(uint16_t unicast_addr, uint8_t elem_num)
1523 {
1524     int i = 0;
1525     struct bt_mesh_rpl *rpl = NULL;
1526     BT_DBG("");
1527 
1528     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
1529         rpl = &bt_mesh.rpl[i];
1530         if (rpl->src >= unicast_addr && rpl->src < unicast_addr + elem_num) {
1531             if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1532                 bt_mesh_clear_node_rpl(rpl->src);
1533             }
1534             memset(rpl, 0, sizeof(struct bt_mesh_rpl));
1535         }
1536     }
1537 }
1538