1 /*  Bluetooth Mesh */
2 
3 /*
4  * SPDX-FileCopyrightText: 2017 Intel Corporation
5  * SPDX-FileContributor: 2018-2021 Espressif Systems (Shanghai) CO LTD
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  */
9 
10 #ifndef _NET_H_
11 #define _NET_H_
12 
13 #include "mesh_access.h"
14 
15 #ifdef __cplusplus
16 extern "C" {
17 #endif
18 
19 #define BLE_MESH_NET_FLAG_KR       BIT(0)
20 #define BLE_MESH_NET_FLAG_IVU      BIT(1)
21 
22 #define BLE_MESH_KR_NORMAL         0x00
23 #define BLE_MESH_KR_PHASE_1        0x01
24 #define BLE_MESH_KR_PHASE_2        0x02
25 #define BLE_MESH_KR_PHASE_3        0x03
26 
27 #define BLE_MESH_IV_UPDATE(flags)   ((flags >> 1) & 0x01)
28 #define BLE_MESH_KEY_REFRESH(flags) (flags & 0x01)
29 
30 /* How many hours in between updating IVU duration */
31 #define BLE_MESH_IVU_MIN_HOURS      96
32 #define BLE_MESH_IVU_HOURS          (BLE_MESH_IVU_MIN_HOURS / CONFIG_BLE_MESH_IVU_DIVIDER)
33 #define BLE_MESH_IVU_TIMEOUT        K_HOURS(BLE_MESH_IVU_HOURS)
34 
35 struct bt_mesh_app_key {
36     uint16_t net_idx;
37     uint16_t app_idx;
38     bool     updated;
39     struct bt_mesh_app_keys {
40         uint8_t id;
41         uint8_t val[16];
42     } keys[2];
43 };
44 
45 struct bt_mesh_subnet {
46     uint32_t beacon_sent;       /* Timestamp of last sent beacon */
47     uint8_t  beacons_last;      /* Number of beacons during last observation window. */
48     uint8_t  beacons_cur;       /* Number of beacons observed during currently ongoing window. */
49 
50     uint8_t  beacon_cache[21];  /* Cached last authenticated beacon */
51 
52     uint16_t net_idx;           /* NetKeyIndex */
53 
54     bool     kr_flag;           /* Key Refresh Flag */
55     uint8_t  kr_phase;          /* Key Refresh Phase */
56 
57     uint8_t  node_id;           /* Node Identity State */
58     uint32_t node_id_start;     /* Node Identity started timestamp */
59 
60     uint8_t  auth[8];           /* Beacon Authentication Value */
61 
62     struct bt_mesh_subnet_keys {
63         uint8_t net[16];        /* NetKey */
64         uint8_t nid;            /* NID */
65         uint8_t enc[16];        /* EncKey */
66         uint8_t net_id[8];      /* Network ID */
67 #if defined(CONFIG_BLE_MESH_GATT_PROXY_SERVER)
68         uint8_t identity[16];   /* IdentityKey */
69 #endif
70         uint8_t privacy[16];    /* PrivacyKey */
71         uint8_t beacon[16];     /* BeaconKey */
72     } keys[2];
73 };
74 
75 struct bt_mesh_rpl {
76     uint16_t src;
77     bool     old_iv;
78 #if defined(CONFIG_BLE_MESH_SETTINGS)
79     bool     store;
80 #endif
81     uint32_t seq;
82 };
83 
84 #if defined(CONFIG_BLE_MESH_FRIEND)
85 #define FRIEND_SEG_RX           CONFIG_BLE_MESH_FRIEND_SEG_RX
86 #define FRIEND_SUB_LIST_SIZE    CONFIG_BLE_MESH_FRIEND_SUB_LIST_SIZE
87 #else
88 #define FRIEND_SEG_RX           0
89 #define FRIEND_SUB_LIST_SIZE    0
90 #endif
91 
92 struct bt_mesh_friend {
93     uint16_t lpn;
94     uint8_t  recv_delay;
95     uint8_t  fsn:1,
96              send_last:1,
97              pending_req:1,
98              pending_buf:1,
99              valid:1,
100              established:1;
101     int32_t  poll_to;
102     uint8_t  num_elem;
103     uint16_t lpn_counter;
104     uint16_t counter;
105 
106     uint16_t net_idx;
107 
108     uint16_t sub_list[FRIEND_SUB_LIST_SIZE];
109 
110     struct k_delayed_work timer;
111 
112     struct bt_mesh_friend_seg {
113         sys_slist_t queue;
114 
115         /* The target number of segments, i.e. not necessarily
116          * the current number of segments, in the queue. This is
117          * used for Friend Queue free space calculations.
118          */
119         uint8_t seg_count;
120     } seg[FRIEND_SEG_RX];
121 
122     struct net_buf *last;
123 
124     sys_slist_t queue;
125     uint32_t    queue_size;
126 
127     /* Friend Clear Procedure */
128     struct {
129         uint32_t start;               /* Clear Procedure start */
130         uint16_t frnd;                /* Previous Friend's address */
131         uint16_t repeat_sec;          /* Repeat timeout in seconds */
132         struct k_delayed_work timer;  /* Repeat timer */
133     } clear;
134 };
135 
136 #if defined(CONFIG_BLE_MESH_LOW_POWER)
137 #define LPN_GROUPS CONFIG_BLE_MESH_LPN_GROUPS
138 #else
139 #define LPN_GROUPS 0
140 #endif
141 
142 /* Low Power Node state */
143 struct bt_mesh_lpn {
144     enum __packed {
145         BLE_MESH_LPN_DISABLED,     /* LPN feature is disabled */
146         BLE_MESH_LPN_CLEAR,        /* Clear in progress */
147         BLE_MESH_LPN_TIMER,        /* Waiting for auto timer expiry */
148         BLE_MESH_LPN_ENABLED,      /* LPN enabled, but no Friend */
149         BLE_MESH_LPN_REQ_WAIT,     /* Wait before scanning for offers */
150         BLE_MESH_LPN_WAIT_OFFER,   /* Friend Req sent */
151         BLE_MESH_LPN_ESTABLISHED,  /* Friendship established */
152         BLE_MESH_LPN_RECV_DELAY,   /* Poll sent, waiting ReceiveDelay */
153         BLE_MESH_LPN_WAIT_UPDATE,  /* Waiting for Update or message */
154         BLE_MESH_LPN_OFFER_RECV,   /* Friend offer received */
155     } state;
156 
157     /* Transaction Number (used for subscription list) */
158     uint8_t xact_next;
159     uint8_t xact_pending;
160     uint8_t sent_req;
161 
162     /* Address of our Friend when we're a LPN. Unassigned if we don't
163      * have a friend yet.
164      */
165     uint16_t frnd;
166 
167     /* Value from the friend offer */
168     uint8_t  recv_win;
169 
170     uint8_t  req_attempts;     /* Number of Request attempts */
171 
172     int32_t  poll_timeout;
173 
174     uint8_t  groups_changed: 1, /* Friend Subscription List needs updating */
175              pending_poll: 1,   /* Poll to be sent after subscription */
176              disable: 1,        /* Disable LPN after clearing */
177              fsn: 1,            /* Friend Sequence Number */
178              established: 1,    /* Friendship established */
179              clear_success: 1;  /* Friend Clear Confirm received */
180 
181     /* Friend Queue Size */
182     uint8_t  queue_size;
183 
184     /* LPNCounter */
185     uint16_t counter;
186 
187     /* Previous Friend of this LPN */
188     uint16_t old_friend;
189 
190     /* Duration reported for last advertising packet */
191     uint16_t adv_duration;
192 
193     /* Next LPN related action timer */
194     struct k_delayed_work timer;
195 
196     /* Subscribed groups */
197     uint16_t groups[LPN_GROUPS];
198 
199     /* Bit fields for tracking which groups the Friend knows about */
200     BLE_MESH_ATOMIC_DEFINE(added, LPN_GROUPS);
201     BLE_MESH_ATOMIC_DEFINE(pending, LPN_GROUPS);
202     BLE_MESH_ATOMIC_DEFINE(to_remove, LPN_GROUPS);
203 };
204 
205 /* bt_mesh_net.flags */
206 enum {
207     BLE_MESH_NODE,            /* Device is a node */
208     BLE_MESH_PROVISIONER,     /* Device is a Provisioner */
209     BLE_MESH_VALID,           /* We have been provisioned */
210     BLE_MESH_VALID_PROV,      /* Provisioner has been enabled */
211     BLE_MESH_SUSPENDED,       /* Network is temporarily suspended */
212     BLE_MESH_IVU_IN_PROGRESS, /* IV Update in Progress */
213     BLE_MESH_IVU_INITIATOR,   /* IV Update initiated by us */
214     BLE_MESH_IVU_TEST,        /* IV Update test mode */
215     BLE_MESH_IVU_PENDING,     /* Update blocked by SDU in progress */
216 
217     /* pending storage actions, must reside within first 32 flags */
218     BLE_MESH_RPL_PENDING,
219     BLE_MESH_KEYS_PENDING,
220     BLE_MESH_NET_PENDING,
221     BLE_MESH_IV_PENDING,
222     BLE_MESH_SEQ_PENDING,
223     BLE_MESH_HB_PUB_PENDING,
224     BLE_MESH_CFG_PENDING,
225     BLE_MESH_MOD_PENDING,
226     BLE_MESH_VA_PENDING,
227 
228     /* Don't touch - intentionally last */
229     BLE_MESH_FLAG_COUNT,
230 };
231 
232 struct bt_mesh_net {
233     uint32_t iv_index; /* Current IV Index */
234     uint32_t seq;      /* Next outgoing sequence number (24 bits) */
235 
236     BLE_MESH_ATOMIC_DEFINE(flags, BLE_MESH_FLAG_COUNT);
237 
238     /* Local network interface */
239     struct k_work local_work;
240     sys_slist_t local_queue;
241 
242 #if defined(CONFIG_BLE_MESH_FRIEND)
243     /* Friend state, unique for each LPN that we're Friends for */
244     struct bt_mesh_friend frnd[CONFIG_BLE_MESH_FRIEND_LPN_COUNT];
245 #endif
246 
247 #if defined(CONFIG_BLE_MESH_LOW_POWER)
248     struct bt_mesh_lpn lpn;  /* Low Power Node state */
249 #endif
250 
251     /* Number of hours in current IV Update state */
252     uint8_t ivu_duration;
253 
254     /* Timer to track duration in current IV Update state */
255     struct k_delayed_work ivu_timer;
256 
257     uint8_t dev_key[16];
258 
259     struct bt_mesh_app_key app_keys[CONFIG_BLE_MESH_APP_KEY_COUNT];
260 
261     struct bt_mesh_subnet sub[CONFIG_BLE_MESH_SUBNET_COUNT];
262 
263     struct bt_mesh_rpl rpl[CONFIG_BLE_MESH_CRPL];
264 
265 #if defined(CONFIG_BLE_MESH_PROVISIONER)
266     /* Application keys stored by provisioner */
267     struct bt_mesh_app_key *p_app_keys[CONFIG_BLE_MESH_PROVISIONER_APP_KEY_COUNT];
268     /* Next app_idx can be assigned */
269     uint16_t p_app_idx_next;
270 
271     /* Network keys stored by provisioner */
272     struct bt_mesh_subnet *p_sub[CONFIG_BLE_MESH_PROVISIONER_SUBNET_COUNT];
273     /* Next net_idx can be assigned */
274     uint16_t p_net_idx_next;
275 #endif
276 };
277 
278 /* Network interface */
279 enum bt_mesh_net_if {
280     BLE_MESH_NET_IF_ADV,
281     BLE_MESH_NET_IF_LOCAL,
282     BLE_MESH_NET_IF_PROXY,
283     BLE_MESH_NET_IF_PROXY_CFG,
284 };
285 
286 /* Decoding context for Network/Transport data */
287 struct bt_mesh_net_rx {
288     struct bt_mesh_subnet *sub;
289     struct bt_mesh_msg_ctx ctx;
290     uint32_t seq;            /* Sequence Number */
291     uint8_t  old_iv:1,       /* iv_index - 1 was used */
292              new_key:1,      /* Data was encrypted with updated key */
293              friend_cred:1,  /* Data was encrypted with friend cred */
294              ctl:1,          /* Network Control */
295              net_if:2,       /* Network interface */
296              local_match:1,  /* Matched a local element */
297 #if CONFIG_BLE_MESH_NOT_RELAY_REPLAY_MSG
298              replay_msg:1,   /* Replayed messages */
299 #endif
300              friend_match:1; /* Matched an LPN we're friends for */
301     uint16_t msg_cache_idx;  /* Index of entry in message cache */
302 };
303 
304 /* Encoding context for Network/Transport data */
305 struct bt_mesh_net_tx {
306     struct bt_mesh_subnet *sub;
307     struct bt_mesh_msg_ctx *ctx;
308     uint16_t src;
309     uint8_t  xmit;
310     uint8_t  friend_cred:1,
311              aszmic:1,
312              aid: 6;
313 };
314 
315 extern struct bt_mesh_net bt_mesh;
316 
317 #define BLE_MESH_NET_IVI_TX (bt_mesh.iv_index - \
318                              bt_mesh_atomic_test_bit(bt_mesh.flags, \
319                              BLE_MESH_IVU_IN_PROGRESS))
320 #define BLE_MESH_NET_IVI_RX(rx) (bt_mesh.iv_index - (rx)->old_iv)
321 
322 #define BLE_MESH_NET_HDR_LEN 9
323 
324 void bt_mesh_msg_cache_clear(uint16_t unicast_addr, uint8_t elem_num);
325 
326 int bt_mesh_net_keys_create(struct bt_mesh_subnet_keys *keys,
327                             const uint8_t key[16]);
328 
329 int bt_mesh_net_create(uint16_t idx, uint8_t flags, const uint8_t key[16],
330                        uint32_t iv_index);
331 
332 uint8_t bt_mesh_net_flags(struct bt_mesh_subnet *sub);
333 
334 bool bt_mesh_kr_update(struct bt_mesh_subnet *sub, uint8_t new_kr, bool new_key);
335 
336 void bt_mesh_net_revoke_keys(struct bt_mesh_subnet *sub);
337 
338 int bt_mesh_net_beacon_update(struct bt_mesh_subnet *sub);
339 
340 void bt_mesh_rpl_reset(void);
341 
342 bool bt_mesh_net_iv_update(uint32_t iv_index, bool iv_update);
343 
344 void bt_mesh_net_sec_update(struct bt_mesh_subnet *sub);
345 
346 struct bt_mesh_subnet *bt_mesh_subnet_get(uint16_t net_idx);
347 
348 struct bt_mesh_subnet *bt_mesh_subnet_find(const uint8_t net_id[8], uint8_t flags,
349                                            uint32_t iv_index, const uint8_t auth[8],
350                                            bool *new_key);
351 
352 int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf,
353                        bool proxy);
354 
355 int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf,
356                      const struct bt_mesh_send_cb *cb, void *cb_data);
357 
358 int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf,
359                        bool new_key, const struct bt_mesh_send_cb *cb,
360                        void *cb_data);
361 
362 int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if,
363                        struct bt_mesh_net_rx *rx, struct net_buf_simple *buf);
364 
365 void bt_mesh_net_recv(struct net_buf_simple *data, int8_t rssi,
366                       enum bt_mesh_net_if net_if);
367 
368 bool bt_mesh_primary_subnet_exist(void);
369 
370 uint32_t bt_mesh_next_seq(void);
371 
372 void bt_mesh_net_start(void);
373 
374 void bt_mesh_net_init(void);
375 void bt_mesh_net_reset(void);
376 void bt_mesh_net_deinit(void);
377 
378 void bt_mesh_net_header_parse(struct net_buf_simple *buf,
379                               struct bt_mesh_net_rx *rx);
380 
381 /* Friendship Credential Management */
382 struct friend_cred {
383     uint16_t net_idx;
384     uint16_t addr;
385 
386     uint16_t lpn_counter;
387     uint16_t frnd_counter;
388 
389     struct {
390         uint8_t nid;         /* NID */
391         uint8_t enc[16];     /* EncKey */
392         uint8_t privacy[16]; /* PrivacyKey */
393     } cred[2];
394 };
395 
396 int friend_cred_get(struct bt_mesh_subnet *sub, uint16_t addr, uint8_t *nid,
397                     const uint8_t **enc, const uint8_t **priv);
398 int friend_cred_set(struct friend_cred *cred, uint8_t idx, const uint8_t net_key[16]);
399 void friend_cred_refresh(uint16_t net_idx);
400 int friend_cred_update(struct bt_mesh_subnet *sub);
401 struct friend_cred *friend_cred_create(struct bt_mesh_subnet *sub, uint16_t addr,
402                                        uint16_t lpn_counter, uint16_t frnd_counter);
403 void friend_cred_clear(struct friend_cred *cred);
404 int friend_cred_del(uint16_t net_idx, uint16_t addr);
405 
send_cb_finalize(const struct bt_mesh_send_cb * cb,void * cb_data)406 static inline void send_cb_finalize(const struct bt_mesh_send_cb *cb,
407                                     void *cb_data)
408 {
409     if (!cb) {
410         return;
411     }
412 
413     if (cb->start) {
414         cb->start(0, 0, cb_data);
415     }
416 
417     if (cb->end) {
418         cb->end(0, cb_data);
419     }
420 }
421 
422 #ifdef __cplusplus
423 }
424 #endif
425 
426 #endif /* _NET_H_ */
427