1 /*
2  * Copyright (c) 2017 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdint.h>
8 
9 #include "adv.h"
10 #include "subnet.h"
11 #include <zephyr/bluetooth/mesh/keys.h>
12 #include <zephyr/bluetooth/mesh/sar_cfg.h>
13 #include <zephyr/kernel.h>
14 #include <zephyr/net_buf.h>
15 #include <zephyr/sys/atomic.h>
16 #include <zephyr/sys/slist.h>
17 
18 #define BT_MESH_IV_UPDATE(flags)   ((flags >> 1) & 0x01)
19 #define BT_MESH_KEY_REFRESH(flags) (flags & 0x01)
20 
21 /* How many hours in between updating IVU duration */
22 #define BT_MESH_IVU_MIN_HOURS      96
23 #define BT_MESH_IVU_HOURS          (BT_MESH_IVU_MIN_HOURS /     \
24 				    CONFIG_BT_MESH_IVU_DIVIDER)
25 #define BT_MESH_IVU_TIMEOUT        K_HOURS(BT_MESH_IVU_HOURS)
26 
27 /* Minimum valid Mesh Network PDU length. The Network headers
28  * themselves take up 9 bytes. After that there is a minimum of 1 byte
29  * payload for both CTL=1 and CTL=0 PDUs (smallest OpCode is 1 byte). CTL=1
30  * PDUs must use a 64-bit (8 byte) NetMIC, whereas CTL=0 PDUs have at least
31  * a 32-bit (4 byte) NetMIC and AppMIC giving again a total of 8 bytes.
32  */
33 #define BT_MESH_NET_MIN_PDU_LEN (BT_MESH_NET_HDR_LEN + 1 + 8)
34 /* Maximum valid Mesh Network PDU length. The longest packet can either be a
35  * transport control message (CTL=1) of 12 bytes + 8 bytes of NetMIC, or an
36  * access message (CTL=0) of 16 bytes + 4 bytes of NetMIC.
37  */
38 #define BT_MESH_NET_MAX_PDU_LEN (BT_MESH_NET_HDR_LEN + 16 + 4)
39 
40 struct bt_mesh_net_cred;
41 enum bt_mesh_nonce_type;
42 
43 struct bt_mesh_node {
44 	uint16_t addr;
45 	uint16_t net_idx;
46 	struct bt_mesh_key dev_key;
47 	uint8_t  num_elem;
48 };
49 
50 #if defined(CONFIG_BT_MESH_FRIEND)
51 #define FRIEND_SEG_RX CONFIG_BT_MESH_FRIEND_SEG_RX
52 #define FRIEND_SUB_LIST_SIZE CONFIG_BT_MESH_FRIEND_SUB_LIST_SIZE
53 #else
54 #define FRIEND_SEG_RX 0
55 #define FRIEND_SUB_LIST_SIZE 0
56 #endif
57 
58 struct bt_mesh_friend {
59 	uint16_t lpn;
60 	uint8_t  recv_delay;
61 	uint8_t  fsn:1,
62 	      send_last:1,
63 	      pending_req:1,
64 	      pending_buf:1,
65 	      established:1;
66 	int32_t poll_to;
67 	uint8_t  num_elem;
68 	uint16_t lpn_counter;
69 	uint16_t counter;
70 
71 	struct bt_mesh_subnet *subnet;
72 
73 	struct bt_mesh_net_cred cred[2];
74 
75 	uint16_t sub_list[FRIEND_SUB_LIST_SIZE];
76 
77 	struct k_work_delayable timer;
78 
79 	struct bt_mesh_friend_seg {
80 		sys_slist_t queue;
81 
82 		/* The target number of segments, i.e. not necessarily
83 		 * the current number of segments, in the queue. This is
84 		 * used for Friend Queue free space calculations.
85 		 */
86 		uint8_t        seg_count;
87 	} seg[FRIEND_SEG_RX];
88 
89 	struct net_buf *last;
90 
91 	sys_slist_t queue;
92 	uint32_t queue_size;
93 
94 	/* Friend Clear Procedure */
95 	struct {
96 		uint32_t start;                  /* Clear Procedure start */
97 		uint16_t frnd;                   /* Previous Friend's address */
98 		uint16_t repeat_sec;             /* Repeat timeout in seconds */
99 		struct k_work_delayable timer;   /* Repeat timer */
100 	} clear;
101 };
102 
103 #if defined(CONFIG_BT_MESH_LOW_POWER)
104 #define LPN_GROUPS CONFIG_BT_MESH_LPN_GROUPS
105 #else
106 #define LPN_GROUPS 0
107 #endif
108 
109 /* Low Power Node state */
110 struct bt_mesh_lpn {
111 	enum __packed {
112 		BT_MESH_LPN_DISABLED,     /* LPN feature is disabled */
113 		BT_MESH_LPN_CLEAR,        /* Clear in progress */
114 		BT_MESH_LPN_TIMER,        /* Waiting for auto timer expiry */
115 		BT_MESH_LPN_ENABLED,      /* LPN enabled, but no Friend */
116 		BT_MESH_LPN_REQ_WAIT,     /* Wait before scanning for offers */
117 		BT_MESH_LPN_WAIT_OFFER,   /* Friend Req sent */
118 		BT_MESH_LPN_ESTABLISHED,  /* Friendship established */
119 		BT_MESH_LPN_RECV_DELAY,   /* Poll sent, waiting ReceiveDelay */
120 		BT_MESH_LPN_WAIT_UPDATE,  /* Waiting for Update or message */
121 	} state;
122 
123 	/* Transaction Number (used for subscription list) */
124 	uint8_t xact_next;
125 	uint8_t xact_pending;
126 	uint8_t sent_req;
127 
128 	/* Address of our Friend when we're a LPN. Unassigned if we don't
129 	 * have a friend yet.
130 	 */
131 	uint16_t frnd;
132 
133 	/* Value from the friend offer */
134 	uint8_t  recv_win;
135 
136 	uint8_t  req_attempts;     /* Number of Request attempts */
137 
138 	int32_t poll_timeout;
139 
140 	uint8_t  groups_changed:1, /* Friend Subscription List needs updating */
141 	      pending_poll:1,   /* Poll to be sent after subscription */
142 	      disable:1,        /* Disable LPN after clearing */
143 	      fsn:1,            /* Friend Sequence Number */
144 	      established:1,    /* Friendship established */
145 	      clear_success:1;  /* Friend Clear Confirm received */
146 
147 	/* Friend Queue Size */
148 	uint8_t  queue_size;
149 
150 	/* FriendCounter */
151 	uint16_t frnd_counter;
152 
153 	/* LPNCounter */
154 	uint16_t lpn_counter;
155 
156 	/* Previous Friend of this LPN */
157 	uint16_t old_friend;
158 
159 	/* Duration reported for last advertising packet */
160 	uint16_t adv_duration;
161 
162 	/* Advertising start time. */
163 	uint32_t adv_start_time;
164 
165 	/* Next LPN related action timer */
166 	struct k_work_delayable timer;
167 
168 	/* Subscribed groups */
169 	uint16_t groups[LPN_GROUPS];
170 
171 	struct bt_mesh_subnet *sub;
172 
173 	struct bt_mesh_net_cred cred[2];
174 
175 	/* Bit fields for tracking which groups the Friend knows about */
176 	ATOMIC_DEFINE(added, LPN_GROUPS);
177 	ATOMIC_DEFINE(pending, LPN_GROUPS);
178 	ATOMIC_DEFINE(to_remove, LPN_GROUPS);
179 };
180 
181 /* bt_mesh_net.flags */
182 enum {
183 	BT_MESH_INIT,            /* We have been initialized */
184 	BT_MESH_VALID,           /* We have been provisioned */
185 	BT_MESH_SUSPENDED,       /* Network is temporarily suspended */
186 	BT_MESH_IVU_IN_PROGRESS, /* IV Update in Progress */
187 	BT_MESH_IVU_INITIATOR,   /* IV Update initiated by us */
188 	BT_MESH_IVU_TEST,        /* IV Update test mode */
189 	BT_MESH_IVU_PENDING,     /* Update blocked by SDU in progress */
190 	BT_MESH_COMP_DIRTY,      /* Composition data is dirty */
191 	BT_MESH_DEVKEY_CAND,     /* Has device key candidate */
192 	BT_MESH_METADATA_DIRTY,  /* Models metadata is dirty */
193 
194 	/* Feature flags */
195 	BT_MESH_RELAY,
196 	BT_MESH_BEACON,
197 	BT_MESH_GATT_PROXY,
198 	BT_MESH_FRIEND,
199 	BT_MESH_PRIV_BEACON,
200 	BT_MESH_PRIV_GATT_PROXY,
201 	BT_MESH_OD_PRIV_PROXY,
202 
203 	/* Don't touch - intentionally last */
204 	BT_MESH_FLAG_COUNT,
205 };
206 
207 struct bt_mesh_net {
208 	uint32_t iv_index; /* Current IV Index */
209 	uint32_t seq;      /* Next outgoing sequence number (24 bits) */
210 
211 	ATOMIC_DEFINE(flags, BT_MESH_FLAG_COUNT);
212 
213 	/* Local network interface */
214 	struct k_work local_work;
215 	sys_slist_t local_queue;
216 
217 #if defined(CONFIG_BT_MESH_FRIEND)
218 	/* Friend state, unique for each LPN that we're Friends for */
219 	struct bt_mesh_friend frnd[CONFIG_BT_MESH_FRIEND_LPN_COUNT];
220 #endif
221 
222 #if defined(CONFIG_BT_MESH_LOW_POWER)
223 	struct bt_mesh_lpn lpn;  /* Low Power Node state */
224 #endif
225 
226 	/* Number of hours in current IV Update state */
227 	uint8_t  ivu_duration;
228 
229 	uint8_t net_xmit;
230 	uint8_t relay_xmit;
231 	uint8_t default_ttl;
232 
233 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
234 	uint8_t priv_beacon_int;
235 #endif
236 
237 	/* Timer to track duration in current IV Update state */
238 	struct k_work_delayable ivu_timer;
239 
240 	struct bt_mesh_key dev_key;
241 
242 #if defined(CONFIG_BT_MESH_RPR_SRV)
243 	struct bt_mesh_key dev_key_cand;
244 #endif
245 #if defined(CONFIG_BT_MESH_OD_PRIV_PROXY_SRV)
246 	uint8_t on_demand_state;
247 #endif
248 	struct bt_mesh_sar_tx sar_tx; /* Transport SAR Transmitter configuration */
249 	struct bt_mesh_sar_rx sar_rx; /* Transport SAR Receiver configuration */
250 };
251 
252 /* Network interface */
253 enum bt_mesh_net_if {
254 	BT_MESH_NET_IF_ADV,
255 	BT_MESH_NET_IF_LOCAL,
256 	BT_MESH_NET_IF_PROXY,
257 	BT_MESH_NET_IF_PROXY_CFG,
258 };
259 
260 /* Decoding context for Network/Transport data */
261 struct bt_mesh_net_rx {
262 	struct bt_mesh_subnet *sub;
263 	struct bt_mesh_msg_ctx ctx;
264 	uint32_t  seq;            /* Sequence Number */
265 	uint8_t   old_iv:1,       /* iv_index - 1 was used */
266 	       new_key:1,      /* Data was encrypted with updated key */
267 	       friend_cred:1,  /* Data was encrypted with friend cred */
268 	       ctl:1,          /* Network Control */
269 	       net_if:2,       /* Network interface */
270 	       local_match:1,  /* Matched a local element */
271 	       friend_match:1; /* Matched an LPN we're friends for */
272 };
273 
274 /* Encoding context for Network/Transport data */
275 struct bt_mesh_net_tx {
276 	struct bt_mesh_subnet *sub;
277 	struct bt_mesh_msg_ctx *ctx;
278 	uint16_t src;
279 	uint8_t  xmit;
280 	uint8_t  friend_cred:1,
281 	      aszmic:1,
282 	      aid:6;
283 };
284 
285 extern struct bt_mesh_net bt_mesh;
286 
287 #define BT_MESH_NET_IVI_TX (bt_mesh.iv_index - \
288 			    atomic_test_bit(bt_mesh.flags, \
289 					    BT_MESH_IVU_IN_PROGRESS))
290 #define BT_MESH_NET_IVI_RX(rx) (bt_mesh.iv_index - (rx)->old_iv)
291 
292 #define BT_MESH_NET_HDR_LEN 9
293 
294 int bt_mesh_net_create(uint16_t idx, uint8_t flags, const struct bt_mesh_key *key,
295 		       uint32_t iv_index);
296 
297 bool bt_mesh_net_iv_update(uint32_t iv_index, bool iv_update);
298 
299 int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf,
300 		       enum bt_mesh_nonce_type type);
301 
302 int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct bt_mesh_adv *adv,
303 		     const struct bt_mesh_send_cb *cb, void *cb_data);
304 
305 int bt_mesh_net_decode(struct net_buf_simple *in, enum bt_mesh_net_if net_if,
306 		       struct bt_mesh_net_rx *rx, struct net_buf_simple *out);
307 
308 void bt_mesh_net_recv(struct net_buf_simple *data, int8_t rssi,
309 		      enum bt_mesh_net_if net_if);
310 
311 void bt_mesh_net_loopback_clear(uint16_t net_idx);
312 
313 uint32_t bt_mesh_next_seq(void);
314 void bt_mesh_net_seq_store(bool force);
315 
316 void bt_mesh_net_init(void);
317 void bt_mesh_net_header_parse(struct net_buf_simple *buf,
318 			      struct bt_mesh_net_rx *rx);
319 void bt_mesh_net_pending_net_store(void);
320 void bt_mesh_net_pending_iv_store(void);
321 void bt_mesh_net_pending_seq_store(void);
322 
323 void bt_mesh_net_pending_dev_key_cand_store(void);
324 void bt_mesh_net_dev_key_cand_store(void);
325 
326 void bt_mesh_net_store(void);
327 void bt_mesh_net_clear(void);
328 void bt_mesh_net_settings_commit(void);
329 
send_cb_finalize(const struct bt_mesh_send_cb * cb,void * cb_data)330 static inline void send_cb_finalize(const struct bt_mesh_send_cb *cb,
331 				    void *cb_data)
332 {
333 	if (!cb) {
334 		return;
335 	}
336 
337 	if (cb->start) {
338 		cb->start(0, 0, cb_data);
339 	}
340 
341 	if (cb->end) {
342 		cb->end(0, cb_data);
343 	}
344 }
345