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