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