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