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