xref: /nrf52832-nimble/packages/NimBLE-latest/nimble/host/mesh/include/mesh/glue.h (revision 042d53a763ad75cb1465103098bb88c245d95138)
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #ifndef _MESH_GLUE_
21 #define _MESH_GLUE_
22 
23 #include <assert.h>
24 #include <errno.h>
25 
26 #include "syscfg/syscfg.h"
27 #include "nimble/nimble_npl.h"
28 
29 #include "os/os_mbuf.h"
30 #include "os/queue.h"
31 
32 #include "nimble/ble.h"
33 #include "host/ble_hs.h"
34 #include "host/ble_uuid.h"
35 #include "../src/ble_sm_priv.h"
36 #include "../src/ble_hs_hci_priv.h"
37 
38 #include "tinycrypt/aes.h"
39 #include "tinycrypt/constants.h"
40 #include "tinycrypt/utils.h"
41 #include "tinycrypt/cmac_mode.h"
42 #include "tinycrypt/ecc_dh.h"
43 
44 #if MYNEWT_VAL(BLE_MESH_SETTINGS)
45 #include "config/config.h"
46 #endif
47 
48 #define u8_t    uint8_t
49 #define s8_t    int8_t
50 #define u16_t   uint16_t
51 #define s16_t   int16_t
52 #define u32_t   uint32_t
53 #define u64_t   uint64_t
54 #define s64_t   int64_t
55 #define s32_t   int32_t
56 
57 /** @brief Helper to declare elements of bt_data arrays
58  *
59  *  This macro is mainly for creating an array of struct bt_data
60  *  elements which is then passed to bt_le_adv_start().
61  *
62  *  @param _type Type of advertising data field
63  *  @param _data Pointer to the data field payload
64  *  @param _data_len Number of bytes behind the _data pointer
65  */
66 #define BT_DATA(_type, _data, _data_len) \
67     { \
68         .type = (_type), \
69         .data_len = (_data_len), \
70         .data = (const u8_t *)(_data), \
71     }
72 
73 /** @brief Helper to declare elements of bt_data arrays
74  *
75  *  This macro is mainly for creating an array of struct bt_data
76  *  elements which is then passed to bt_le_adv_start().
77  *
78  *  @param _type Type of advertising data field
79  *  @param _bytes Variable number of single-byte parameters
80  */
81 #define BT_DATA_BYTES(_type, _bytes...) \
82     BT_DATA(_type, ((u8_t []) { _bytes }), \
83         sizeof((u8_t []) { _bytes }))
84 
85 /* EIR/AD data type definitions */
86 #define BT_DATA_FLAGS                   0x01 /* AD flags */
87 #define BT_DATA_UUID16_SOME             0x02 /* 16-bit UUID, more available */
88 #define BT_DATA_UUID16_ALL              0x03 /* 16-bit UUID, all listed */
89 #define BT_DATA_UUID32_SOME             0x04 /* 32-bit UUID, more available */
90 #define BT_DATA_UUID32_ALL              0x05 /* 32-bit UUID, all listed */
91 #define BT_DATA_UUID128_SOME            0x06 /* 128-bit UUID, more available */
92 #define BT_DATA_UUID128_ALL             0x07 /* 128-bit UUID, all listed */
93 #define BT_DATA_NAME_SHORTENED          0x08 /* Shortened name */
94 #define BT_DATA_NAME_COMPLETE           0x09 /* Complete name */
95 #define BT_DATA_TX_POWER                0x0a /* Tx Power */
96 #define BT_DATA_SOLICIT16               0x14 /* Solicit UUIDs, 16-bit */
97 #define BT_DATA_SOLICIT128              0x15 /* Solicit UUIDs, 128-bit */
98 #define BT_DATA_SVC_DATA16              0x16 /* Service data, 16-bit UUID */
99 #define BT_DATA_GAP_APPEARANCE          0x19 /* GAP appearance */
100 #define BT_DATA_SOLICIT32               0x1f /* Solicit UUIDs, 32-bit */
101 #define BT_DATA_SVC_DATA32              0x20 /* Service data, 32-bit UUID */
102 #define BT_DATA_SVC_DATA128             0x21 /* Service data, 128-bit UUID */
103 #define BT_DATA_URI                     0x24 /* URI */
104 #define BT_DATA_MESH_PROV               0x29 /* Mesh Provisioning PDU */
105 #define BT_DATA_MESH_MESSAGE            0x2a /* Mesh Networking PDU */
106 #define BT_DATA_MESH_BEACON             0x2b /* Mesh Beacon */
107 
108 #define BT_DATA_MANUFACTURER_DATA       0xff /* Manufacturer Specific Data */
109 
110 #define BT_LE_AD_LIMITED                0x01 /* Limited Discoverable */
111 #define BT_LE_AD_GENERAL                0x02 /* General Discoverable */
112 #define BT_LE_AD_NO_BREDR               0x04 /* BR/EDR not supported */
113 
114 #define sys_put_be16(a,b) put_be16(b, a)
115 #define sys_put_le16(a,b) put_le16(b, a)
116 #define sys_put_be32(a,b) put_be32(b, a)
117 #define sys_get_be16(a) get_be16(a)
118 #define sys_get_le16(a) get_le16(a)
119 #define sys_get_be32(a) get_be32(a)
120 #define sys_cpu_to_be16(a) htobe16(a)
121 #define sys_cpu_to_be32(a) htobe32(a)
122 #define sys_be32_to_cpu(a) be32toh(a)
123 #define sys_be16_to_cpu(a) be16toh(a)
124 #define sys_le16_to_cpu(a) le16toh(a)
125 
126 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
127 #define CODE_UNREACHABLE __builtin_unreachable()
128 #define __ASSERT(code, str) \
129     do {                          \
130         if (!(code)) BT_ERR(str); \
131         assert(code);             \
132     } while (0);
133 
134 #define __ASSERT_NO_MSG(test) __ASSERT(test, "")
135 
136 /* Mesh is designed to not use mbuf chains */
137 #if BT_DBG_ENABLED
138 #define ASSERT_NOT_CHAIN(om) assert(SLIST_NEXT(om, om_next) == NULL)
139 #else
140 #define ASSERT_NOT_CHAIN(om) (void)(om)
141 #endif
142 
143 #define __packed    __attribute__((__packed__))
144 
145 #define MSEC_PER_SEC   (1000)
146 #define K_MSEC(ms)     (ms)
147 #define K_SECONDS(s)   K_MSEC((s) * MSEC_PER_SEC)
148 #define K_MINUTES(m)   K_SECONDS((m) * 60)
149 #define K_HOURS(h)     K_MINUTES((h) * 60)
150 
151 #ifndef BIT
152 #define BIT(n)  (1UL << (n))
153 #endif
154 
155 #define BIT_MASK(n) (BIT(n) - 1)
156 
157 #define BT_GAP_ADV_FAST_INT_MIN_1               0x0030  /* 30 ms    */
158 #define BT_GAP_ADV_FAST_INT_MAX_1               0x0060  /* 60 ms    */
159 #define BT_GAP_ADV_FAST_INT_MIN_2               0x00a0  /* 100 ms   */
160 #define BT_GAP_ADV_FAST_INT_MAX_2               0x00f0  /* 150 ms   */
161 #define BT_GAP_ADV_SLOW_INT_MIN                 0x0640  /* 1 s      */
162 #define BT_GAP_ADV_SLOW_INT_MAX                 0x0780  /* 1.2 s    */
163 
164 #define BT_DBG(fmt, ...)    \
165     if (BT_DBG_ENABLED) { \
166         BLE_HS_LOG(DEBUG, "%s: " fmt "\n", __func__, ## __VA_ARGS__); \
167     }
168 #define BT_INFO(fmt, ...)   BLE_HS_LOG(INFO, "%s: " fmt "\n", __func__, ## __VA_ARGS__);
169 #define BT_WARN(fmt, ...)   BLE_HS_LOG(WARN, "%s: " fmt "\n", __func__, ## __VA_ARGS__);
170 #define BT_ERR(fmt, ...)    BLE_HS_LOG(ERROR, "%s: " fmt "\n", __func__, ## __VA_ARGS__);
171 #define BT_GATT_ERR(_att_err)   (-(_att_err))
172 
173 typedef ble_addr_t bt_addr_le_t;
174 
175 #define k_fifo_init(queue) ble_npl_eventq_init(queue)
176 #define net_buf_simple_tailroom(buf) OS_MBUF_TRAILINGSPACE(buf)
177 #define net_buf_tailroom(buf) net_buf_simple_tailroom(buf)
178 #define net_buf_headroom(buf) ((buf)->om_data - &(buf)->om_databuf[buf->om_pkthdr_len])
179 #define net_buf_simple_headroom(buf) net_buf_headroom(buf)
180 #define net_buf_simple_tail(buf) ((buf)->om_data + (buf)->om_len)
181 
182 struct net_buf_simple_state {
183     /** Offset of the data pointer from the beginning of the storage */
184     u16_t offset;
185     /** Length of data */
186     u16_t len;
187 };
188 
NET_BUF_SIMPLE(uint16_t size)189 static inline struct os_mbuf * NET_BUF_SIMPLE(uint16_t size)
190 {
191     struct os_mbuf *buf;
192 
193     buf = os_msys_get(size, 0);
194     assert(buf);
195 
196     return buf;
197 }
198 
199 #define K_NO_WAIT (0)
200 #define K_FOREVER (-1)
201 
202 /* This is by purpose */
net_buf_simple_init(struct os_mbuf * buf,size_t reserve_head)203 static inline void net_buf_simple_init(struct os_mbuf *buf,
204                                        size_t reserve_head)
205 {
206     /* This is called in Zephyr after init.
207      * Note in Mynewt case we don't care abour reserved head*/
208     buf->om_data = &buf->om_databuf[buf->om_pkthdr_len] + reserve_head;
209     buf->om_len = 0;
210 }
211 
212 void net_buf_put(struct ble_npl_eventq *fifo, struct os_mbuf *buf);
213 void * net_buf_ref(struct os_mbuf *om);
214 void net_buf_unref(struct os_mbuf *om);
215 uint16_t net_buf_simple_pull_le16(struct os_mbuf *om);
216 uint16_t net_buf_simple_pull_be16(struct os_mbuf *om);
217 uint32_t net_buf_simple_pull_be32(struct os_mbuf *om);
218 uint32_t net_buf_simple_pull_le32(struct os_mbuf *om);
219 uint8_t net_buf_simple_pull_u8(struct os_mbuf *om);
220 void net_buf_simple_add_le16(struct os_mbuf *om, uint16_t val);
221 void net_buf_simple_add_be16(struct os_mbuf *om, uint16_t val);
222 void net_buf_simple_add_u8(struct os_mbuf *om, uint8_t val);
223 void net_buf_simple_add_be32(struct os_mbuf *om, uint32_t val);
224 void net_buf_simple_add_le32(struct os_mbuf *om, uint32_t val);
225 void net_buf_add_zeros(struct os_mbuf *om, uint8_t len);
226 void net_buf_simple_push_le16(struct os_mbuf *om, uint16_t val);
227 void net_buf_simple_push_be16(struct os_mbuf *om, uint16_t val);
228 void net_buf_simple_push_u8(struct os_mbuf *om, uint8_t val);
229 void *net_buf_simple_pull(struct os_mbuf *om, uint8_t len);
230 void *net_buf_simple_add(struct os_mbuf *om, uint8_t len);
231 bool k_fifo_is_empty(struct ble_npl_eventq *q);
232 void *net_buf_get(struct ble_npl_eventq *fifo,s32_t t);
233 uint8_t *net_buf_simple_push(struct os_mbuf *om, uint8_t len);
234 void net_buf_reserve(struct os_mbuf *om, size_t reserve);
235 
236 #define net_buf_add_mem(a,b,c) os_mbuf_append(a,b,c)
237 #define net_buf_simple_add_mem(a,b,c) os_mbuf_append(a,b,c)
238 #define net_buf_add_u8(a,b) net_buf_simple_add_u8(a,b)
239 #define net_buf_add(a,b) net_buf_simple_add(a,b)
240 
241 #define net_buf_clone(a, b) os_mbuf_dup(a)
242 #define net_buf_add_be32(a, b) net_buf_simple_add_be32(a, b)
243 #define net_buf_add_be16(a, b) net_buf_simple_add_be16(a, b)
244 
245 #define BT_GATT_CCC_NOTIFY BLE_GATT_CHR_PROP_NOTIFY
246 #define bt_gatt_attr ble_gatt_attr
247 
248 /** Description of different data types that can be encoded into
249   * advertising data. Used to form arrays that are passed to the
250   * bt_le_adv_start() function.
251   */
252 struct bt_data {
253     u8_t type;
254     u8_t data_len;
255     const u8_t *data;
256 };
257 
258 struct bt_pub_key_cb {
259     /** @brief Callback type for Public Key generation.
260      *
261      *  Used to notify of the local public key or that the local key is not
262      *  available (either because of a failure to read it or because it is
263      *  being regenerated).
264      *
265      *  @param key The local public key, or NULL in case of no key.
266      */
267     void (*func)(const u8_t key[64]);
268 
269     struct bt_pub_key_cb *_next;
270 };
271 
272 typedef void (*bt_dh_key_cb_t)(const u8_t key[32]);
273 int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb);
274 int bt_pub_key_gen(struct bt_pub_key_cb *new_cb);
275 uint8_t *bt_pub_key_get(void);
276 int bt_rand(void *buf, size_t len);
277 const char * bt_hex(const void *buf, size_t len);
278 int bt_encrypt_be(const uint8_t *key, const uint8_t *plaintext, uint8_t *enc_data);
279 void bt_mesh_register_gatt(void);
280 int bt_le_adv_start(const struct ble_gap_adv_params *param,
281                     const struct bt_data *ad, size_t ad_len,
282                     const struct bt_data *sd, size_t sd_len);
283 int bt_le_adv_stop(bool proxy);
284 
285 struct k_delayed_work {
286     struct ble_npl_callout work;
287 };
288 
289 void k_work_init(struct ble_npl_callout *work, ble_npl_event_fn handler);
290 void k_delayed_work_init(struct k_delayed_work *w, ble_npl_event_fn *f);
291 void k_delayed_work_cancel(struct k_delayed_work *w);
292 void k_delayed_work_submit(struct k_delayed_work *w, uint32_t ms);
293 int64_t k_uptime_get(void);
294 u32_t k_uptime_get_32(void);
295 void k_sleep(int32_t duration);
296 void k_work_submit(struct ble_npl_callout *w);
297 void k_work_add_arg(struct ble_npl_callout *w, void *arg);
298 void k_delayed_work_add_arg(struct k_delayed_work *w, void *arg);
299 uint32_t k_delayed_work_remaining_get(struct k_delayed_work *w);
300 
net_buf_simple_save(struct os_mbuf * buf,struct net_buf_simple_state * state)301 static inline void net_buf_simple_save(struct os_mbuf *buf,
302                        struct net_buf_simple_state *state)
303 {
304     state->offset = net_buf_simple_headroom(buf);
305     state->len = buf->om_len;
306 }
307 
net_buf_simple_restore(struct os_mbuf * buf,struct net_buf_simple_state * state)308 static inline void net_buf_simple_restore(struct os_mbuf *buf,
309                                           struct net_buf_simple_state *state)
310 {
311       buf->om_data = &buf->om_databuf[buf->om_pkthdr_len] + state->offset;
312       buf->om_len = state->len;
313 }
314 
sys_memcpy_swap(void * dst,const void * src,size_t length)315 static inline void sys_memcpy_swap(void *dst, const void *src, size_t length)
316 {
317     __ASSERT(((src < dst && (src + length) <= dst) ||
318           (src > dst && (dst + length) <= src)),
319          "Source and destination buffers must not overlap");
320 
321     src += length - 1;
322 
323     for (; length > 0; length--) {
324         *((u8_t *)dst++) = *((u8_t *)src--);
325     }
326 }
327 
328 #define popcount(x) __builtin_popcount(x)
329 
find_lsb_set(u32_t op)330 static inline unsigned int find_lsb_set(u32_t op)
331 {
332     return __builtin_ffs(op);
333 }
334 
find_msb_set(u32_t op)335 static inline unsigned int find_msb_set(u32_t op)
336 {
337     if (!op)
338         return 0;
339 
340     return 32 - __builtin_clz(op);
341 }
342 
343 #define CONFIG_BT_MESH_FRIEND               BLE_MESH_FRIEND
344 #define CONFIG_BT_MESH_GATT_PROXY           BLE_MESH_GATT_PROXY
345 #define CONFIG_BT_MESH_IV_UPDATE_TEST       BLE_MESH_IV_UPDATE_TEST
346 #define CONFIG_BT_MESH_LOW_POWER            BLE_MESH_LOW_POWER
347 #define CONFIG_BT_MESH_LPN_AUTO             BLE_MESH_LPN_AUTO
348 #define CONFIG_BT_MESH_LPN_ESTABLISHMENT    BLE_MESH_LPN_ESTABLISHMENT
349 #define CONFIG_BT_MESH_PB_ADV               BLE_MESH_PB_ADV
350 #define CONFIG_BT_MESH_PB_GATT              BLE_MESH_PB_GATT
351 #define CONFIG_BT_MESH_PROV                 BLE_MESH_PROV
352 #define CONFIG_BT_TESTING                   BLE_MESH_TESTING
353 #define CONFIG_BT_SETTINGS                  BLE_MESH_SETTINGS
354 #define CONFIG_SETTINGS                     BLE_MESH_SETTINGS
355 #define BT_SETTINGS                         BLE_MESH_SETTINGS
356 
357 /* Above flags are used with IS_ENABLED macro */
358 #define IS_ENABLED(config) MYNEWT_VAL(config)
359 
360 #define CONFIG_BT_MESH_LPN_GROUPS           MYNEWT_VAL(BLE_MESH_LPN_GROUPS)
361 #define CONFIG_BT_MESH_ADV_BUF_COUNT        MYNEWT_VAL(BLE_MESH_ADV_BUF_COUNT)
362 #define CONFIG_BT_MESH_FRIEND_QUEUE_SIZE    MYNEWT_VAL(BLE_MESH_FRIEND_QUEUE_SIZE)
363 #define CONFIG_BT_MESH_FRIEND_RECV_WIN      MYNEWT_VAL(BLE_MESH_FRIEND_RECV_WIN)
364 #define CONFIG_BT_MESH_LPN_POLL_TIMEOUT     MYNEWT_VAL(BLE_MESH_LPN_POLL_TIMEOUT)
365 #define CONFIG_BT_MESH_MODEL_GROUP_COUNT    MYNEWT_VAL(BLE_MESH_MODEL_GROUP_COUNT)
366 #define CONFIG_BT_MESH_MODEL_KEY_COUNT      MYNEWT_VAL(BLE_MESH_MODEL_KEY_COUNT)
367 #define CONFIG_BT_MESH_NODE_ID_TIMEOUT      MYNEWT_VAL(BLE_MESH_NODE_ID_TIMEOUT)
368 #define CONFIG_BT_MAX_CONN                  MYNEWT_VAL(BLE_MAX_CONNECTIONS)
369 #define CONFIG_BT_MESH_SEQ_STORE_RATE       MYNEWT_VAL(BLE_MESH_SEQ_STORE_RATE)
370 #define CONFIG_BT_MESH_RPL_STORE_TIMEOUT    MYNEWT_VAL(BLE_MESH_RPL_STORE_TIMEOUT)
371 #define CONFIG_BT_MESH_APP_KEY_COUNT        MYNEWT_VAL(BLE_MESH_APP_KEY_COUNT)
372 #define CONFIG_BT_MESH_SUBNET_COUNT         MYNEWT_VAL(BLE_MESH_SUBNET_COUNT)
373 #define CONFIG_BT_MESH_STORE_TIMEOUT        MYNEWT_VAL(BLE_MESH_STORE_TIMEOUT)
374 #define CONFIG_BT_MESH_IVU_DIVIDER          MYNEWT_VAL(BLE_MESH_IVU_DIVIDER)
375 #define CONFIG_BT_DEVICE_NAME               MYNEWT_VAL(BLE_MESH_DEVICE_NAME)
376 #define CONFIG_BT_MESH_TX_SEG_MAX           MYNEWT_VAL(BLE_MESH_TX_SEG_MAX)
377 
378 #define printk console_printf
379 
380 #define CONTAINER_OF(ptr, type, field) \
381 	((type *)(((char *)(ptr)) - offsetof(type, field)))
382 
383 
384 #define k_sem ble_npl_sem
385 
k_sem_init(struct k_sem * sem,unsigned int initial_count,unsigned int limit)386 static inline void k_sem_init(struct k_sem *sem, unsigned int initial_count,
387 			      unsigned int limit)
388 {
389 	ble_npl_sem_init(sem, initial_count);
390 }
391 
k_sem_take(struct k_sem * sem,s32_t timeout)392 static inline int k_sem_take(struct k_sem *sem, s32_t timeout)
393 {
394 	uint32_t ticks;
395 
396 	ble_npl_time_ms_to_ticks(timeout, &ticks);
397 	return - ble_npl_sem_pend(sem,  ticks);
398 }
399 
k_sem_give(struct k_sem * sem)400 static inline void k_sem_give(struct k_sem *sem)
401 {
402 	ble_npl_sem_release(sem);
403 }
404 
405 /* Helpers to access the storage array, since we don't have access to its
406  * type at this point anymore.
407  */
408 
409 #define BUF_SIZE(pool) (pool->omp_pool->mp_block_size)
410 
net_buf_id(struct os_mbuf * buf)411 static inline int net_buf_id(struct os_mbuf *buf)
412 {
413 	struct os_mbuf_pool *pool = buf->om_omp;
414 	u8_t *pool_start = (u8_t *)pool->omp_pool->mp_membuf_addr;
415 	u8_t *buf_ptr = (u8_t *)buf;
416 
417 	return (buf_ptr - pool_start) / BUF_SIZE(pool);
418 }
419 
420 /* XXX: We should not use os_mbuf_pkthdr chains to represent a list of
421  * packets, this is a hack. For now this is not an issue, because mesh
422  * does not use os_mbuf chains. We should change this in the future.
423  */
424 STAILQ_HEAD(net_buf_slist_t, os_mbuf_pkthdr);
425 
426 void net_buf_slist_init(struct net_buf_slist_t *list);
427 bool net_buf_slist_is_empty(struct net_buf_slist_t *list);
428 struct os_mbuf *net_buf_slist_peek_head(struct net_buf_slist_t *list);
429 struct os_mbuf *net_buf_slist_peek_next(struct os_mbuf *buf);
430 struct os_mbuf *net_buf_slist_get(struct net_buf_slist_t *list);
431 void net_buf_slist_put(struct net_buf_slist_t *list, struct os_mbuf *buf);
432 void net_buf_slist_remove(struct net_buf_slist_t *list, struct os_mbuf *prev,
433 			  struct os_mbuf *cur);
434 void net_buf_slist_merge_slist(struct net_buf_slist_t *list,
435 			       struct net_buf_slist_t *list_to_append);
436 #define NET_BUF_SLIST_FOR_EACH_NODE(head, var) STAILQ_FOREACH(var, head, omp_next)
437 
438 #if MYNEWT_VAL(BLE_MESH_SETTINGS)
439 
440 #define settings_load conf_load
441 int settings_bytes_from_str(char *val_str, void *vp, int *len);
442 char *settings_str_from_bytes(void *vp, int vp_len, char *buf, int buf_len);
443 
444 #define snprintk snprintf
445 #define BT_SETTINGS_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
446 #define settings_save_one conf_save_one
447 
448 #else
449 
450 static inline int
settings_load(void)451 settings_load(void)
452 {
453 	return 0;
454 }
455 
456 #endif /* MYNEWT_VAL(MYNEWT_VAL_BLE_MESH_SETTINGS) */
457 
458 #define BUILD_ASSERT(cond) _Static_assert(cond, "")
459 
460 #endif
461