1 /* gatt.c - Generic Attribute Profile handling */
2
3 /*
4 * Copyright (c) 2015-2016 Intel Corporation
5 * Copyright (c) 2023 Nordic Semiconductor ASA
6 *
7 * SPDX-License-Identifier: Apache-2.0
8 */
9
10 #include <zephyr/kernel.h>
11 #include <string.h>
12 #include <errno.h>
13 #include <stdbool.h>
14 #include <stdlib.h>
15 #include <zephyr/sys/atomic.h>
16 #include <zephyr/sys/byteorder.h>
17 #include <zephyr/sys/iterable_sections.h>
18 #include <zephyr/sys/util.h>
19 #include <zephyr/sys/check.h>
20
21 #include <zephyr/settings/settings.h>
22
23 #if defined(CONFIG_BT_GATT_CACHING)
24 #include <tinycrypt/constants.h>
25 #include <tinycrypt/utils.h>
26 #include <tinycrypt/aes.h>
27 #include <tinycrypt/cmac_mode.h>
28 #include <tinycrypt/ccm_mode.h>
29 #endif /* CONFIG_BT_GATT_CACHING */
30
31 #include <zephyr/bluetooth/hci.h>
32 #include <zephyr/bluetooth/bluetooth.h>
33 #include <zephyr/bluetooth/conn.h>
34 #include <zephyr/bluetooth/uuid.h>
35 #include <zephyr/bluetooth/gatt.h>
36 #include <zephyr/drivers/bluetooth/hci_driver.h>
37
38 #include "common/bt_str.h"
39
40 #include "hci_core.h"
41 #include "conn_internal.h"
42 #include "keys.h"
43 #include "l2cap_internal.h"
44 #include "att_internal.h"
45 #include "smp.h"
46 #include "settings.h"
47 #include "gatt_internal.h"
48 #include "long_wq.h"
49
50 #define LOG_LEVEL CONFIG_BT_GATT_LOG_LEVEL
51 #include <zephyr/logging/log.h>
52 LOG_MODULE_REGISTER(bt_gatt);
53
54 #define SC_TIMEOUT K_MSEC(10)
55 #define DB_HASH_TIMEOUT K_MSEC(10)
56
57 static uint16_t last_static_handle;
58
59 /* Persistent storage format for GATT CCC */
60 struct ccc_store {
61 uint16_t handle;
62 uint16_t value;
63 };
64
65 struct gatt_sub {
66 uint8_t id;
67 bt_addr_le_t peer;
68 sys_slist_t list;
69 };
70
71 #if defined(CONFIG_BT_GATT_CLIENT)
72 #define SUB_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
73 #else
74 #define SUB_MAX 0
75 #endif /* CONFIG_BT_GATT_CLIENT */
76
77 /**
78 * Entry x is free for reuse whenever (subscriptions[x].peer == BT_ADDR_LE_ANY).
79 * Invariant: (sys_slist_is_empty(subscriptions[x].list))
80 * <=> (subscriptions[x].peer == BT_ADDR_LE_ANY).
81 */
82 static struct gatt_sub subscriptions[SUB_MAX];
83 static sys_slist_t callback_list = SYS_SLIST_STATIC_INIT(&callback_list);
84
85 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
86 static sys_slist_t db;
87 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
88
89 enum gatt_global_flags {
90 GATT_INITIALIZED,
91 GATT_SERVICE_INITIALIZED,
92
93 GATT_NUM_FLAGS,
94 };
95
96 static ATOMIC_DEFINE(gatt_flags, GATT_NUM_FLAGS);
97
read_name(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)98 static ssize_t read_name(struct bt_conn *conn, const struct bt_gatt_attr *attr,
99 void *buf, uint16_t len, uint16_t offset)
100 {
101 const char *name = bt_get_name();
102
103 return bt_gatt_attr_read(conn, attr, buf, len, offset, name,
104 strlen(name));
105 }
106
107 #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE)
108
write_name(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * buf,uint16_t len,uint16_t offset,uint8_t flags)109 static ssize_t write_name(struct bt_conn *conn, const struct bt_gatt_attr *attr,
110 const void *buf, uint16_t len, uint16_t offset,
111 uint8_t flags)
112 {
113 char value[CONFIG_BT_DEVICE_NAME_MAX] = {};
114
115 if (offset >= sizeof(value)) {
116 return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
117 }
118
119 if (offset + len >= sizeof(value)) {
120 return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
121 }
122
123 memcpy(value, buf, len);
124
125 bt_set_name(value);
126
127 return len;
128 }
129
130 #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */
131
read_appearance(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)132 static ssize_t read_appearance(struct bt_conn *conn,
133 const struct bt_gatt_attr *attr, void *buf,
134 uint16_t len, uint16_t offset)
135 {
136 uint16_t appearance = sys_cpu_to_le16(bt_get_appearance());
137
138 return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance,
139 sizeof(appearance));
140 }
141
142 #if defined(CONFIG_BT_DEVICE_APPEARANCE_GATT_WRITABLE)
write_appearance(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * buf,uint16_t len,uint16_t offset,uint8_t flags)143 static ssize_t write_appearance(struct bt_conn *conn, const struct bt_gatt_attr *attr,
144 const void *buf, uint16_t len, uint16_t offset,
145 uint8_t flags)
146 {
147 uint16_t appearance_le = sys_cpu_to_le16(bt_get_appearance());
148 char * const appearance_le_bytes = (char *)&appearance_le;
149 uint16_t appearance;
150 int err;
151
152 if (offset >= sizeof(appearance_le)) {
153 return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
154 }
155
156 if ((offset + len) > sizeof(appearance_le)) {
157 return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
158 }
159
160 memcpy(&appearance_le_bytes[offset], buf, len);
161 appearance = sys_le16_to_cpu(appearance_le);
162
163 err = bt_set_appearance(appearance);
164
165 if (err) {
166 return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY);
167 }
168
169 return len;
170 }
171 #endif /* CONFIG_BT_DEVICE_APPEARANCE_GATT_WRITABLE */
172
173 #if CONFIG_BT_DEVICE_APPEARANCE_GATT_WRITABLE
174 #define GAP_APPEARANCE_PROPS (BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE)
175 #define GAP_APPEARANCE_PERMS (BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_AUTHEN)
176 #define GAP_APPEARANCE_WRITE_HANDLER write_appearance
177 #else
178 #define GAP_APPEARANCE_PROPS BT_GATT_CHRC_READ
179 #define GAP_APPEARANCE_PERMS BT_GATT_PERM_READ
180 #define GAP_APPEARANCE_WRITE_HANDLER NULL
181 #endif
182
183 #if defined (CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
184 /* This checks if the range entered is valid */
185 BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MIN_INT > 3200 &&
186 CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff));
187 BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MAX_INT > 3200 &&
188 CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff));
189 BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT > 3200 &&
190 CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff));
191 BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_MIN_INT == 0xffff) ||
192 (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <=
193 CONFIG_BT_PERIPHERAL_PREF_MAX_INT));
194 BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_TIMEOUT * 4U) >
195 ((1U + CONFIG_BT_PERIPHERAL_PREF_LATENCY) *
196 CONFIG_BT_PERIPHERAL_PREF_MAX_INT));
197
read_ppcp(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)198 static ssize_t read_ppcp(struct bt_conn *conn, const struct bt_gatt_attr *attr,
199 void *buf, uint16_t len, uint16_t offset)
200 {
201 struct __packed {
202 uint16_t min_int;
203 uint16_t max_int;
204 uint16_t latency;
205 uint16_t timeout;
206 } ppcp;
207
208 ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT);
209 ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT);
210 ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_LATENCY);
211 ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
212
213 return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp,
214 sizeof(ppcp));
215 }
216 #endif
217
218 #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY)
read_central_addr_res(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)219 static ssize_t read_central_addr_res(struct bt_conn *conn,
220 const struct bt_gatt_attr *attr, void *buf,
221 uint16_t len, uint16_t offset)
222 {
223 uint8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP;
224
225 return bt_gatt_attr_read(conn, attr, buf, len, offset,
226 ¢ral_addr_res, sizeof(central_addr_res));
227 }
228 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */
229
230 BT_GATT_SERVICE_DEFINE(_2_gap_svc,
231 BT_GATT_PRIMARY_SERVICE(BT_UUID_GAP),
232 #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE)
233 /* Require pairing for writes to device name */
234 BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME,
235 BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
236 BT_GATT_PERM_READ |
237 #if defined(CONFIG_DEVICE_NAME_GATT_WRITABLE_AUTHEN)
238 BT_GATT_PERM_WRITE_AUTHEN,
239 #elif defined(CONFIG_DEVICE_NAME_GATT_WRITABLE_ENCRYPT)
240 BT_GATT_PERM_WRITE_ENCRYPT,
241 #else
242 BT_GATT_PERM_WRITE,
243 #endif
244 read_name, write_name, bt_dev.name),
245 #else
246 BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ,
247 BT_GATT_PERM_READ, read_name, NULL, NULL),
248 #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */
249 BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, GAP_APPEARANCE_PROPS,
250 GAP_APPEARANCE_PERMS, read_appearance,
251 GAP_APPEARANCE_WRITE_HANDLER, NULL),
252 #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY)
253 BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES,
254 BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
255 read_central_addr_res, NULL, NULL),
256 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */
257 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
258 BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ,
259 BT_GATT_PERM_READ, read_ppcp, NULL, NULL),
260 #endif
261 );
262
263 struct sc_data {
264 uint16_t start;
265 uint16_t end;
266 } __packed;
267
268 struct gatt_sc_cfg {
269 uint8_t id;
270 bt_addr_le_t peer;
271 struct {
272 uint16_t start;
273 uint16_t end;
274 } data;
275 };
276
277 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
278 #define SC_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
279 #else
280 #define SC_CFG_MAX 0
281 #endif
282 static struct gatt_sc_cfg sc_cfg[SC_CFG_MAX];
283 BUILD_ASSERT(sizeof(struct sc_data) == sizeof(sc_cfg[0].data));
284
285 enum {
286 SC_RANGE_CHANGED, /* SC range changed */
287 SC_INDICATE_PENDING, /* SC indicate pending */
288 SC_LOAD, /* SC has been loaded from settings */
289
290 DB_HASH_VALID, /* Database hash needs to be calculated */
291 DB_HASH_LOAD, /* Database hash loaded from settings. */
292 DB_HASH_LOAD_PROC, /* DB hash loaded from settings has been processed. */
293
294 /* Total number of flags - must be at the end of the enum */
295 SC_NUM_FLAGS,
296 };
297
298 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
299 static struct gatt_sc {
300 struct bt_gatt_indicate_params params;
301 uint16_t start;
302 uint16_t end;
303 struct k_work_delayable work;
304
305 ATOMIC_DEFINE(flags, SC_NUM_FLAGS);
306 } gatt_sc;
307 #endif /* defined(CONFIG_BT_GATT_SERVICE_CHANGED) */
308
309 #if defined(CONFIG_BT_GATT_CACHING)
310 static struct db_hash {
311 uint8_t hash[16];
312 #if defined(CONFIG_BT_SETTINGS)
313 uint8_t stored_hash[16];
314 #endif
315 struct k_work_delayable work;
316 struct k_work_sync sync;
317 } db_hash;
318 #endif
319
find_sc_cfg(uint8_t id,const bt_addr_le_t * addr)320 static struct gatt_sc_cfg *find_sc_cfg(uint8_t id, const bt_addr_le_t *addr)
321 {
322 LOG_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr));
323
324 for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
325 if (id == sc_cfg[i].id &&
326 bt_addr_le_eq(&sc_cfg[i].peer, addr)) {
327 return &sc_cfg[i];
328 }
329 }
330
331 return NULL;
332 }
333
sc_store(struct gatt_sc_cfg * cfg)334 static void sc_store(struct gatt_sc_cfg *cfg)
335 {
336 int err;
337
338 err = bt_settings_store_sc(cfg->id, &cfg->peer, &cfg->data, sizeof(cfg->data));
339 if (err) {
340 LOG_ERR("failed to store SC (err %d)", err);
341 return;
342 }
343
344 LOG_DBG("stored SC for %s (0x%04x-0x%04x)", bt_addr_le_str(&cfg->peer), cfg->data.start,
345 cfg->data.end);
346 }
347
clear_sc_cfg(struct gatt_sc_cfg * cfg)348 static void clear_sc_cfg(struct gatt_sc_cfg *cfg)
349 {
350 memset(cfg, 0, sizeof(*cfg));
351 }
352
bt_gatt_clear_sc(uint8_t id,const bt_addr_le_t * addr)353 static int bt_gatt_clear_sc(uint8_t id, const bt_addr_le_t *addr)
354 {
355
356 struct gatt_sc_cfg *cfg;
357
358 cfg = find_sc_cfg(id, (bt_addr_le_t *)addr);
359 if (!cfg) {
360 return 0;
361 }
362
363 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
364 int err;
365
366 err = bt_settings_delete_sc(cfg->id, &cfg->peer);
367 if (err) {
368 LOG_ERR("failed to delete SC (err %d)", err);
369 } else {
370 LOG_DBG("deleted SC for %s", bt_addr_le_str(&cfg->peer));
371 }
372 }
373
374 clear_sc_cfg(cfg);
375
376 return 0;
377 }
378
sc_clear(struct bt_conn * conn)379 static void sc_clear(struct bt_conn *conn)
380 {
381 if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
382 int err;
383
384 err = bt_gatt_clear_sc(conn->id, &conn->le.dst);
385 if (err) {
386 LOG_ERR("Failed to clear SC %d", err);
387 }
388 } else {
389 struct gatt_sc_cfg *cfg;
390
391 cfg = find_sc_cfg(conn->id, &conn->le.dst);
392 if (cfg) {
393 clear_sc_cfg(cfg);
394 }
395 }
396 }
397
sc_reset(struct gatt_sc_cfg * cfg)398 static void sc_reset(struct gatt_sc_cfg *cfg)
399 {
400 LOG_DBG("peer %s", bt_addr_le_str(&cfg->peer));
401
402 memset(&cfg->data, 0, sizeof(cfg->data));
403
404 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
405 sc_store(cfg);
406 }
407 }
408
update_range(uint16_t * start,uint16_t * end,uint16_t new_start,uint16_t new_end)409 static bool update_range(uint16_t *start, uint16_t *end, uint16_t new_start,
410 uint16_t new_end)
411 {
412 LOG_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x", *start, *end, new_start,
413 new_end);
414
415 /* Check if inside existing range */
416 if (new_start >= *start && new_end <= *end) {
417 return false;
418 }
419
420 /* Update range */
421 if (*start > new_start) {
422 *start = new_start;
423 }
424
425 if (*end < new_end) {
426 *end = new_end;
427 }
428
429 return true;
430 }
431
sc_save(uint8_t id,bt_addr_le_t * peer,uint16_t start,uint16_t end)432 static void sc_save(uint8_t id, bt_addr_le_t *peer, uint16_t start, uint16_t end)
433 {
434 struct gatt_sc_cfg *cfg;
435 bool modified = false;
436
437 LOG_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start, end);
438
439 cfg = find_sc_cfg(id, peer);
440 if (!cfg) {
441 /* Find and initialize a free sc_cfg entry */
442 cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
443 if (!cfg) {
444 LOG_ERR("unable to save SC: no cfg left");
445 return;
446 }
447
448 cfg->id = id;
449 bt_addr_le_copy(&cfg->peer, peer);
450 }
451
452 /* Check if there is any change stored */
453 if (!(cfg->data.start || cfg->data.end)) {
454 cfg->data.start = start;
455 cfg->data.end = end;
456 modified = true;
457 goto done;
458 }
459
460 modified = update_range(&cfg->data.start, &cfg->data.end, start, end);
461
462 done:
463 if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
464 modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
465 sc_store(cfg);
466 }
467 }
468
sc_ccc_cfg_write(struct bt_conn * conn,const struct bt_gatt_attr * attr,uint16_t value)469 static ssize_t sc_ccc_cfg_write(struct bt_conn *conn,
470 const struct bt_gatt_attr *attr, uint16_t value)
471 {
472 LOG_DBG("value 0x%04x", value);
473
474 if (value == BT_GATT_CCC_INDICATE) {
475 /* Create a new SC configuration entry if subscribed */
476 sc_save(conn->id, &conn->le.dst, 0, 0);
477 } else {
478 sc_clear(conn);
479 }
480
481 return sizeof(value);
482 }
483
484 static struct _bt_gatt_ccc sc_ccc = BT_GATT_CCC_INITIALIZER(NULL,
485 sc_ccc_cfg_write,
486 NULL);
487
488 /* Do not shuffle the values in this enum, they are used as bit offsets when
489 * saving the CF flags to NVS (i.e. NVS persists between FW upgrades).
490 */
491 enum {
492 CF_CHANGE_AWARE, /* Client is changed aware */
493 CF_DB_HASH_READ, /* The client has read the database hash */
494
495 /* Total number of flags - must be at the end of the enum */
496 CF_NUM_FLAGS,
497 };
498
499 #define CF_BIT_ROBUST_CACHING 0
500 #define CF_BIT_EATT 1
501 #define CF_BIT_NOTIFY_MULTI 2
502 #define CF_BIT_LAST CF_BIT_NOTIFY_MULTI
503
504 #define CF_NUM_BITS (CF_BIT_LAST + 1)
505 #define CF_NUM_BYTES ((CF_BIT_LAST / 8) + 1)
506 #define CF_FLAGS_STORE_LEN 1
507
508 #define CF_ROBUST_CACHING(_cfg) (_cfg->data[0] & BIT(CF_BIT_ROBUST_CACHING))
509 #define CF_EATT(_cfg) (_cfg->data[0] & BIT(CF_BIT_EATT))
510 #define CF_NOTIFY_MULTI(_cfg) (_cfg->data[0] & BIT(CF_BIT_NOTIFY_MULTI))
511
512 struct gatt_cf_cfg {
513 uint8_t id;
514 bt_addr_le_t peer;
515 uint8_t data[CF_NUM_BYTES];
516 ATOMIC_DEFINE(flags, CF_NUM_FLAGS);
517 };
518
519 #if defined(CONFIG_BT_GATT_CACHING)
520 #define CF_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
521 #else
522 #define CF_CFG_MAX 0
523 #endif /* CONFIG_BT_GATT_CACHING */
524
525 static struct gatt_cf_cfg cf_cfg[CF_CFG_MAX] = {};
526
clear_cf_cfg(struct gatt_cf_cfg * cfg)527 static void clear_cf_cfg(struct gatt_cf_cfg *cfg)
528 {
529 bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
530 memset(cfg->data, 0, sizeof(cfg->data));
531 atomic_set(cfg->flags, 0);
532 }
533
534 enum delayed_store_flags {
535 DELAYED_STORE_CCC,
536 DELAYED_STORE_CF,
537 DELAYED_STORE_NUM_FLAGS
538 };
539
540 #if defined(CONFIG_BT_SETTINGS_DELAYED_STORE)
541 static void gatt_delayed_store_enqueue(uint8_t id, const bt_addr_le_t *peer_addr,
542 enum delayed_store_flags flag);
543 #endif
544
545 #if defined(CONFIG_BT_GATT_CACHING)
set_change_aware_no_store(struct gatt_cf_cfg * cfg,bool aware)546 static bool set_change_aware_no_store(struct gatt_cf_cfg *cfg, bool aware)
547 {
548 bool changed;
549
550 if (aware) {
551 changed = !atomic_test_and_set_bit(cfg->flags, CF_CHANGE_AWARE);
552 } else {
553 changed = atomic_test_and_clear_bit(cfg->flags, CF_CHANGE_AWARE);
554 }
555
556 LOG_DBG("peer is now change-%saware", aware ? "" : "un");
557
558 return changed;
559 }
560
set_change_aware(struct gatt_cf_cfg * cfg,bool aware)561 static void set_change_aware(struct gatt_cf_cfg *cfg, bool aware)
562 {
563 bool changed = set_change_aware_no_store(cfg, aware);
564
565 #if defined(CONFIG_BT_SETTINGS_DELAYED_STORE)
566 if (changed) {
567 gatt_delayed_store_enqueue(cfg->id, &cfg->peer, DELAYED_STORE_CF);
568 }
569 #else
570 (void)changed;
571 #endif
572 }
573
574 static int bt_gatt_store_cf(uint8_t id, const bt_addr_le_t *peer);
575
set_all_change_unaware(void)576 static void set_all_change_unaware(void)
577 {
578 #if defined(CONFIG_BT_SETTINGS)
579 /* Mark all bonded peers as change-unaware.
580 * - Can be called when not in a connection with said peers
581 * - Doesn't have any effect when no bonds are in memory. This is the
582 * case when the device has just booted and `settings_load` hasn't yet
583 * been called.
584 * - Expensive to call, as it will write the new status to settings
585 * right away.
586 */
587 for (size_t i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
588 struct gatt_cf_cfg *cfg = &cf_cfg[i];
589
590 if (!bt_addr_le_eq(&cfg->peer, BT_ADDR_LE_ANY)) {
591 set_change_aware_no_store(cfg, false);
592 bt_gatt_store_cf(cfg->id, &cfg->peer);
593 }
594 }
595 #endif /* CONFIG_BT_SETTINGS */
596 }
597
find_cf_cfg(struct bt_conn * conn)598 static struct gatt_cf_cfg *find_cf_cfg(struct bt_conn *conn)
599 {
600 int i;
601
602 for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
603 struct gatt_cf_cfg *cfg = &cf_cfg[i];
604
605 if (!conn) {
606 if (bt_addr_le_eq(&cfg->peer, BT_ADDR_LE_ANY)) {
607 return cfg;
608 }
609 } else if (bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer)) {
610 return cfg;
611 }
612 }
613
614 return NULL;
615 }
616
cf_read(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)617 static ssize_t cf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
618 void *buf, uint16_t len, uint16_t offset)
619 {
620 struct gatt_cf_cfg *cfg;
621 uint8_t data[1] = {};
622
623 cfg = find_cf_cfg(conn);
624 if (cfg) {
625 memcpy(data, cfg->data, sizeof(data));
626 }
627
628 return bt_gatt_attr_read(conn, attr, buf, len, offset, data,
629 sizeof(data));
630 }
631
cf_set_value(struct gatt_cf_cfg * cfg,const uint8_t * value,uint16_t len)632 static bool cf_set_value(struct gatt_cf_cfg *cfg, const uint8_t *value, uint16_t len)
633 {
634 uint16_t i;
635
636 /* Validate the bits */
637 for (i = 0U; i <= CF_BIT_LAST && (i / 8) < len; i++) {
638 if ((cfg->data[i / 8] & BIT(i % 8)) &&
639 !(value[i / 8] & BIT(i % 8))) {
640 /* A client shall never clear a bit it has set */
641 return false;
642 }
643 }
644
645 /* Set the bits for each octect */
646 for (i = 0U; i < len && i < CF_NUM_BYTES; i++) {
647 if (i == (CF_NUM_BYTES - 1)) {
648 cfg->data[i] |= value[i] & BIT_MASK(CF_NUM_BITS % 8);
649 } else {
650 cfg->data[i] |= value[i];
651 }
652
653 LOG_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i], value[i]);
654 }
655
656 return true;
657 }
658
cf_write(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * buf,uint16_t len,uint16_t offset,uint8_t flags)659 static ssize_t cf_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,
660 const void *buf, uint16_t len, uint16_t offset, uint8_t flags)
661 {
662 struct gatt_cf_cfg *cfg;
663 const uint8_t *value = buf;
664
665 if (offset > sizeof(cfg->data)) {
666 return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
667 }
668
669 if (offset + len > sizeof(cfg->data)) {
670 return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
671 }
672
673 cfg = find_cf_cfg(conn);
674 if (!cfg) {
675 cfg = find_cf_cfg(NULL);
676 }
677
678 if (!cfg) {
679 LOG_WRN("No space to store Client Supported Features");
680 return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
681 }
682
683 LOG_DBG("handle 0x%04x len %u", attr->handle, len);
684
685 if (!cf_set_value(cfg, value, len)) {
686 return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
687 }
688
689 bt_addr_le_copy(&cfg->peer, &conn->le.dst);
690 cfg->id = conn->id;
691 set_change_aware(cfg, true);
692
693 return len;
694 }
695
696 struct gen_hash_state {
697 struct tc_cmac_struct state;
698 int err;
699 };
700
701 union hash_attr_value {
702 /* Bluetooth Core Specification Version 5.3 | Vol 3, Part G
703 * Table 3.1: Service declaration
704 */
705 union {
706 uint16_t uuid16;
707 uint8_t uuid128[BT_UUID_SIZE_128];
708 } __packed service;
709 /* Bluetooth Core Specification Version 5.3 | Vol 3, Part G
710 * Table 3.2: Include declaration
711 */
712 struct {
713 uint16_t attribute_handle;
714 uint16_t end_group_handle;
715 uint16_t uuid16;
716 } __packed inc;
717 /* Bluetooth Core Specification Version 5.3 | Vol 3, Part G
718 * Table 3.3: Characteristic declaration
719 */
720 struct {
721 uint8_t properties;
722 uint16_t value_handle;
723 union {
724 uint16_t uuid16;
725 uint8_t uuid128[BT_UUID_SIZE_128];
726 } __packed;
727 } __packed chrc;
728 /* Bluetooth Core Specification Version 5.3 | Vol 3, Part G
729 * Table 3.5: Characteristic Properties bit field
730 */
731 struct {
732 uint16_t properties;
733 } __packed cep;
734 } __packed;
735
gen_hash_m(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)736 static uint8_t gen_hash_m(const struct bt_gatt_attr *attr, uint16_t handle,
737 void *user_data)
738 {
739 struct gen_hash_state *state = user_data;
740 struct bt_uuid_16 *u16;
741 uint8_t data[sizeof(union hash_attr_value)];
742 ssize_t len;
743 uint16_t value;
744
745 if (attr->uuid->type != BT_UUID_TYPE_16)
746 return BT_GATT_ITER_CONTINUE;
747
748 u16 = (struct bt_uuid_16 *)attr->uuid;
749
750 switch (u16->val) {
751 /* Attributes to hash: handle + UUID + value */
752 case BT_UUID_GATT_PRIMARY_VAL:
753 case BT_UUID_GATT_SECONDARY_VAL:
754 case BT_UUID_GATT_INCLUDE_VAL:
755 case BT_UUID_GATT_CHRC_VAL:
756 case BT_UUID_GATT_CEP_VAL:
757 value = sys_cpu_to_le16(handle);
758 if (tc_cmac_update(&state->state, (uint8_t *)&value,
759 sizeof(handle)) == TC_CRYPTO_FAIL) {
760 state->err = -EINVAL;
761 return BT_GATT_ITER_STOP;
762 }
763
764 value = sys_cpu_to_le16(u16->val);
765 if (tc_cmac_update(&state->state, (uint8_t *)&value,
766 sizeof(u16->val)) == TC_CRYPTO_FAIL) {
767 state->err = -EINVAL;
768 return BT_GATT_ITER_STOP;
769 }
770
771 len = attr->read(NULL, attr, data, sizeof(data), 0);
772 if (len < 0) {
773 state->err = len;
774 return BT_GATT_ITER_STOP;
775 }
776
777 if (tc_cmac_update(&state->state, data, len) ==
778 TC_CRYPTO_FAIL) {
779 state->err = -EINVAL;
780 return BT_GATT_ITER_STOP;
781 }
782
783 break;
784 /* Attributes to hash: handle + UUID */
785 case BT_UUID_GATT_CUD_VAL:
786 case BT_UUID_GATT_CCC_VAL:
787 case BT_UUID_GATT_SCC_VAL:
788 case BT_UUID_GATT_CPF_VAL:
789 case BT_UUID_GATT_CAF_VAL:
790 value = sys_cpu_to_le16(handle);
791 if (tc_cmac_update(&state->state, (uint8_t *)&value,
792 sizeof(handle)) == TC_CRYPTO_FAIL) {
793 state->err = -EINVAL;
794 return BT_GATT_ITER_STOP;
795 }
796
797 value = sys_cpu_to_le16(u16->val);
798 if (tc_cmac_update(&state->state, (uint8_t *)&value,
799 sizeof(u16->val)) == TC_CRYPTO_FAIL) {
800 state->err = -EINVAL;
801 return BT_GATT_ITER_STOP;
802 }
803 break;
804 default:
805 return BT_GATT_ITER_CONTINUE;
806 }
807
808 return BT_GATT_ITER_CONTINUE;
809 }
810
db_hash_store(void)811 static void db_hash_store(void)
812 {
813 #if defined(CONFIG_BT_SETTINGS)
814 int err;
815
816 err = bt_settings_store_hash(&db_hash.hash, sizeof(db_hash.hash));
817 if (err) {
818 LOG_ERR("Failed to save Database Hash (err %d)", err);
819 }
820
821 LOG_DBG("Database Hash stored");
822 #endif /* CONFIG_BT_SETTINGS */
823 }
824
db_hash_gen(void)825 static void db_hash_gen(void)
826 {
827 uint8_t key[16] = {};
828 struct tc_aes_key_sched_struct sched;
829 struct gen_hash_state state;
830
831 if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) {
832 LOG_ERR("Unable to setup AES CMAC");
833 return;
834 }
835
836 bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state);
837
838 if (tc_cmac_final(db_hash.hash, &state.state) == TC_CRYPTO_FAIL) {
839 LOG_ERR("Unable to calculate hash");
840 return;
841 }
842
843 /**
844 * Core 5.1 does not state the endianess of the hash.
845 * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic
846 * Values shall be LE unless otherwise defined. PTS expects hash to be
847 * in little endianess as well. bt_smp_aes_cmac calculates the hash in
848 * big endianess so we have to swap.
849 */
850 sys_mem_swap(db_hash.hash, sizeof(db_hash.hash));
851
852 LOG_HEXDUMP_DBG(db_hash.hash, sizeof(db_hash.hash), "Hash: ");
853
854 atomic_set_bit(gatt_sc.flags, DB_HASH_VALID);
855 }
856
857 static void sc_indicate(uint16_t start, uint16_t end);
858
do_db_hash(void)859 static void do_db_hash(void)
860 {
861 bool new_hash = !atomic_test_bit(gatt_sc.flags, DB_HASH_VALID);
862
863 if (new_hash) {
864 db_hash_gen();
865 }
866
867 #if defined(CONFIG_BT_SETTINGS)
868 bool hash_loaded_from_settings =
869 atomic_test_bit(gatt_sc.flags, DB_HASH_LOAD);
870 bool already_processed =
871 atomic_test_bit(gatt_sc.flags, DB_HASH_LOAD_PROC);
872
873 if (!hash_loaded_from_settings) {
874 /* we want to generate the hash, but not overwrite the hash
875 * stored in settings, that we haven't yet loaded.
876 */
877 return;
878 }
879
880 if (already_processed) {
881 /* hash has been loaded from settings and we have already
882 * executed the special case below once. we can now safely save
883 * the calculated hash to settings (if it has changed).
884 */
885 if (new_hash) {
886 set_all_change_unaware();
887 db_hash_store();
888 }
889 } else {
890 /* this is only supposed to run once, on bootup, after the hash
891 * has been loaded from settings.
892 */
893 atomic_set_bit(gatt_sc.flags, DB_HASH_LOAD_PROC);
894
895 /* Check if hash matches then skip SC update */
896 if (!memcmp(db_hash.stored_hash, db_hash.hash,
897 sizeof(db_hash.stored_hash))) {
898 LOG_DBG("Database Hash matches");
899 k_work_cancel_delayable(&gatt_sc.work);
900 atomic_clear_bit(gatt_sc.flags, SC_RANGE_CHANGED);
901 return;
902 }
903
904 LOG_HEXDUMP_DBG(db_hash.hash, sizeof(db_hash.hash), "New Hash: ");
905
906 /* GATT database has been modified since last boot, likely due
907 * to a firmware update or a dynamic service that was not
908 * re-registered on boot.
909 * Indicate Service Changed to all bonded devices for the full
910 * database range to invalidate client-side cache and force
911 * discovery on reconnect.
912 */
913 sc_indicate(0x0001, 0xffff);
914
915 /* Hash did not match, overwrite with current hash.
916 * Also immediately set all peers (in settings) as
917 * change-unaware.
918 */
919 set_all_change_unaware();
920 db_hash_store();
921 }
922 #endif /* defined(CONFIG_BT_SETTINGS) */
923 }
924
db_hash_process(struct k_work * work)925 static void db_hash_process(struct k_work *work)
926 {
927 do_db_hash();
928 }
929
db_hash_read(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)930 static ssize_t db_hash_read(struct bt_conn *conn,
931 const struct bt_gatt_attr *attr,
932 void *buf, uint16_t len, uint16_t offset)
933 {
934 struct gatt_cf_cfg *cfg;
935
936 /* Check if db_hash is already pending in which case it shall be
937 * generated immediately instead of waiting for the work to complete.
938 */
939 (void)k_work_cancel_delayable_sync(&db_hash.work, &db_hash.sync);
940 if (!atomic_test_bit(gatt_sc.flags, DB_HASH_VALID)) {
941 db_hash_gen();
942 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
943 set_all_change_unaware();
944 db_hash_store();
945 }
946 }
947
948 /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
949 * 2.5.2.1 Robust Caching
950 * A connected client becomes change-aware when...
951 * The client reads the Database Hash characteristic and then the server
952 * receives another ATT request from the client.
953 */
954 cfg = find_cf_cfg(conn);
955 if (cfg &&
956 CF_ROBUST_CACHING(cfg) &&
957 !atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) {
958 atomic_set_bit(cfg->flags, CF_DB_HASH_READ);
959 }
960
961 return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash.hash,
962 sizeof(db_hash.hash));
963 }
964
remove_cf_cfg(struct bt_conn * conn)965 static void remove_cf_cfg(struct bt_conn *conn)
966 {
967 struct gatt_cf_cfg *cfg;
968
969 cfg = find_cf_cfg(conn);
970 if (!cfg) {
971 return;
972 }
973
974 /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405:
975 * For clients with a trusted relationship, the characteristic value
976 * shall be persistent across connections. For clients without a
977 * trusted relationship the characteristic value shall be set to the
978 * default value at each connection.
979 */
980 if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
981 clear_cf_cfg(cfg);
982 } else {
983 /* Update address in case it has changed */
984 bt_addr_le_copy(&cfg->peer, &conn->le.dst);
985 }
986 }
987
988 #if defined(CONFIG_BT_EATT)
989 #define SF_BIT_EATT 0
990 #define SF_BIT_LAST SF_BIT_EATT
991
sf_read(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)992 static ssize_t sf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
993 void *buf, uint16_t len, uint16_t offset)
994 {
995 uint8_t value = BIT(SF_BIT_EATT);
996
997 return bt_gatt_attr_read(conn, attr, buf, len, offset, &value,
998 sizeof(value));
999 }
1000 #endif /* CONFIG_BT_EATT */
1001 #endif /* CONFIG_BT_GATT_CACHING */
1002
1003 static struct gatt_cf_cfg *find_cf_cfg_by_addr(uint8_t id,
1004 const bt_addr_le_t *addr);
1005
bt_gatt_store_cf(uint8_t id,const bt_addr_le_t * peer)1006 static int bt_gatt_store_cf(uint8_t id, const bt_addr_le_t *peer)
1007 {
1008 #if defined(CONFIG_BT_GATT_CACHING)
1009 struct gatt_cf_cfg *cfg;
1010 char dst[CF_NUM_BYTES + CF_FLAGS_STORE_LEN];
1011 char *str;
1012 size_t len;
1013 int err;
1014
1015 cfg = find_cf_cfg_by_addr(id, peer);
1016 if (!cfg) {
1017 /* No cfg found, just clear it */
1018 LOG_DBG("No config for CF");
1019 str = NULL;
1020 len = 0;
1021 } else {
1022 str = (char *)cfg->data;
1023 len = sizeof(cfg->data);
1024
1025 /* add the CF data to a temp array */
1026 memcpy(dst, str, len);
1027
1028 /* add the change-aware flag */
1029 bool is_change_aware = atomic_test_bit(cfg->flags, CF_CHANGE_AWARE);
1030
1031 dst[len] = 0;
1032 WRITE_BIT(dst[len], CF_CHANGE_AWARE, is_change_aware);
1033 len += CF_FLAGS_STORE_LEN;
1034
1035 str = dst;
1036 }
1037
1038 err = bt_settings_store_cf(id, peer, str, len);
1039 if (err) {
1040 LOG_ERR("Failed to store Client Features (err %d)", err);
1041 return err;
1042 }
1043
1044 LOG_DBG("Stored CF for %s", bt_addr_le_str(peer));
1045 LOG_HEXDUMP_DBG(str, len, "Saved data");
1046 #endif /* CONFIG_BT_GATT_CACHING */
1047 return 0;
1048
1049 }
1050
1051 #if defined(CONFIG_BT_SETTINGS) && defined(CONFIG_BT_SMP)
1052 /** Struct used to store both the id and the random address of a device when replacing
1053 * random addresses in the ccc attribute's cfg array with the device's id address after
1054 * pairing complete.
1055 */
1056 struct addr_match {
1057 const bt_addr_le_t *private_addr;
1058 const bt_addr_le_t *id_addr;
1059 };
1060
convert_to_id_on_match(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)1061 static uint8_t convert_to_id_on_match(const struct bt_gatt_attr *attr,
1062 uint16_t handle, void *user_data)
1063 {
1064 struct _bt_gatt_ccc *ccc;
1065 struct addr_match *match = user_data;
1066
1067 /* Check if attribute is a CCC */
1068 if (attr->write != bt_gatt_attr_write_ccc) {
1069 return BT_GATT_ITER_CONTINUE;
1070 }
1071
1072 ccc = attr->user_data;
1073
1074 /* Copy the device's id address to the config's address if the config's address is the
1075 * same as the device's private address
1076 */
1077 for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
1078 if (bt_addr_le_eq(&ccc->cfg[i].peer, match->private_addr)) {
1079 bt_addr_le_copy(&ccc->cfg[i].peer, match->id_addr);
1080 }
1081 }
1082
1083 return BT_GATT_ITER_CONTINUE;
1084 }
1085
bt_gatt_identity_resolved(struct bt_conn * conn,const bt_addr_le_t * private_addr,const bt_addr_le_t * id_addr)1086 static void bt_gatt_identity_resolved(struct bt_conn *conn, const bt_addr_le_t *private_addr,
1087 const bt_addr_le_t *id_addr)
1088 {
1089 /* Update the ccc cfg addresses */
1090 struct addr_match user_data = {
1091 .private_addr = private_addr,
1092 .id_addr = id_addr
1093 };
1094 bool is_bonded = bt_addr_le_is_bonded(conn->id, &conn->le.dst);
1095
1096 bt_gatt_foreach_attr(0x0001, 0xffff, convert_to_id_on_match, &user_data);
1097
1098 /* Store the ccc */
1099 if (is_bonded) {
1100 bt_gatt_store_ccc(conn->id, &conn->le.dst);
1101 }
1102
1103 /* Update the cf addresses and store it if we get a match */
1104 struct gatt_cf_cfg *cfg = find_cf_cfg_by_addr(conn->id, private_addr);
1105
1106 if (cfg) {
1107 bt_addr_le_copy(&cfg->peer, id_addr);
1108 if (is_bonded) {
1109 bt_gatt_store_cf(conn->id, &conn->le.dst);
1110 }
1111 }
1112 }
1113
bt_gatt_pairing_complete(struct bt_conn * conn,bool bonded)1114 static void bt_gatt_pairing_complete(struct bt_conn *conn, bool bonded)
1115 {
1116 if (bonded) {
1117 /* Store the ccc and cf data */
1118 bt_gatt_store_ccc(conn->id, &(conn->le.dst));
1119 bt_gatt_store_cf(conn->id, &conn->le.dst);
1120 }
1121 }
1122 #endif /* CONFIG_BT_SETTINGS && CONFIG_BT_SMP */
1123
1124 BT_GATT_SERVICE_DEFINE(_1_gatt_svc,
1125 BT_GATT_PRIMARY_SERVICE(BT_UUID_GATT),
1126 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
1127 /* Bluetooth 5.0, Vol3 Part G:
1128 * The Service Changed characteristic Attribute Handle on the server
1129 * shall not change if the server has a trusted relationship with any
1130 * client.
1131 */
1132 BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE,
1133 BT_GATT_PERM_NONE, NULL, NULL, NULL),
1134 BT_GATT_CCC_MANAGED(&sc_ccc, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
1135 #if defined(CONFIG_BT_GATT_CACHING)
1136 BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES,
1137 BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
1138 BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
1139 cf_read, cf_write, NULL),
1140 BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH,
1141 BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
1142 db_hash_read, NULL, NULL),
1143 #if defined(CONFIG_BT_EATT)
1144 BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SERVER_FEATURES,
1145 BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
1146 sf_read, NULL, NULL),
1147 #endif /* CONFIG_BT_EATT */
1148 #endif /* CONFIG_BT_GATT_CACHING */
1149 #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */
1150 );
1151
1152 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
found_attr(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)1153 static uint8_t found_attr(const struct bt_gatt_attr *attr, uint16_t handle,
1154 void *user_data)
1155 {
1156 const struct bt_gatt_attr **found = user_data;
1157
1158 *found = attr;
1159
1160 return BT_GATT_ITER_STOP;
1161 }
1162
find_attr(uint16_t handle)1163 static const struct bt_gatt_attr *find_attr(uint16_t handle)
1164 {
1165 const struct bt_gatt_attr *attr = NULL;
1166
1167 bt_gatt_foreach_attr(handle, handle, found_attr, &attr);
1168
1169 return attr;
1170 }
1171
gatt_insert(struct bt_gatt_service * svc,uint16_t last_handle)1172 static void gatt_insert(struct bt_gatt_service *svc, uint16_t last_handle)
1173 {
1174 struct bt_gatt_service *tmp, *prev = NULL;
1175
1176 if (last_handle == 0 || svc->attrs[0].handle > last_handle) {
1177 sys_slist_append(&db, &svc->node);
1178 return;
1179 }
1180
1181 /* DB shall always have its service in ascending order */
1182 SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node) {
1183 if (tmp->attrs[0].handle > svc->attrs[0].handle) {
1184 if (prev) {
1185 sys_slist_insert(&db, &prev->node, &svc->node);
1186 } else {
1187 sys_slist_prepend(&db, &svc->node);
1188 }
1189 return;
1190 }
1191
1192 prev = tmp;
1193 }
1194 }
1195
gatt_register(struct bt_gatt_service * svc)1196 static int gatt_register(struct bt_gatt_service *svc)
1197 {
1198 struct bt_gatt_service *last;
1199 uint16_t handle, last_handle;
1200 struct bt_gatt_attr *attrs = svc->attrs;
1201 uint16_t count = svc->attr_count;
1202
1203 if (sys_slist_is_empty(&db)) {
1204 handle = last_static_handle;
1205 last_handle = 0;
1206 goto populate;
1207 }
1208
1209 last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
1210 handle = last->attrs[last->attr_count - 1].handle;
1211 last_handle = handle;
1212
1213 populate:
1214 /* Populate the handles and append them to the list */
1215 for (; attrs && count; attrs++, count--) {
1216 if (!attrs->handle) {
1217 /* Allocate handle if not set already */
1218 attrs->handle = ++handle;
1219 } else if (attrs->handle > handle) {
1220 /* Use existing handle if valid */
1221 handle = attrs->handle;
1222 } else if (find_attr(attrs->handle)) {
1223 /* Service has conflicting handles */
1224 LOG_ERR("Unable to register handle 0x%04x", attrs->handle);
1225 return -EINVAL;
1226 }
1227
1228 LOG_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x", attrs, attrs->handle,
1229 bt_uuid_str(attrs->uuid), attrs->perm);
1230 }
1231
1232 gatt_insert(svc, last_handle);
1233
1234 return 0;
1235 }
1236 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
1237
sc_work_submit(k_timeout_t timeout)1238 static inline void sc_work_submit(k_timeout_t timeout)
1239 {
1240 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
1241 k_work_reschedule(&gatt_sc.work, timeout);
1242 #endif
1243 }
1244
1245 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
sc_indicate_rsp(struct bt_conn * conn,struct bt_gatt_indicate_params * params,uint8_t err)1246 static void sc_indicate_rsp(struct bt_conn *conn,
1247 struct bt_gatt_indicate_params *params, uint8_t err)
1248 {
1249 #if defined(CONFIG_BT_GATT_CACHING)
1250 struct gatt_cf_cfg *cfg;
1251 #endif
1252
1253 LOG_DBG("err 0x%02x", err);
1254
1255 atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
1256
1257 /* Check if there is new change in the meantime */
1258 if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
1259 /* Reschedule without any delay since it is waiting already */
1260 sc_work_submit(K_NO_WAIT);
1261 }
1262
1263 #if defined(CONFIG_BT_GATT_CACHING)
1264 /* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 3, Part G page 1476:
1265 * 2.5.2.1 Robust Caching
1266 * ... a change-unaware connected client using exactly one ATT bearer
1267 * becomes change-aware when ...
1268 * The client receives and confirms a Handle Value Indication
1269 * for the Service Changed characteristic
1270 */
1271 if (bt_att_fixed_chan_only(conn)) {
1272 cfg = find_cf_cfg(conn);
1273 if (cfg && CF_ROBUST_CACHING(cfg)) {
1274 set_change_aware(cfg, true);
1275 }
1276 }
1277 #endif /* CONFIG_BT_GATT_CACHING */
1278 }
1279
sc_process(struct k_work * work)1280 static void sc_process(struct k_work *work)
1281 {
1282 struct k_work_delayable *dwork = k_work_delayable_from_work(work);
1283 struct gatt_sc *sc = CONTAINER_OF(dwork, struct gatt_sc, work);
1284 uint16_t sc_range[2];
1285
1286 __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING),
1287 "Indicate already pending");
1288
1289 LOG_DBG("start 0x%04x end 0x%04x", sc->start, sc->end);
1290
1291 sc_range[0] = sys_cpu_to_le16(sc->start);
1292 sc_range[1] = sys_cpu_to_le16(sc->end);
1293
1294 atomic_clear_bit(sc->flags, SC_RANGE_CHANGED);
1295 sc->start = 0U;
1296 sc->end = 0U;
1297
1298 sc->params.attr = &_1_gatt_svc.attrs[2];
1299 sc->params.func = sc_indicate_rsp;
1300 sc->params.data = &sc_range[0];
1301 sc->params.len = sizeof(sc_range);
1302 #if defined(CONFIG_BT_EATT)
1303 sc->params.chan_opt = BT_ATT_CHAN_OPT_NONE;
1304 #endif /* CONFIG_BT_EATT */
1305
1306 if (bt_gatt_indicate(NULL, &sc->params)) {
1307 /* No connections to indicate */
1308 return;
1309 }
1310
1311 atomic_set_bit(sc->flags, SC_INDICATE_PENDING);
1312 }
1313 #endif /* defined(CONFIG_BT_GATT_SERVICE_CHANGED) */
1314
clear_ccc_cfg(struct bt_gatt_ccc_cfg * cfg)1315 static void clear_ccc_cfg(struct bt_gatt_ccc_cfg *cfg)
1316 {
1317 bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
1318 cfg->id = 0U;
1319 cfg->value = 0U;
1320 }
1321
1322 static void gatt_store_ccc_cf(uint8_t id, const bt_addr_le_t *peer_addr);
1323
1324 struct ds_peer {
1325 uint8_t id;
1326 bt_addr_le_t peer;
1327
1328 ATOMIC_DEFINE(flags, DELAYED_STORE_NUM_FLAGS);
1329 };
1330
1331 IF_ENABLED(CONFIG_BT_SETTINGS_DELAYED_STORE, (
1332 static struct gatt_delayed_store {
1333 struct ds_peer peer_list[CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN];
1334 struct k_work_delayable work;
1335 } gatt_delayed_store;
1336 ))
1337
gatt_delayed_store_find(uint8_t id,const bt_addr_le_t * peer_addr)1338 static struct ds_peer *gatt_delayed_store_find(uint8_t id,
1339 const bt_addr_le_t *peer_addr)
1340 {
1341 IF_ENABLED(CONFIG_BT_SETTINGS_DELAYED_STORE, ({
1342 struct ds_peer *el;
1343
1344 for (size_t i = 0; i < ARRAY_SIZE(gatt_delayed_store.peer_list); i++) {
1345 el = &gatt_delayed_store.peer_list[i];
1346 if (el->id == id &&
1347 bt_addr_le_eq(peer_addr, &el->peer)) {
1348 return el;
1349 }
1350 }
1351 }))
1352
1353 return NULL;
1354 }
1355
gatt_delayed_store_free(struct ds_peer * el)1356 static void gatt_delayed_store_free(struct ds_peer *el)
1357 {
1358 if (el) {
1359 el->id = 0;
1360 memset(&el->peer, 0, sizeof(el->peer));
1361 atomic_set(el->flags, 0);
1362 }
1363 }
1364
1365 #if defined(CONFIG_BT_SETTINGS_DELAYED_STORE)
gatt_delayed_store_alloc(uint8_t id,const bt_addr_le_t * peer_addr)1366 static struct ds_peer *gatt_delayed_store_alloc(uint8_t id,
1367 const bt_addr_le_t *peer_addr)
1368 {
1369 struct ds_peer *el;
1370
1371 for (size_t i = 0; i < ARRAY_SIZE(gatt_delayed_store.peer_list); i++) {
1372 el = &gatt_delayed_store.peer_list[i];
1373
1374 /* Checking for the flags is cheaper than a memcmp for the
1375 * address, so we use that to signal that a given slot is
1376 * free.
1377 */
1378 if (atomic_get(el->flags) == 0) {
1379 bt_addr_le_copy(&el->peer, peer_addr);
1380 el->id = id;
1381
1382 return el;
1383 }
1384 }
1385
1386 return NULL;
1387 }
1388
gatt_delayed_store_enqueue(uint8_t id,const bt_addr_le_t * peer_addr,enum delayed_store_flags flag)1389 static void gatt_delayed_store_enqueue(uint8_t id, const bt_addr_le_t *peer_addr,
1390 enum delayed_store_flags flag)
1391 {
1392 bool bonded = bt_addr_le_is_bonded(id, peer_addr);
1393 struct ds_peer *el = gatt_delayed_store_find(id, peer_addr);
1394
1395 if (bonded) {
1396 if (el == NULL) {
1397 el = gatt_delayed_store_alloc(id, peer_addr);
1398 __ASSERT(el != NULL, "Can't save CF / CCC to flash");
1399 }
1400
1401 atomic_set_bit(el->flags, flag);
1402
1403 k_work_reschedule(&gatt_delayed_store.work,
1404 K_MSEC(CONFIG_BT_SETTINGS_DELAYED_STORE_MS));
1405 }
1406 }
1407
delayed_store(struct k_work * work)1408 static void delayed_store(struct k_work *work)
1409 {
1410 struct ds_peer *el;
1411 struct k_work_delayable *dwork = k_work_delayable_from_work(work);
1412 struct gatt_delayed_store *store =
1413 CONTAINER_OF(dwork, struct gatt_delayed_store, work);
1414
1415 for (size_t i = 0; i < ARRAY_SIZE(gatt_delayed_store.peer_list); i++) {
1416 el = &store->peer_list[i];
1417
1418 gatt_store_ccc_cf(el->id, &el->peer);
1419 }
1420 }
1421 #endif /* CONFIG_BT_SETTINGS_DELAYED_STORE */
1422
gatt_store_ccc_cf(uint8_t id,const bt_addr_le_t * peer_addr)1423 static void gatt_store_ccc_cf(uint8_t id, const bt_addr_le_t *peer_addr)
1424 {
1425 struct ds_peer *el = gatt_delayed_store_find(id, peer_addr);
1426
1427 if (bt_addr_le_is_bonded(id, peer_addr)) {
1428 if (!IS_ENABLED(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) ||
1429 (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) && el &&
1430 atomic_test_and_clear_bit(el->flags, DELAYED_STORE_CCC))) {
1431 bt_gatt_store_ccc(id, peer_addr);
1432 }
1433
1434 if (!IS_ENABLED(CONFIG_BT_SETTINGS_CF_STORE_ON_WRITE) ||
1435 (IS_ENABLED(CONFIG_BT_SETTINGS_CF_STORE_ON_WRITE) && el &&
1436 atomic_test_and_clear_bit(el->flags, DELAYED_STORE_CF))) {
1437 bt_gatt_store_cf(id, peer_addr);
1438 }
1439
1440 if (el && atomic_get(el->flags) == 0) {
1441 gatt_delayed_store_free(el);
1442 }
1443 }
1444 }
1445
bt_gatt_service_init(void)1446 static void bt_gatt_service_init(void)
1447 {
1448 if (atomic_test_and_set_bit(gatt_flags, GATT_SERVICE_INITIALIZED)) {
1449 return;
1450 }
1451
1452 STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc) {
1453 last_static_handle += svc->attr_count;
1454 }
1455 }
1456
bt_gatt_init(void)1457 void bt_gatt_init(void)
1458 {
1459 if (atomic_test_and_set_bit(gatt_flags, GATT_INITIALIZED)) {
1460 return;
1461 }
1462
1463 bt_gatt_service_init();
1464
1465 #if defined(CONFIG_BT_GATT_CACHING)
1466 k_work_init_delayable(&db_hash.work, db_hash_process);
1467
1468 /* Submit work to Generate initial hash as there could be static
1469 * services already in the database.
1470 */
1471 if (IS_ENABLED(CONFIG_BT_LONG_WQ)) {
1472 bt_long_wq_schedule(&db_hash.work, DB_HASH_TIMEOUT);
1473 } else {
1474 k_work_schedule(&db_hash.work, DB_HASH_TIMEOUT);
1475 }
1476 #endif /* CONFIG_BT_GATT_CACHING */
1477
1478 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
1479 k_work_init_delayable(&gatt_sc.work, sc_process);
1480 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1481 /* Make sure to not send SC indications until SC
1482 * settings are loaded
1483 */
1484 atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING);
1485 }
1486 #endif /* defined(CONFIG_BT_GATT_SERVICE_CHANGED) */
1487
1488 #if defined(CONFIG_BT_SETTINGS_DELAYED_STORE)
1489 k_work_init_delayable(&gatt_delayed_store.work, delayed_store);
1490 #endif
1491
1492 #if defined(CONFIG_BT_SETTINGS) && defined(CONFIG_BT_SMP)
1493 static struct bt_conn_auth_info_cb gatt_conn_auth_info_cb = {
1494 .pairing_complete = bt_gatt_pairing_complete,
1495 };
1496
1497 /* Register the gatt module for authentication info callbacks so it can
1498 * be notified when pairing has completed. This is used to enable CCC
1499 * and CF storage on pairing complete.
1500 */
1501 bt_conn_auth_info_cb_register(&gatt_conn_auth_info_cb);
1502
1503 static struct bt_conn_cb gatt_conn_cb = {
1504 .identity_resolved = bt_gatt_identity_resolved,
1505 };
1506
1507 /* Also update the address of CCC or CF writes that happened before the
1508 * identity resolution. Note that to increase security in the future, we
1509 * might want to explicitly not do this and treat a bonded device as a
1510 * brand-new peer.
1511 */
1512 bt_conn_cb_register(&gatt_conn_cb);
1513 #endif /* CONFIG_BT_SETTINGS && CONFIG_BT_SMP */
1514 }
1515
sc_indicate(uint16_t start,uint16_t end)1516 static void sc_indicate(uint16_t start, uint16_t end)
1517 {
1518 #if defined(CONFIG_BT_GATT_DYNAMIC_DB) || \
1519 (defined(CONFIG_BT_GATT_CACHING) && defined(CONFIG_BT_SETTINGS))
1520 LOG_DBG("start 0x%04x end 0x%04x", start, end);
1521
1522 if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
1523 gatt_sc.start = start;
1524 gatt_sc.end = end;
1525 goto submit;
1526 }
1527
1528 if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) {
1529 return;
1530 }
1531
1532 submit:
1533 if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) {
1534 LOG_DBG("indicate pending, waiting until complete...");
1535 return;
1536 }
1537
1538 /* Reschedule since the range has changed */
1539 sc_work_submit(SC_TIMEOUT);
1540 #endif /* BT_GATT_DYNAMIC_DB || (BT_GATT_CACHING && BT_SETTINGS) */
1541 }
1542
bt_gatt_cb_register(struct bt_gatt_cb * cb)1543 void bt_gatt_cb_register(struct bt_gatt_cb *cb)
1544 {
1545 sys_slist_append(&callback_list, &cb->node);
1546 }
1547
1548 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
db_changed(void)1549 static void db_changed(void)
1550 {
1551 #if defined(CONFIG_BT_GATT_CACHING)
1552 struct bt_conn *conn;
1553 int i;
1554
1555 atomic_clear_bit(gatt_sc.flags, DB_HASH_VALID);
1556
1557 if (IS_ENABLED(CONFIG_BT_LONG_WQ)) {
1558 bt_long_wq_reschedule(&db_hash.work, DB_HASH_TIMEOUT);
1559 } else {
1560 k_work_reschedule(&db_hash.work, DB_HASH_TIMEOUT);
1561 }
1562
1563 for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
1564 struct gatt_cf_cfg *cfg = &cf_cfg[i];
1565
1566 if (bt_addr_le_eq(&cfg->peer, BT_ADDR_LE_ANY)) {
1567 continue;
1568 }
1569
1570 if (CF_ROBUST_CACHING(cfg)) {
1571 /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching
1572 *... the database changes again before the client
1573 * becomes change-aware in which case the error response
1574 * shall be sent again.
1575 */
1576 conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, &cfg->peer);
1577 if (conn) {
1578 bt_att_clear_out_of_sync_sent(conn);
1579 bt_conn_unref(conn);
1580 }
1581
1582 atomic_clear_bit(cfg->flags, CF_DB_HASH_READ);
1583 set_change_aware(cfg, false);
1584 }
1585 }
1586 #endif
1587 }
1588
gatt_unregister_ccc(struct _bt_gatt_ccc * ccc)1589 static void gatt_unregister_ccc(struct _bt_gatt_ccc *ccc)
1590 {
1591 ccc->value = 0;
1592
1593 for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
1594 struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
1595
1596 if (!bt_addr_le_eq(&cfg->peer, BT_ADDR_LE_ANY)) {
1597 struct bt_conn *conn;
1598 bool store = true;
1599
1600 conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
1601 if (conn) {
1602 if (conn->state == BT_CONN_CONNECTED) {
1603 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
1604 gatt_delayed_store_enqueue(conn->id,
1605 &conn->le.dst,
1606 DELAYED_STORE_CCC);
1607 #endif
1608 store = false;
1609 }
1610
1611 bt_conn_unref(conn);
1612 }
1613
1614 if (IS_ENABLED(CONFIG_BT_SETTINGS) && store &&
1615 bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
1616 bt_gatt_store_ccc(cfg->id, &cfg->peer);
1617 }
1618
1619 clear_ccc_cfg(cfg);
1620 }
1621 }
1622 }
1623
gatt_unregister(struct bt_gatt_service * svc)1624 static int gatt_unregister(struct bt_gatt_service *svc)
1625 {
1626 if (!sys_slist_find_and_remove(&db, &svc->node)) {
1627 return -ENOENT;
1628 }
1629
1630 for (uint16_t i = 0; i < svc->attr_count; i++) {
1631 struct bt_gatt_attr *attr = &svc->attrs[i];
1632
1633 if (attr->write == bt_gatt_attr_write_ccc) {
1634 gatt_unregister_ccc(attr->user_data);
1635 }
1636 }
1637
1638 return 0;
1639 }
1640
bt_gatt_service_register(struct bt_gatt_service * svc)1641 int bt_gatt_service_register(struct bt_gatt_service *svc)
1642 {
1643 int err;
1644
1645 __ASSERT(svc, "invalid parameters\n");
1646 __ASSERT(svc->attrs, "invalid parameters\n");
1647 __ASSERT(svc->attr_count, "invalid parameters\n");
1648
1649 if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
1650 atomic_test_bit(gatt_flags, GATT_INITIALIZED) &&
1651 !atomic_test_bit(gatt_sc.flags, SC_LOAD)) {
1652 LOG_ERR("Can't register service after init and before settings are loaded.");
1653 return -EINVAL;
1654 }
1655
1656 /* Init GATT core services */
1657 bt_gatt_service_init();
1658
1659 /* Do no allow to register mandatory services twice */
1660 if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) ||
1661 !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) {
1662 return -EALREADY;
1663 }
1664
1665 k_sched_lock();
1666
1667 err = gatt_register(svc);
1668 if (err < 0) {
1669 k_sched_unlock();
1670 return err;
1671 }
1672
1673 /* Don't submit any work until the stack is initialized */
1674 if (!atomic_test_bit(gatt_flags, GATT_INITIALIZED)) {
1675 k_sched_unlock();
1676 return 0;
1677 }
1678
1679 sc_indicate(svc->attrs[0].handle,
1680 svc->attrs[svc->attr_count - 1].handle);
1681
1682 db_changed();
1683
1684 k_sched_unlock();
1685
1686 return 0;
1687 }
1688
bt_gatt_service_unregister(struct bt_gatt_service * svc)1689 int bt_gatt_service_unregister(struct bt_gatt_service *svc)
1690 {
1691 int err;
1692
1693 __ASSERT(svc, "invalid parameters\n");
1694
1695 k_sched_lock();
1696
1697 err = gatt_unregister(svc);
1698 if (err) {
1699 k_sched_unlock();
1700 return err;
1701 }
1702
1703 /* Don't submit any work until the stack is initialized */
1704 if (!atomic_test_bit(gatt_flags, GATT_INITIALIZED)) {
1705 k_sched_unlock();
1706 return 0;
1707 }
1708
1709 sc_indicate(svc->attrs[0].handle,
1710 svc->attrs[svc->attr_count - 1].handle);
1711
1712 db_changed();
1713
1714 k_sched_unlock();
1715
1716 return 0;
1717 }
1718
bt_gatt_service_is_registered(const struct bt_gatt_service * svc)1719 bool bt_gatt_service_is_registered(const struct bt_gatt_service *svc)
1720 {
1721 bool registered = false;
1722 sys_snode_t *node;
1723
1724 k_sched_lock();
1725 SYS_SLIST_FOR_EACH_NODE(&db, node) {
1726 if (&svc->node == node) {
1727 registered = true;
1728 break;
1729 }
1730 }
1731
1732 k_sched_unlock();
1733
1734 return registered;
1735 }
1736 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
1737
bt_gatt_attr_read(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t buf_len,uint16_t offset,const void * value,uint16_t value_len)1738 ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
1739 void *buf, uint16_t buf_len, uint16_t offset,
1740 const void *value, uint16_t value_len)
1741 {
1742 uint16_t len;
1743
1744 if (offset > value_len) {
1745 return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
1746 }
1747
1748 len = MIN(buf_len, value_len - offset);
1749
1750 LOG_DBG("handle 0x%04x offset %u length %u", attr->handle, offset, len);
1751
1752 memcpy(buf, (uint8_t *)value + offset, len);
1753
1754 return len;
1755 }
1756
bt_gatt_attr_read_service(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)1757 ssize_t bt_gatt_attr_read_service(struct bt_conn *conn,
1758 const struct bt_gatt_attr *attr,
1759 void *buf, uint16_t len, uint16_t offset)
1760 {
1761 const struct bt_uuid *uuid = attr->user_data;
1762
1763 if (uuid->type == BT_UUID_TYPE_16) {
1764 uint16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
1765
1766 return bt_gatt_attr_read(conn, attr, buf, len, offset,
1767 &uuid16, 2);
1768 }
1769
1770 return bt_gatt_attr_read(conn, attr, buf, len, offset,
1771 BT_UUID_128(uuid)->val, 16);
1772 }
1773
1774 struct gatt_incl {
1775 uint16_t start_handle;
1776 uint16_t end_handle;
1777 uint16_t uuid16;
1778 } __packed;
1779
get_service_handles(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)1780 static uint8_t get_service_handles(const struct bt_gatt_attr *attr,
1781 uint16_t handle, void *user_data)
1782 {
1783 struct gatt_incl *include = user_data;
1784
1785 /* Stop if attribute is a service */
1786 if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) ||
1787 !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
1788 return BT_GATT_ITER_STOP;
1789 }
1790
1791 include->end_handle = sys_cpu_to_le16(handle);
1792
1793 return BT_GATT_ITER_CONTINUE;
1794 }
1795
bt_gatt_attr_get_handle(const struct bt_gatt_attr * attr)1796 uint16_t bt_gatt_attr_get_handle(const struct bt_gatt_attr *attr)
1797 {
1798 uint16_t handle = 1;
1799
1800 if (!attr) {
1801 return 0;
1802 }
1803
1804 if (attr->handle) {
1805 return attr->handle;
1806 }
1807
1808 STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) {
1809 /* Skip ahead if start is not within service attributes array */
1810 if ((attr < &static_svc->attrs[0]) ||
1811 (attr > &static_svc->attrs[static_svc->attr_count - 1])) {
1812 handle += static_svc->attr_count;
1813 continue;
1814 }
1815
1816 for (size_t i = 0; i < static_svc->attr_count; i++, handle++) {
1817 if (attr == &static_svc->attrs[i]) {
1818 return handle;
1819 }
1820 }
1821 }
1822
1823 return 0;
1824 }
1825
bt_gatt_attr_read_included(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)1826 ssize_t bt_gatt_attr_read_included(struct bt_conn *conn,
1827 const struct bt_gatt_attr *attr,
1828 void *buf, uint16_t len, uint16_t offset)
1829 {
1830 struct bt_gatt_attr *incl = attr->user_data;
1831 uint16_t handle = bt_gatt_attr_get_handle(incl);
1832 struct bt_uuid *uuid = incl->user_data;
1833 struct gatt_incl pdu;
1834 uint8_t value_len;
1835
1836 /* first attr points to the start handle */
1837 pdu.start_handle = sys_cpu_to_le16(handle);
1838 value_len = sizeof(pdu.start_handle) + sizeof(pdu.end_handle);
1839
1840 /*
1841 * Core 4.2, Vol 3, Part G, 3.2,
1842 * The Service UUID shall only be present when the UUID is a
1843 * 16-bit Bluetooth UUID.
1844 */
1845 if (uuid->type == BT_UUID_TYPE_16) {
1846 pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
1847 value_len += sizeof(pdu.uuid16);
1848 }
1849
1850 /* Lookup for service end handle */
1851 bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu);
1852
1853 return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
1854 }
1855
1856 struct gatt_chrc {
1857 uint8_t properties;
1858 uint16_t value_handle;
1859 union {
1860 uint16_t uuid16;
1861 uint8_t uuid[16];
1862 };
1863 } __packed;
1864
bt_gatt_attr_value_handle(const struct bt_gatt_attr * attr)1865 uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr)
1866 {
1867 uint16_t handle = 0;
1868
1869 if (attr != NULL && bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC) == 0) {
1870 struct bt_gatt_chrc *chrc = attr->user_data;
1871
1872 handle = chrc->value_handle;
1873 if (handle == 0) {
1874 /* Fall back to Zephyr value handle policy */
1875 handle = bt_gatt_attr_get_handle(attr) + 1U;
1876 }
1877 }
1878
1879 return handle;
1880 }
1881
bt_gatt_attr_read_chrc(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)1882 ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn,
1883 const struct bt_gatt_attr *attr, void *buf,
1884 uint16_t len, uint16_t offset)
1885 {
1886 struct bt_gatt_chrc *chrc = attr->user_data;
1887 struct gatt_chrc pdu;
1888 uint8_t value_len;
1889
1890 pdu.properties = chrc->properties;
1891 /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534:
1892 * 3.3.2 Characteristic Value Declaration
1893 * The Characteristic Value declaration contains the value of the
1894 * characteristic. It is the first Attribute after the characteristic
1895 * declaration. All characteristic definitions shall have a
1896 * Characteristic Value declaration.
1897 */
1898 pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr));
1899
1900 value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle);
1901
1902 if (chrc->uuid->type == BT_UUID_TYPE_16) {
1903 pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val);
1904 value_len += 2U;
1905 } else {
1906 memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16);
1907 value_len += 16U;
1908 }
1909
1910 return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
1911 }
1912
gatt_foreach_iter(const struct bt_gatt_attr * attr,uint16_t handle,uint16_t start_handle,uint16_t end_handle,const struct bt_uuid * uuid,const void * attr_data,uint16_t * num_matches,bt_gatt_attr_func_t func,void * user_data)1913 static uint8_t gatt_foreach_iter(const struct bt_gatt_attr *attr,
1914 uint16_t handle, uint16_t start_handle,
1915 uint16_t end_handle,
1916 const struct bt_uuid *uuid,
1917 const void *attr_data, uint16_t *num_matches,
1918 bt_gatt_attr_func_t func, void *user_data)
1919 {
1920 uint8_t result;
1921
1922 /* Stop if over the requested range */
1923 if (handle > end_handle) {
1924 return BT_GATT_ITER_STOP;
1925 }
1926
1927 /* Check if attribute handle is within range */
1928 if (handle < start_handle) {
1929 return BT_GATT_ITER_CONTINUE;
1930 }
1931
1932 /* Match attribute UUID if set */
1933 if (uuid && bt_uuid_cmp(uuid, attr->uuid)) {
1934 return BT_GATT_ITER_CONTINUE;
1935 }
1936
1937 /* Match attribute user_data if set */
1938 if (attr_data && attr_data != attr->user_data) {
1939 return BT_GATT_ITER_CONTINUE;
1940 }
1941
1942 *num_matches -= 1;
1943
1944 result = func(attr, handle, user_data);
1945
1946 if (!*num_matches) {
1947 return BT_GATT_ITER_STOP;
1948 }
1949
1950 return result;
1951 }
1952
foreach_attr_type_dyndb(uint16_t start_handle,uint16_t end_handle,const struct bt_uuid * uuid,const void * attr_data,uint16_t num_matches,bt_gatt_attr_func_t func,void * user_data)1953 static void foreach_attr_type_dyndb(uint16_t start_handle, uint16_t end_handle,
1954 const struct bt_uuid *uuid,
1955 const void *attr_data, uint16_t num_matches,
1956 bt_gatt_attr_func_t func, void *user_data)
1957 {
1958 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
1959 size_t i;
1960 struct bt_gatt_service *svc;
1961
1962 SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node) {
1963 struct bt_gatt_service *next;
1964
1965 next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node);
1966 if (next) {
1967 /* Skip ahead if start is not within service handles */
1968 if (next->attrs[0].handle <= start_handle) {
1969 continue;
1970 }
1971 }
1972
1973 for (i = 0; i < svc->attr_count; i++) {
1974 struct bt_gatt_attr *attr = &svc->attrs[i];
1975
1976 if (gatt_foreach_iter(attr, attr->handle,
1977 start_handle,
1978 end_handle,
1979 uuid, attr_data,
1980 &num_matches,
1981 func, user_data) ==
1982 BT_GATT_ITER_STOP) {
1983 return;
1984 }
1985 }
1986 }
1987 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
1988 }
1989
bt_gatt_foreach_attr_type(uint16_t start_handle,uint16_t end_handle,const struct bt_uuid * uuid,const void * attr_data,uint16_t num_matches,bt_gatt_attr_func_t func,void * user_data)1990 void bt_gatt_foreach_attr_type(uint16_t start_handle, uint16_t end_handle,
1991 const struct bt_uuid *uuid,
1992 const void *attr_data, uint16_t num_matches,
1993 bt_gatt_attr_func_t func, void *user_data)
1994 {
1995 size_t i;
1996
1997 if (!num_matches) {
1998 num_matches = UINT16_MAX;
1999 }
2000
2001 if (start_handle <= last_static_handle) {
2002 uint16_t handle = 1;
2003
2004 STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) {
2005 /* Skip ahead if start is not within service handles */
2006 if (handle + static_svc->attr_count < start_handle) {
2007 handle += static_svc->attr_count;
2008 continue;
2009 }
2010
2011 for (i = 0; i < static_svc->attr_count; i++, handle++) {
2012 if (gatt_foreach_iter(&static_svc->attrs[i],
2013 handle, start_handle,
2014 end_handle, uuid,
2015 attr_data, &num_matches,
2016 func, user_data) ==
2017 BT_GATT_ITER_STOP) {
2018 return;
2019 }
2020 }
2021 }
2022 }
2023
2024 /* Iterate over dynamic db */
2025 foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data,
2026 num_matches, func, user_data);
2027 }
2028
find_next(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)2029 static uint8_t find_next(const struct bt_gatt_attr *attr, uint16_t handle,
2030 void *user_data)
2031 {
2032 struct bt_gatt_attr **next = user_data;
2033
2034 *next = (struct bt_gatt_attr *)attr;
2035
2036 return BT_GATT_ITER_STOP;
2037 }
2038
bt_gatt_attr_next(const struct bt_gatt_attr * attr)2039 struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr)
2040 {
2041 struct bt_gatt_attr *next = NULL;
2042 uint16_t handle = bt_gatt_attr_get_handle(attr);
2043
2044 bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next);
2045
2046 return next;
2047 }
2048
find_ccc_cfg(const struct bt_conn * conn,struct _bt_gatt_ccc * ccc)2049 static struct bt_gatt_ccc_cfg *find_ccc_cfg(const struct bt_conn *conn,
2050 struct _bt_gatt_ccc *ccc)
2051 {
2052 for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
2053 struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
2054
2055 if (conn) {
2056 if (bt_conn_is_peer_addr_le(conn, cfg->id,
2057 &cfg->peer)) {
2058 return cfg;
2059 }
2060 } else if (bt_addr_le_eq(&cfg->peer, BT_ADDR_LE_ANY)) {
2061 return cfg;
2062 }
2063 }
2064
2065 return NULL;
2066 }
2067
bt_gatt_attr_read_ccc(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)2068 ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn,
2069 const struct bt_gatt_attr *attr, void *buf,
2070 uint16_t len, uint16_t offset)
2071 {
2072 struct _bt_gatt_ccc *ccc = attr->user_data;
2073 const struct bt_gatt_ccc_cfg *cfg;
2074 uint16_t value;
2075
2076 cfg = find_ccc_cfg(conn, ccc);
2077 if (cfg) {
2078 value = sys_cpu_to_le16(cfg->value);
2079 } else {
2080 /* Default to disable if there is no cfg for the peer */
2081 value = 0x0000;
2082 }
2083
2084 return bt_gatt_attr_read(conn, attr, buf, len, offset, &value,
2085 sizeof(value));
2086 }
2087
gatt_ccc_changed(const struct bt_gatt_attr * attr,struct _bt_gatt_ccc * ccc)2088 static void gatt_ccc_changed(const struct bt_gatt_attr *attr,
2089 struct _bt_gatt_ccc *ccc)
2090 {
2091 int i;
2092 uint16_t value = 0x0000;
2093
2094 for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
2095 if (ccc->cfg[i].value > value) {
2096 value = ccc->cfg[i].value;
2097 }
2098 }
2099
2100 LOG_DBG("ccc %p value 0x%04x", ccc, value);
2101
2102 if (value != ccc->value) {
2103 ccc->value = value;
2104 if (ccc->cfg_changed) {
2105 ccc->cfg_changed(attr, value);
2106 }
2107 }
2108 }
2109
bt_gatt_attr_write_ccc(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * buf,uint16_t len,uint16_t offset,uint8_t flags)2110 ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn,
2111 const struct bt_gatt_attr *attr, const void *buf,
2112 uint16_t len, uint16_t offset, uint8_t flags)
2113 {
2114 struct _bt_gatt_ccc *ccc = attr->user_data;
2115 struct bt_gatt_ccc_cfg *cfg;
2116 bool value_changed;
2117 uint16_t value;
2118
2119 if (offset) {
2120 return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
2121 }
2122
2123 if (!len || len > sizeof(uint16_t)) {
2124 return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2125 }
2126
2127 if (len < sizeof(uint16_t)) {
2128 value = *(uint8_t *)buf;
2129 } else {
2130 value = sys_get_le16(buf);
2131 }
2132
2133 cfg = find_ccc_cfg(conn, ccc);
2134 if (!cfg) {
2135 /* If there's no existing entry, but the new value is zero,
2136 * we don't need to do anything, since a disabled CCC is
2137 * behaviorally the same as no written CCC.
2138 */
2139 if (!value) {
2140 return len;
2141 }
2142
2143 cfg = find_ccc_cfg(NULL, ccc);
2144 if (!cfg) {
2145 LOG_WRN("No space to store CCC cfg");
2146 return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
2147 }
2148
2149 bt_addr_le_copy(&cfg->peer, &conn->le.dst);
2150 cfg->id = conn->id;
2151 }
2152
2153 /* Confirm write if cfg is managed by application */
2154 if (ccc->cfg_write) {
2155 ssize_t write = ccc->cfg_write(conn, attr, value);
2156
2157 if (write < 0) {
2158 return write;
2159 }
2160
2161 /* Accept size=1 for backwards compatibility */
2162 if (write != sizeof(value) && write != 1) {
2163 return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY);
2164 }
2165 }
2166
2167 value_changed = cfg->value != value;
2168 cfg->value = value;
2169
2170 LOG_DBG("handle 0x%04x value %u", attr->handle, cfg->value);
2171
2172 /* Update cfg if don't match */
2173 if (cfg->value != ccc->value) {
2174 gatt_ccc_changed(attr, ccc);
2175 }
2176
2177 if (value_changed) {
2178 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
2179 /* Enqueue CCC store if value has changed for the connection */
2180 gatt_delayed_store_enqueue(conn->id, &conn->le.dst, DELAYED_STORE_CCC);
2181 #endif
2182 }
2183
2184 /* Disabled CCC is the same as no configured CCC, so clear the entry */
2185 if (!value) {
2186 clear_ccc_cfg(cfg);
2187 }
2188
2189 return len;
2190 }
2191
bt_gatt_attr_read_cep(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)2192 ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn,
2193 const struct bt_gatt_attr *attr, void *buf,
2194 uint16_t len, uint16_t offset)
2195 {
2196 const struct bt_gatt_cep *value = attr->user_data;
2197 uint16_t props = sys_cpu_to_le16(value->properties);
2198
2199 return bt_gatt_attr_read(conn, attr, buf, len, offset, &props,
2200 sizeof(props));
2201 }
2202
bt_gatt_attr_read_cud(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)2203 ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn,
2204 const struct bt_gatt_attr *attr, void *buf,
2205 uint16_t len, uint16_t offset)
2206 {
2207 const char *value = attr->user_data;
2208
2209 return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
2210 strlen(value));
2211 }
2212
2213 struct gatt_cpf {
2214 uint8_t format;
2215 int8_t exponent;
2216 uint16_t unit;
2217 uint8_t name_space;
2218 uint16_t description;
2219 } __packed;
2220
bt_gatt_attr_read_cpf(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)2221 ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn,
2222 const struct bt_gatt_attr *attr, void *buf,
2223 uint16_t len, uint16_t offset)
2224 {
2225 const struct bt_gatt_cpf *cpf = attr->user_data;
2226 struct gatt_cpf value;
2227
2228 value.format = cpf->format;
2229 value.exponent = cpf->exponent;
2230 value.unit = sys_cpu_to_le16(cpf->unit);
2231 value.name_space = cpf->name_space;
2232 value.description = sys_cpu_to_le16(cpf->description);
2233
2234 return bt_gatt_attr_read(conn, attr, buf, len, offset, &value,
2235 sizeof(value));
2236 }
2237
2238 struct notify_data {
2239 const struct bt_gatt_attr *attr;
2240 uint16_t handle;
2241 int err;
2242 uint16_t type;
2243 union {
2244 struct bt_gatt_notify_params *nfy_params;
2245 struct bt_gatt_indicate_params *ind_params;
2246 };
2247 };
2248
2249 #if defined(CONFIG_BT_GATT_NOTIFY_MULTIPLE)
2250
2251 static struct net_buf *nfy_mult[CONFIG_BT_MAX_CONN];
2252
gatt_notify_mult_send(struct bt_conn * conn,struct net_buf * buf)2253 static int gatt_notify_mult_send(struct bt_conn *conn, struct net_buf *buf)
2254 {
2255 int ret;
2256 uint8_t *pdu = buf->data;
2257 /* PDU structure is [Opcode (1)] [Handle (2)] [Length (2)] [Value (Length)] */
2258 uint16_t first_attr_len = sys_get_le16(&pdu[3]);
2259
2260 /* Convert to ATT_HANDLE_VALUE_NTF if containing a single handle. */
2261 if (buf->len ==
2262 (1 + sizeof(struct bt_att_notify_mult) + first_attr_len)) {
2263 /* Store attr handle */
2264 uint16_t handle = sys_get_le16(&pdu[1]);
2265
2266 /* Remove the ATT_MULTIPLE_HANDLE_VALUE_NTF opcode,
2267 * attribute handle and length
2268 */
2269 (void)net_buf_pull(buf, 1 + sizeof(struct bt_att_notify_mult));
2270
2271 /* Add back an ATT_HANDLE_VALUE_NTF opcode and attr handle */
2272 /* PDU structure is now [Opcode (1)] [Handle (1)] [Value] */
2273 net_buf_push_le16(buf, handle);
2274 net_buf_push_u8(buf, BT_ATT_OP_NOTIFY);
2275 LOG_DBG("Converted BT_ATT_OP_NOTIFY_MULT with single attr to BT_ATT_OP_NOTIFY");
2276 }
2277
2278 ret = bt_att_send(conn, buf);
2279 if (ret < 0) {
2280 net_buf_unref(buf);
2281 }
2282
2283 return ret;
2284 }
2285
notify_mult_process(struct k_work * work)2286 static void notify_mult_process(struct k_work *work)
2287 {
2288 int i;
2289
2290 /* Send to any connection with an allocated buffer */
2291 for (i = 0; i < ARRAY_SIZE(nfy_mult); i++) {
2292 struct net_buf **buf = &nfy_mult[i];
2293
2294 if (*buf) {
2295 struct bt_conn *conn = bt_conn_lookup_index(i);
2296
2297 gatt_notify_mult_send(conn, *buf);
2298 *buf = NULL;
2299 bt_conn_unref(conn);
2300 }
2301 }
2302 }
2303
2304 K_WORK_DELAYABLE_DEFINE(nfy_mult_work, notify_mult_process);
2305
gatt_cf_notify_multi(struct bt_conn * conn)2306 static bool gatt_cf_notify_multi(struct bt_conn *conn)
2307 {
2308 struct gatt_cf_cfg *cfg;
2309
2310 cfg = find_cf_cfg(conn);
2311 if (!cfg) {
2312 return false;
2313 }
2314
2315 return CF_NOTIFY_MULTI(cfg);
2316 }
2317
gatt_notify_flush(struct bt_conn * conn)2318 static int gatt_notify_flush(struct bt_conn *conn)
2319 {
2320 int err = 0;
2321 struct net_buf **buf = &nfy_mult[bt_conn_index(conn)];
2322
2323 if (*buf) {
2324 err = gatt_notify_mult_send(conn, *buf);
2325 *buf = NULL;
2326 }
2327
2328 return err;
2329 }
2330
cleanup_notify(struct bt_conn * conn)2331 static void cleanup_notify(struct bt_conn *conn)
2332 {
2333 struct net_buf **buf = &nfy_mult[bt_conn_index(conn)];
2334
2335 if (*buf) {
2336 net_buf_unref(*buf);
2337 *buf = NULL;
2338 }
2339 }
2340
gatt_add_nfy_to_buf(struct net_buf * buf,uint16_t handle,struct bt_gatt_notify_params * params)2341 static void gatt_add_nfy_to_buf(struct net_buf *buf,
2342 uint16_t handle,
2343 struct bt_gatt_notify_params *params)
2344 {
2345 struct bt_att_notify_mult *nfy;
2346
2347 nfy = net_buf_add(buf, sizeof(*nfy));
2348 nfy->handle = sys_cpu_to_le16(handle);
2349 nfy->len = sys_cpu_to_le16(params->len);
2350
2351 net_buf_add(buf, params->len);
2352 (void)memcpy(nfy->value, params->data, params->len);
2353 }
2354
2355 #if (CONFIG_BT_GATT_NOTIFY_MULTIPLE_FLUSH_MS != 0)
gatt_notify_mult(struct bt_conn * conn,uint16_t handle,struct bt_gatt_notify_params * params)2356 static int gatt_notify_mult(struct bt_conn *conn, uint16_t handle,
2357 struct bt_gatt_notify_params *params)
2358 {
2359 struct net_buf **buf = &nfy_mult[bt_conn_index(conn)];
2360
2361 /* Check if we can fit more data into it, in case it doesn't fit send
2362 * the existing buffer and proceed to create a new one
2363 */
2364 if (*buf && ((net_buf_tailroom(*buf) < sizeof(struct bt_att_notify_mult) + params->len) ||
2365 !bt_att_tx_meta_data_match(*buf, params->func, params->user_data,
2366 BT_ATT_CHAN_OPT(params)))) {
2367 int ret;
2368
2369 ret = gatt_notify_mult_send(conn, *buf);
2370 *buf = NULL;
2371 if (ret < 0) {
2372 return ret;
2373 }
2374 }
2375
2376 if (!*buf) {
2377 *buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY_MULT,
2378 sizeof(struct bt_att_notify_mult) + params->len);
2379 if (!*buf) {
2380 return -ENOMEM;
2381 }
2382
2383 bt_att_set_tx_meta_data(*buf, params->func, params->user_data,
2384 BT_ATT_CHAN_OPT(params));
2385 } else {
2386 /* Increment the number of handles, ensuring the notify callback
2387 * gets called once for every attribute.
2388 */
2389 bt_att_increment_tx_meta_data_attr_count(*buf, 1);
2390 }
2391
2392 LOG_DBG("handle 0x%04x len %u", handle, params->len);
2393 gatt_add_nfy_to_buf(*buf, handle, params);
2394
2395 /* Use `k_work_schedule` to keep the original deadline, instead of
2396 * re-setting the timeout whenever a new notification is appended.
2397 */
2398 k_work_schedule(&nfy_mult_work,
2399 K_MSEC(CONFIG_BT_GATT_NOTIFY_MULTIPLE_FLUSH_MS));
2400
2401 return 0;
2402 }
2403 #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE_FLUSH_MS != 0 */
2404 #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE */
2405
gatt_notify(struct bt_conn * conn,uint16_t handle,struct bt_gatt_notify_params * params)2406 static int gatt_notify(struct bt_conn *conn, uint16_t handle,
2407 struct bt_gatt_notify_params *params)
2408 {
2409 struct net_buf *buf;
2410 struct bt_att_notify *nfy;
2411
2412 #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE)
2413 /* BLUETOOTH CORE SPECIFICATION Version 5.3
2414 * Vol 3, Part G 2.5.3 (page 1479):
2415 *
2416 * Except for a Handle Value indication for the Service Changed
2417 * characteristic, the server shall not send notifications and
2418 * indications to such a client until it becomes change-aware.
2419 */
2420 if (!bt_gatt_change_aware(conn, false)) {
2421 return -EAGAIN;
2422 }
2423 #endif
2424
2425 /* Confirm that the connection has the correct level of security */
2426 if (bt_gatt_check_perm(conn, params->attr, BT_GATT_PERM_READ_ENCRYPT_MASK)) {
2427 LOG_WRN("Link is not encrypted");
2428 return -EPERM;
2429 }
2430
2431 if (IS_ENABLED(CONFIG_BT_GATT_ENFORCE_SUBSCRIPTION)) {
2432 /* Check if client has subscribed before sending notifications.
2433 * This is not really required in the Bluetooth specification,
2434 * but follows its spirit.
2435 */
2436 if (!bt_gatt_is_subscribed(conn, params->attr, BT_GATT_CCC_NOTIFY)) {
2437 LOG_WRN("Device is not subscribed to characteristic");
2438 return -EINVAL;
2439 }
2440 }
2441
2442 if (IS_ENABLED(CONFIG_BT_EATT) &&
2443 !bt_att_chan_opt_valid(conn, BT_ATT_CHAN_OPT(params))) {
2444 return -EINVAL;
2445 }
2446
2447 #if defined(CONFIG_BT_GATT_NOTIFY_MULTIPLE) && (CONFIG_BT_GATT_NOTIFY_MULTIPLE_FLUSH_MS != 0)
2448 if (gatt_cf_notify_multi(conn)) {
2449 return gatt_notify_mult(conn, handle, params);
2450 }
2451 #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE */
2452
2453 buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY,
2454 sizeof(*nfy) + params->len);
2455 if (!buf) {
2456 LOG_WRN("No buffer available to send notification");
2457 return -ENOMEM;
2458 }
2459
2460 LOG_DBG("conn %p handle 0x%04x", conn, handle);
2461
2462 nfy = net_buf_add(buf, sizeof(*nfy));
2463 nfy->handle = sys_cpu_to_le16(handle);
2464
2465 net_buf_add(buf, params->len);
2466 memcpy(nfy->value, params->data, params->len);
2467
2468 bt_att_set_tx_meta_data(buf, params->func, params->user_data, BT_ATT_CHAN_OPT(params));
2469 return bt_att_send(conn, buf);
2470 }
2471
2472 /* Converts error (negative errno) to ATT Error code */
att_err_from_int(int err)2473 static uint8_t att_err_from_int(int err)
2474 {
2475 LOG_DBG("%d", err);
2476
2477 /* ATT error codes are 1 byte values, so any value outside the range is unknown */
2478 if (!IN_RANGE(err, 0, UINT8_MAX)) {
2479 return BT_ATT_ERR_UNLIKELY;
2480 }
2481
2482 return err;
2483 }
2484
gatt_indicate_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)2485 static void gatt_indicate_rsp(struct bt_conn *conn, int err,
2486 const void *pdu, uint16_t length, void *user_data)
2487 {
2488 struct bt_gatt_indicate_params *params = user_data;
2489
2490 if (params->func) {
2491 params->func(conn, params, att_err_from_int(err));
2492 }
2493
2494 params->_ref--;
2495 if (params->destroy && (params->_ref == 0)) {
2496 params->destroy(params);
2497 }
2498 }
2499
gatt_req_alloc(bt_att_func_t func,void * params,bt_att_encode_t encode,uint8_t op,size_t len)2500 static struct bt_att_req *gatt_req_alloc(bt_att_func_t func, void *params,
2501 bt_att_encode_t encode,
2502 uint8_t op,
2503 size_t len)
2504 {
2505 struct bt_att_req *req;
2506
2507 /* Allocate new request */
2508 req = bt_att_req_alloc(BT_ATT_TIMEOUT);
2509 if (!req) {
2510 return NULL;
2511 }
2512
2513 #if defined(CONFIG_BT_SMP)
2514 req->att_op = op;
2515 req->len = len;
2516 req->encode = encode;
2517 #endif
2518 req->func = func;
2519 req->user_data = params;
2520
2521 return req;
2522 }
2523
2524 #ifdef CONFIG_BT_GATT_CLIENT
gatt_req_send(struct bt_conn * conn,bt_att_func_t func,void * params,bt_att_encode_t encode,uint8_t op,size_t len,enum bt_att_chan_opt chan_opt)2525 static int gatt_req_send(struct bt_conn *conn, bt_att_func_t func, void *params,
2526 bt_att_encode_t encode, uint8_t op, size_t len,
2527 enum bt_att_chan_opt chan_opt)
2528
2529 {
2530 struct bt_att_req *req;
2531 struct net_buf *buf;
2532 int err;
2533
2534 if (IS_ENABLED(CONFIG_BT_EATT) &&
2535 !bt_att_chan_opt_valid(conn, chan_opt)) {
2536 return -EINVAL;
2537 }
2538
2539 req = gatt_req_alloc(func, params, encode, op, len);
2540 if (!req) {
2541 return -ENOMEM;
2542 }
2543
2544 buf = bt_att_create_pdu(conn, op, len);
2545 if (!buf) {
2546 bt_att_req_free(req);
2547 return -ENOMEM;
2548 }
2549
2550 bt_att_set_tx_meta_data(buf, NULL, NULL, chan_opt);
2551
2552 req->buf = buf;
2553
2554 err = encode(buf, len, params);
2555 if (err) {
2556 bt_att_req_free(req);
2557 return err;
2558 }
2559
2560 err = bt_att_req_send(conn, req);
2561 if (err) {
2562 bt_att_req_free(req);
2563 }
2564
2565 return err;
2566 }
2567 #endif
2568
gatt_indicate(struct bt_conn * conn,uint16_t handle,struct bt_gatt_indicate_params * params)2569 static int gatt_indicate(struct bt_conn *conn, uint16_t handle,
2570 struct bt_gatt_indicate_params *params)
2571 {
2572 struct net_buf *buf;
2573 struct bt_att_indicate *ind;
2574 struct bt_att_req *req;
2575 size_t len;
2576 int err;
2577
2578 #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE)
2579 /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
2580 * Except for the Handle Value indication, the server shall not send
2581 * notifications and indications to such a client until it becomes
2582 * change-aware.
2583 */
2584 if (!(params->func && (params->func == sc_indicate_rsp ||
2585 params->func == sc_restore_rsp)) &&
2586 !bt_gatt_change_aware(conn, false)) {
2587 return -EAGAIN;
2588 }
2589 #endif
2590
2591 /* Confirm that the connection has the correct level of security */
2592 if (bt_gatt_check_perm(conn, params->attr, BT_GATT_PERM_READ_ENCRYPT_MASK)) {
2593 LOG_WRN("Link is not encrypted");
2594 return -EPERM;
2595 }
2596
2597 if (IS_ENABLED(CONFIG_BT_GATT_ENFORCE_SUBSCRIPTION)) {
2598 /* Check if client has subscribed before sending notifications.
2599 * This is not really required in the Bluetooth specification,
2600 * but follows its spirit.
2601 */
2602 if (!bt_gatt_is_subscribed(conn, params->attr, BT_GATT_CCC_INDICATE)) {
2603 LOG_WRN("Device is not subscribed to characteristic");
2604 return -EINVAL;
2605 }
2606 }
2607
2608 if (IS_ENABLED(CONFIG_BT_EATT) &&
2609 !bt_att_chan_opt_valid(conn, BT_ATT_CHAN_OPT(params))) {
2610 return -EINVAL;
2611 }
2612
2613 len = sizeof(*ind) + params->len;
2614
2615 req = gatt_req_alloc(gatt_indicate_rsp, params, NULL,
2616 BT_ATT_OP_INDICATE, len);
2617 if (!req) {
2618 return -ENOMEM;
2619 }
2620
2621 buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE, len);
2622 if (!buf) {
2623 LOG_WRN("No buffer available to send indication");
2624 bt_att_req_free(req);
2625 return -ENOMEM;
2626 }
2627
2628 bt_att_set_tx_meta_data(buf, NULL, NULL, BT_ATT_CHAN_OPT(params));
2629
2630 ind = net_buf_add(buf, sizeof(*ind));
2631 ind->handle = sys_cpu_to_le16(handle);
2632
2633 net_buf_add(buf, params->len);
2634 memcpy(ind->value, params->data, params->len);
2635
2636 LOG_DBG("conn %p handle 0x%04x", conn, handle);
2637
2638 req->buf = buf;
2639
2640 err = bt_att_req_send(conn, req);
2641 if (err) {
2642 bt_att_req_free(req);
2643 }
2644
2645 return err;
2646 }
2647
notify_cb(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)2648 static uint8_t notify_cb(const struct bt_gatt_attr *attr, uint16_t handle,
2649 void *user_data)
2650 {
2651 struct notify_data *data = user_data;
2652 struct _bt_gatt_ccc *ccc;
2653 size_t i;
2654
2655 /* Check attribute user_data must be of type struct _bt_gatt_ccc */
2656 if (attr->write != bt_gatt_attr_write_ccc) {
2657 return BT_GATT_ITER_CONTINUE;
2658 }
2659
2660 ccc = attr->user_data;
2661
2662 /* Save Service Changed data if peer is not connected */
2663 if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) {
2664 for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
2665 struct gatt_sc_cfg *cfg = &sc_cfg[i];
2666 struct bt_conn *conn;
2667
2668 if (bt_addr_le_eq(&cfg->peer, BT_ADDR_LE_ANY)) {
2669 continue;
2670 }
2671
2672 conn = bt_conn_lookup_state_le(cfg->id, &cfg->peer,
2673 BT_CONN_CONNECTED);
2674 if (!conn) {
2675 struct sc_data *sc;
2676
2677 sc = (struct sc_data *)data->ind_params->data;
2678 sc_save(cfg->id, &cfg->peer,
2679 sys_le16_to_cpu(sc->start),
2680 sys_le16_to_cpu(sc->end));
2681 continue;
2682 }
2683
2684 bt_conn_unref(conn);
2685 }
2686 }
2687
2688 /* Notify all peers configured */
2689 for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
2690 struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
2691 struct bt_conn *conn;
2692 int err;
2693
2694 /* Check if config value matches data type since consolidated
2695 * value may be for a different peer.
2696 */
2697 if (cfg->value != data->type) {
2698 continue;
2699 }
2700
2701 conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
2702 if (!conn) {
2703 continue;
2704 }
2705
2706 if (conn->state != BT_CONN_CONNECTED) {
2707 bt_conn_unref(conn);
2708 continue;
2709 }
2710
2711 /* Confirm match if cfg is managed by application */
2712 if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) {
2713 bt_conn_unref(conn);
2714 continue;
2715 }
2716
2717 /* Confirm that the connection has the correct level of security */
2718 if (bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_ENCRYPT_MASK)) {
2719 LOG_WRN("Link is not encrypted");
2720 bt_conn_unref(conn);
2721 continue;
2722 }
2723
2724 /* Use the Characteristic Value handle discovered since the
2725 * Client Characteristic Configuration descriptor may occur
2726 * in any position within the characteristic definition after
2727 * the Characteristic Value.
2728 * Only notify or indicate devices which are subscribed.
2729 */
2730 if ((data->type == BT_GATT_CCC_INDICATE) &&
2731 (cfg->value & BT_GATT_CCC_INDICATE)) {
2732 err = gatt_indicate(conn, data->handle, data->ind_params);
2733 if (err == 0) {
2734 data->ind_params->_ref++;
2735 }
2736 } else if ((data->type == BT_GATT_CCC_NOTIFY) &&
2737 (cfg->value & BT_GATT_CCC_NOTIFY)) {
2738 err = gatt_notify(conn, data->handle, data->nfy_params);
2739 } else {
2740 err = 0;
2741 }
2742
2743 bt_conn_unref(conn);
2744
2745 data->err = err;
2746
2747 if (err < 0) {
2748 return BT_GATT_ITER_STOP;
2749 }
2750 }
2751
2752 return BT_GATT_ITER_CONTINUE;
2753 }
2754
match_uuid(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)2755 static uint8_t match_uuid(const struct bt_gatt_attr *attr, uint16_t handle,
2756 void *user_data)
2757 {
2758 struct notify_data *data = user_data;
2759
2760 data->attr = attr;
2761 data->handle = handle;
2762
2763 return BT_GATT_ITER_STOP;
2764 }
2765
gatt_find_by_uuid(struct notify_data * found,const struct bt_uuid * uuid)2766 static bool gatt_find_by_uuid(struct notify_data *found,
2767 const struct bt_uuid *uuid)
2768 {
2769 found->attr = NULL;
2770
2771 bt_gatt_foreach_attr_type(found->handle, 0xffff, uuid, NULL, 1,
2772 match_uuid, found);
2773
2774 return found->attr ? true : false;
2775 }
2776
bt_gatt_find_by_uuid(const struct bt_gatt_attr * attr,uint16_t attr_count,const struct bt_uuid * uuid)2777 struct bt_gatt_attr *bt_gatt_find_by_uuid(const struct bt_gatt_attr *attr,
2778 uint16_t attr_count,
2779 const struct bt_uuid *uuid)
2780 {
2781 struct bt_gatt_attr *found = NULL;
2782 uint16_t start_handle = bt_gatt_attr_value_handle(attr);
2783 uint16_t end_handle = start_handle && attr_count ?
2784 start_handle + attr_count : 0xffff;
2785
2786 bt_gatt_foreach_attr_type(start_handle, end_handle, uuid, NULL, 1,
2787 find_next, &found);
2788
2789 return found;
2790 }
2791
bt_gatt_notify_cb(struct bt_conn * conn,struct bt_gatt_notify_params * params)2792 int bt_gatt_notify_cb(struct bt_conn *conn,
2793 struct bt_gatt_notify_params *params)
2794 {
2795 struct notify_data data;
2796
2797 __ASSERT(params, "invalid parameters\n");
2798 __ASSERT(params->attr || params->uuid, "invalid parameters\n");
2799
2800 if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2801 return -EAGAIN;
2802 }
2803
2804 if (conn && conn->state != BT_CONN_CONNECTED) {
2805 return -ENOTCONN;
2806 }
2807
2808 data.attr = params->attr;
2809 data.handle = bt_gatt_attr_get_handle(data.attr);
2810
2811 /* Lookup UUID if it was given */
2812 if (params->uuid) {
2813 if (!gatt_find_by_uuid(&data, params->uuid)) {
2814 return -ENOENT;
2815 }
2816
2817 params->attr = data.attr;
2818 } else {
2819 if (!data.handle) {
2820 return -ENOENT;
2821 }
2822 }
2823
2824 /* Check if attribute is a characteristic then adjust the handle */
2825 if (!bt_uuid_cmp(data.attr->uuid, BT_UUID_GATT_CHRC)) {
2826 struct bt_gatt_chrc *chrc = data.attr->user_data;
2827
2828 if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) {
2829 return -EINVAL;
2830 }
2831
2832 data.handle = bt_gatt_attr_value_handle(data.attr);
2833 }
2834
2835 if (conn) {
2836 return gatt_notify(conn, data.handle, params);
2837 }
2838
2839 data.err = -ENOTCONN;
2840 data.type = BT_GATT_CCC_NOTIFY;
2841 data.nfy_params = params;
2842
2843 bt_gatt_foreach_attr_type(data.handle, 0xffff, BT_UUID_GATT_CCC, NULL,
2844 1, notify_cb, &data);
2845
2846 return data.err;
2847 }
2848
2849 #if defined(CONFIG_BT_GATT_NOTIFY_MULTIPLE)
gatt_notify_multiple_verify_args(struct bt_conn * conn,struct bt_gatt_notify_params params[],uint16_t num_params)2850 static int gatt_notify_multiple_verify_args(struct bt_conn *conn,
2851 struct bt_gatt_notify_params params[],
2852 uint16_t num_params)
2853 {
2854 __ASSERT(params, "invalid parameters\n");
2855 __ASSERT(params->attr, "invalid parameters\n");
2856
2857 CHECKIF(num_params < 2) {
2858 /* Use the standard notification API when sending only one
2859 * notification.
2860 */
2861 return -EINVAL;
2862 }
2863
2864 CHECKIF(conn == NULL) {
2865 /* Use the standard notification API to send to all connected
2866 * peers.
2867 */
2868 return -EINVAL;
2869 }
2870
2871 if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2872 return -EAGAIN;
2873 }
2874
2875 if (conn->state != BT_CONN_CONNECTED) {
2876 return -ENOTCONN;
2877 }
2878
2879 #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE)
2880 /* BLUETOOTH CORE SPECIFICATION Version 5.3
2881 * Vol 3, Part G 2.5.3 (page 1479):
2882 *
2883 * Except for a Handle Value indication for the Service Changed
2884 * characteristic, the server shall not send notifications and
2885 * indications to such a client until it becomes change-aware.
2886 */
2887 if (!bt_gatt_change_aware(conn, false)) {
2888 return -EAGAIN;
2889 }
2890 #endif
2891
2892 /* This API guarantees an ATT_MULTIPLE_HANDLE_VALUE_NTF over the air. */
2893 if (!gatt_cf_notify_multi(conn)) {
2894 return -EOPNOTSUPP;
2895 }
2896
2897 return 0;
2898 }
2899
gatt_notify_multiple_verify_params(struct bt_conn * conn,struct bt_gatt_notify_params params[],uint16_t num_params,size_t * total_len)2900 static int gatt_notify_multiple_verify_params(struct bt_conn *conn,
2901 struct bt_gatt_notify_params params[],
2902 uint16_t num_params, size_t *total_len)
2903 {
2904 for (uint16_t i = 0; i < num_params; i++) {
2905 /* Compute the total data length. */
2906 *total_len += params[i].len;
2907
2908 /* Confirm that the connection has the correct level of security. */
2909 if (bt_gatt_check_perm(conn, params[i].attr,
2910 BT_GATT_PERM_READ_ENCRYPT |
2911 BT_GATT_PERM_READ_AUTHEN)) {
2912 LOG_WRN("Link is not encrypted");
2913 return -EPERM;
2914 }
2915
2916 /* The current implementation requires the same callbacks and
2917 * user_data.
2918 */
2919 if ((params[0].func != params[i].func) ||
2920 (params[0].user_data != params[i].user_data)) {
2921 return -EINVAL;
2922 }
2923
2924 /* This API doesn't support passing UUIDs. */
2925 if (params[i].uuid) {
2926 return -EINVAL;
2927 }
2928
2929 /* Check if the supplied handle is invalid. */
2930 if (!bt_gatt_attr_get_handle(params[i].attr)) {
2931 return -EINVAL;
2932 }
2933
2934 /* Check if the characteristic is subscribed. */
2935 if (IS_ENABLED(CONFIG_BT_GATT_ENFORCE_SUBSCRIPTION) &&
2936 !bt_gatt_is_subscribed(conn, params[i].attr,
2937 BT_GATT_CCC_NOTIFY)) {
2938 LOG_WRN("Device is not subscribed to characteristic");
2939 return -EINVAL;
2940 }
2941 }
2942
2943 /* PDU length is specified with a 16-bit value. */
2944 if (*total_len > UINT16_MAX) {
2945 return -ERANGE;
2946 }
2947
2948 /* Check there is a bearer with a high enough MTU. */
2949 if (bt_att_get_mtu(conn) <
2950 (sizeof(struct bt_att_notify_mult) + *total_len)) {
2951 return -ERANGE;
2952 }
2953
2954 return 0;
2955 }
2956
bt_gatt_notify_multiple(struct bt_conn * conn,uint16_t num_params,struct bt_gatt_notify_params params[])2957 int bt_gatt_notify_multiple(struct bt_conn *conn,
2958 uint16_t num_params,
2959 struct bt_gatt_notify_params params[])
2960 {
2961 int err;
2962 size_t total_len = 0;
2963 struct net_buf *buf;
2964
2965 /* Validate arguments, connection state and feature support. */
2966 err = gatt_notify_multiple_verify_args(conn, params, num_params);
2967 if (err) {
2968 return err;
2969 }
2970
2971 /* Validate all the attributes that we want to notify.
2972 * Also gets us the total length of the PDU as a side-effect.
2973 */
2974 err = gatt_notify_multiple_verify_params(conn, params, num_params, &total_len);
2975 if (err) {
2976 return err;
2977 }
2978
2979 /* Send any outstanding notifications.
2980 * Frees up buffer space for our PDU.
2981 */
2982 gatt_notify_flush(conn);
2983
2984 /* Build the PDU */
2985 buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY_MULT,
2986 sizeof(struct bt_att_notify_mult) + total_len);
2987 if (!buf) {
2988 return -ENOMEM;
2989 }
2990
2991 /* Register the callback. It will be called num_params times. */
2992 bt_att_set_tx_meta_data(buf, params->func, params->user_data, BT_ATT_CHAN_OPT(params));
2993 bt_att_increment_tx_meta_data_attr_count(buf, num_params - 1);
2994
2995 for (uint16_t i = 0; i < num_params; i++) {
2996 struct notify_data data;
2997
2998 data.attr = params[i].attr;
2999 data.handle = bt_gatt_attr_get_handle(data.attr);
3000
3001 /* Check if attribute is a characteristic then adjust the
3002 * handle
3003 */
3004 if (!bt_uuid_cmp(data.attr->uuid, BT_UUID_GATT_CHRC)) {
3005 data.handle = bt_gatt_attr_value_handle(data.attr);
3006 }
3007
3008 /* Add handle and data to the command buffer. */
3009 gatt_add_nfy_to_buf(buf, data.handle, ¶ms[i]);
3010 }
3011
3012 /* Send the buffer. */
3013 return gatt_notify_mult_send(conn, buf);
3014 }
3015 #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE */
3016
bt_gatt_indicate(struct bt_conn * conn,struct bt_gatt_indicate_params * params)3017 int bt_gatt_indicate(struct bt_conn *conn,
3018 struct bt_gatt_indicate_params *params)
3019 {
3020 struct notify_data data;
3021
3022 __ASSERT(params, "invalid parameters\n");
3023 __ASSERT(params->attr || params->uuid, "invalid parameters\n");
3024
3025 if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
3026 return -EAGAIN;
3027 }
3028
3029 if (conn && conn->state != BT_CONN_CONNECTED) {
3030 return -ENOTCONN;
3031 }
3032
3033 data.attr = params->attr;
3034 data.handle = bt_gatt_attr_get_handle(data.attr);
3035
3036 /* Lookup UUID if it was given */
3037 if (params->uuid) {
3038 if (!gatt_find_by_uuid(&data, params->uuid)) {
3039 return -ENOENT;
3040 }
3041
3042 params->attr = data.attr;
3043 } else {
3044 if (!data.handle) {
3045 return -ENOENT;
3046 }
3047 }
3048
3049 /* Check if attribute is a characteristic then adjust the handle */
3050 if (!bt_uuid_cmp(data.attr->uuid, BT_UUID_GATT_CHRC)) {
3051 struct bt_gatt_chrc *chrc = data.attr->user_data;
3052
3053 if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) {
3054 return -EINVAL;
3055 }
3056
3057 data.handle = bt_gatt_attr_value_handle(data.attr);
3058 }
3059
3060 if (conn) {
3061 params->_ref = 1;
3062 return gatt_indicate(conn, data.handle, params);
3063 }
3064
3065 data.err = -ENOTCONN;
3066 data.type = BT_GATT_CCC_INDICATE;
3067 data.ind_params = params;
3068
3069 params->_ref = 0;
3070 bt_gatt_foreach_attr_type(data.handle, 0xffff, BT_UUID_GATT_CCC, NULL,
3071 1, notify_cb, &data);
3072
3073 return data.err;
3074 }
3075
bt_gatt_get_mtu(struct bt_conn * conn)3076 uint16_t bt_gatt_get_mtu(struct bt_conn *conn)
3077 {
3078 return bt_att_get_mtu(conn);
3079 }
3080
bt_gatt_check_perm(struct bt_conn * conn,const struct bt_gatt_attr * attr,uint16_t mask)3081 uint8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr,
3082 uint16_t mask)
3083 {
3084 if ((mask & BT_GATT_PERM_READ) &&
3085 (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) {
3086 return BT_ATT_ERR_READ_NOT_PERMITTED;
3087 }
3088
3089 if ((mask & BT_GATT_PERM_WRITE) &&
3090 (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) {
3091 return BT_ATT_ERR_WRITE_NOT_PERMITTED;
3092 }
3093
3094 if (IS_ENABLED(CONFIG_BT_CONN_DISABLE_SECURITY)) {
3095 return 0;
3096 }
3097
3098 mask &= attr->perm;
3099
3100 /*
3101 * Core Specification 5.4 Vol. 3 Part C 10.3.1
3102 *
3103 * If neither an LTK nor an STK is available, the service
3104 * request shall be rejected with the error code
3105 * “Insufficient Authentication”.
3106 * Note: When the link is not encrypted, the error code
3107 * “Insufficient Authentication” does not indicate that
3108 * MITM protection is required.
3109 *
3110 * If an LTK or an STK is available and encryption is
3111 * required (LE security mode 1) but encryption is not
3112 * enabled, the service request shall be rejected with
3113 * the error code “Insufficient Encryption”.
3114 */
3115
3116 if (mask &
3117 (BT_GATT_PERM_ENCRYPT_MASK | BT_GATT_PERM_AUTHEN_MASK | BT_GATT_PERM_LESC_MASK)) {
3118 #if defined(CONFIG_BT_SMP)
3119 if (!conn->encrypt) {
3120 if (bt_conn_ltk_present(conn)) {
3121 return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
3122 } else {
3123 return BT_ATT_ERR_AUTHENTICATION;
3124 }
3125 }
3126
3127 if (mask & BT_GATT_PERM_AUTHEN_MASK) {
3128 if (bt_conn_get_security(conn) < BT_SECURITY_L3) {
3129 return BT_ATT_ERR_AUTHENTICATION;
3130 }
3131 }
3132
3133 if (mask & BT_GATT_PERM_LESC_MASK) {
3134 const struct bt_keys *keys = conn->le.keys;
3135
3136 if (!keys || (keys->flags & BT_KEYS_SC) == 0) {
3137 return BT_ATT_ERR_AUTHENTICATION;
3138 }
3139 }
3140 #else
3141 return BT_ATT_ERR_AUTHENTICATION;
3142 #endif /* CONFIG_BT_SMP */
3143 }
3144
3145 return 0;
3146 }
3147
sc_restore_rsp(struct bt_conn * conn,struct bt_gatt_indicate_params * params,uint8_t err)3148 static void sc_restore_rsp(struct bt_conn *conn,
3149 struct bt_gatt_indicate_params *params, uint8_t err)
3150 {
3151 #if defined(CONFIG_BT_GATT_CACHING)
3152 struct gatt_cf_cfg *cfg;
3153 #endif
3154
3155 LOG_DBG("err 0x%02x", err);
3156
3157 #if defined(CONFIG_BT_GATT_CACHING)
3158 /* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 3, Part G page 1476:
3159 * 2.5.2.1 Robust Caching
3160 * ... a change-unaware connected client using exactly one ATT bearer
3161 * becomes change-aware when ...
3162 * The client receives and confirms a Handle Value Indication
3163 * for the Service Changed characteristic
3164 */
3165
3166 if (bt_att_fixed_chan_only(conn)) {
3167 cfg = find_cf_cfg(conn);
3168 if (cfg && CF_ROBUST_CACHING(cfg)) {
3169 set_change_aware(cfg, true);
3170 }
3171 }
3172 #endif /* CONFIG_BT_GATT_CACHING */
3173
3174 if (!err && IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
3175 struct gatt_sc_cfg *gsc_cfg = find_sc_cfg(conn->id, &conn->le.dst);
3176
3177 if (gsc_cfg) {
3178 sc_reset(gsc_cfg);
3179 }
3180 }
3181 }
3182
3183 static struct bt_gatt_indicate_params sc_restore_params[CONFIG_BT_MAX_CONN];
3184 static uint16_t sc_range[CONFIG_BT_MAX_CONN][2];
3185
sc_restore(struct bt_conn * conn)3186 static void sc_restore(struct bt_conn *conn)
3187 {
3188 struct gatt_sc_cfg *cfg;
3189 uint8_t index;
3190
3191 cfg = find_sc_cfg(conn->id, &conn->le.dst);
3192 if (!cfg) {
3193 LOG_DBG("no SC data found");
3194 return;
3195 }
3196
3197 if (!(cfg->data.start || cfg->data.end)) {
3198 return;
3199 }
3200
3201 LOG_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer), cfg->data.start,
3202 cfg->data.end);
3203
3204 index = bt_conn_index(conn);
3205
3206 sc_range[index][0] = sys_cpu_to_le16(cfg->data.start);
3207 sc_range[index][1] = sys_cpu_to_le16(cfg->data.end);
3208
3209 sc_restore_params[index].attr = &_1_gatt_svc.attrs[2];
3210 sc_restore_params[index].func = sc_restore_rsp;
3211 sc_restore_params[index].data = &sc_range[index][0];
3212 sc_restore_params[index].len = sizeof(sc_range[index]);
3213
3214 if (bt_gatt_indicate(conn, &sc_restore_params[index])) {
3215 LOG_ERR("SC restore indication failed");
3216 }
3217 }
3218
3219 struct conn_data {
3220 struct bt_conn *conn;
3221 bt_security_t sec;
3222 };
3223
update_ccc(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)3224 static uint8_t update_ccc(const struct bt_gatt_attr *attr, uint16_t handle,
3225 void *user_data)
3226 {
3227 struct conn_data *data = user_data;
3228 struct bt_conn *conn = data->conn;
3229 struct _bt_gatt_ccc *ccc;
3230 size_t i;
3231 uint8_t err;
3232
3233 /* Check attribute user_data must be of type struct _bt_gatt_ccc */
3234 if (attr->write != bt_gatt_attr_write_ccc) {
3235 return BT_GATT_ITER_CONTINUE;
3236 }
3237
3238 ccc = attr->user_data;
3239
3240 for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
3241 struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
3242
3243 /* Ignore configuration for different peer or not active */
3244 if (!cfg->value ||
3245 !bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer)) {
3246 continue;
3247 }
3248
3249 /* Check if attribute requires encryption/authentication */
3250 err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK);
3251 if (err) {
3252 bt_security_t sec;
3253
3254 if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) {
3255 LOG_WRN("CCC %p not writable", attr);
3256 continue;
3257 }
3258
3259 sec = BT_SECURITY_L2;
3260
3261 if (err == BT_ATT_ERR_AUTHENTICATION) {
3262 sec = BT_SECURITY_L3;
3263 }
3264
3265 /* Check if current security is enough */
3266 if (IS_ENABLED(CONFIG_BT_SMP) &&
3267 bt_conn_get_security(conn) < sec) {
3268 if (data->sec < sec) {
3269 data->sec = sec;
3270 }
3271 continue;
3272 }
3273 }
3274
3275 gatt_ccc_changed(attr, ccc);
3276
3277 if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) &&
3278 ccc == &sc_ccc) {
3279 sc_restore(conn);
3280 }
3281
3282 return BT_GATT_ITER_CONTINUE;
3283 }
3284
3285 return BT_GATT_ITER_CONTINUE;
3286 }
3287
disconnected_cb(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)3288 static uint8_t disconnected_cb(const struct bt_gatt_attr *attr, uint16_t handle,
3289 void *user_data)
3290 {
3291 struct bt_conn *conn = user_data;
3292 struct _bt_gatt_ccc *ccc;
3293 bool value_used;
3294 size_t i;
3295
3296 /* Check attribute user_data must be of type struct _bt_gatt_ccc */
3297 if (attr->write != bt_gatt_attr_write_ccc) {
3298 return BT_GATT_ITER_CONTINUE;
3299 }
3300
3301 ccc = attr->user_data;
3302
3303 /* If already disabled skip */
3304 if (!ccc->value) {
3305 return BT_GATT_ITER_CONTINUE;
3306 }
3307
3308 /* Checking if all values are disabled */
3309 value_used = false;
3310
3311 for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
3312 struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
3313
3314 /* Ignore configurations with disabled value */
3315 if (!cfg->value) {
3316 continue;
3317 }
3318
3319 if (!bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer)) {
3320 struct bt_conn *tmp;
3321
3322 /* Skip if there is another peer connected */
3323 tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
3324 if (tmp) {
3325 if (tmp->state == BT_CONN_CONNECTED) {
3326 value_used = true;
3327 }
3328
3329 bt_conn_unref(tmp);
3330 }
3331 } else {
3332 /* Clear value if not paired */
3333 if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
3334 if (ccc == &sc_ccc) {
3335 sc_clear(conn);
3336 }
3337
3338 clear_ccc_cfg(cfg);
3339 } else {
3340 /* Update address in case it has changed */
3341 bt_addr_le_copy(&cfg->peer, &conn->le.dst);
3342 }
3343 }
3344 }
3345
3346 /* If all values are now disabled, reset value while disconnected */
3347 if (!value_used) {
3348 ccc->value = 0U;
3349 if (ccc->cfg_changed) {
3350 ccc->cfg_changed(attr, ccc->value);
3351 }
3352
3353 LOG_DBG("ccc %p reseted", ccc);
3354 }
3355
3356 return BT_GATT_ITER_CONTINUE;
3357 }
3358
bt_gatt_is_subscribed(struct bt_conn * conn,const struct bt_gatt_attr * attr,uint16_t ccc_type)3359 bool bt_gatt_is_subscribed(struct bt_conn *conn,
3360 const struct bt_gatt_attr *attr, uint16_t ccc_type)
3361 {
3362 const struct _bt_gatt_ccc *ccc;
3363
3364 __ASSERT(conn, "invalid parameter\n");
3365 __ASSERT(attr, "invalid parameter\n");
3366
3367 if (conn->state != BT_CONN_CONNECTED) {
3368 return false;
3369 }
3370
3371 /* Check if attribute is a characteristic declaration */
3372 if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
3373 struct bt_gatt_chrc *chrc = attr->user_data;
3374
3375 if (!(chrc->properties &
3376 (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) {
3377 /* Characteristic doesn't support subscription */
3378 return false;
3379 }
3380
3381 attr = bt_gatt_attr_next(attr);
3382 __ASSERT(attr, "No more attributes\n");
3383 }
3384
3385 /* Check if attribute is a characteristic value */
3386 if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
3387 attr = bt_gatt_attr_next(attr);
3388 __ASSERT(attr, "No more attributes\n");
3389 }
3390
3391 /* Find the CCC Descriptor */
3392 while (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) &&
3393 /* Also stop if we leave the current characteristic definition */
3394 bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC) &&
3395 bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) &&
3396 bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
3397 attr = bt_gatt_attr_next(attr);
3398 if (!attr) {
3399 return false;
3400 }
3401 }
3402
3403 if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
3404 return false;
3405 }
3406
3407 ccc = attr->user_data;
3408
3409 /* Check if the connection is subscribed */
3410 for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) {
3411 const struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
3412
3413 if (bt_conn_is_peer_addr_le(conn, cfg->id, &cfg->peer) &&
3414 (ccc_type & ccc->cfg[i].value)) {
3415 return true;
3416 }
3417 }
3418
3419 return false;
3420 }
3421
gatt_sub_is_empty(struct gatt_sub * sub)3422 static bool gatt_sub_is_empty(struct gatt_sub *sub)
3423 {
3424 return sys_slist_is_empty(&sub->list);
3425 }
3426
3427 /** @brief Free sub for reuse.
3428 */
gatt_sub_free(struct gatt_sub * sub)3429 static void gatt_sub_free(struct gatt_sub *sub)
3430 {
3431 __ASSERT_NO_MSG(gatt_sub_is_empty(sub));
3432 bt_addr_le_copy(&sub->peer, BT_ADDR_LE_ANY);
3433 }
3434
gatt_sub_remove(struct bt_conn * conn,struct gatt_sub * sub,sys_snode_t * prev,struct bt_gatt_subscribe_params * params)3435 static void gatt_sub_remove(struct bt_conn *conn, struct gatt_sub *sub,
3436 sys_snode_t *prev,
3437 struct bt_gatt_subscribe_params *params)
3438 {
3439 if (params) {
3440 /* Remove subscription from the list*/
3441 sys_slist_remove(&sub->list, prev, ¶ms->node);
3442 /* Notify removal */
3443 params->notify(conn, params, NULL, 0);
3444 }
3445
3446 if (gatt_sub_is_empty(sub)) {
3447 gatt_sub_free(sub);
3448 }
3449 }
3450
3451 #if defined(CONFIG_BT_GATT_CLIENT)
gatt_sub_find(struct bt_conn * conn)3452 static struct gatt_sub *gatt_sub_find(struct bt_conn *conn)
3453 {
3454 for (int i = 0; i < ARRAY_SIZE(subscriptions); i++) {
3455 struct gatt_sub *sub = &subscriptions[i];
3456
3457 if (!conn) {
3458 if (bt_addr_le_eq(&sub->peer, BT_ADDR_LE_ANY)) {
3459 return sub;
3460 }
3461 } else if (bt_conn_is_peer_addr_le(conn, sub->id, &sub->peer)) {
3462 return sub;
3463 }
3464 }
3465
3466 return NULL;
3467 }
3468
gatt_sub_add(struct bt_conn * conn)3469 static struct gatt_sub *gatt_sub_add(struct bt_conn *conn)
3470 {
3471 struct gatt_sub *sub;
3472
3473 sub = gatt_sub_find(conn);
3474 if (!sub) {
3475 sub = gatt_sub_find(NULL);
3476 if (sub) {
3477 bt_addr_le_copy(&sub->peer, &conn->le.dst);
3478 sub->id = conn->id;
3479 }
3480 }
3481
3482 return sub;
3483 }
3484
gatt_sub_find_by_addr(uint8_t id,const bt_addr_le_t * addr)3485 static struct gatt_sub *gatt_sub_find_by_addr(uint8_t id,
3486 const bt_addr_le_t *addr)
3487 {
3488 for (int i = 0; i < ARRAY_SIZE(subscriptions); i++) {
3489 struct gatt_sub *sub = &subscriptions[i];
3490
3491 if (id == sub->id && bt_addr_le_eq(&sub->peer, addr)) {
3492 return sub;
3493 }
3494 }
3495
3496 return NULL;
3497 }
3498
gatt_sub_add_by_addr(uint8_t id,const bt_addr_le_t * addr)3499 static struct gatt_sub *gatt_sub_add_by_addr(uint8_t id,
3500 const bt_addr_le_t *addr)
3501 {
3502 struct gatt_sub *sub;
3503
3504 sub = gatt_sub_find_by_addr(id, addr);
3505 if (!sub) {
3506 sub = gatt_sub_find(NULL);
3507 if (sub) {
3508 bt_addr_le_copy(&sub->peer, addr);
3509 sub->id = id;
3510 }
3511 }
3512
3513 return sub;
3514 }
3515
check_subscribe_security_level(struct bt_conn * conn,const struct bt_gatt_subscribe_params * params)3516 static bool check_subscribe_security_level(struct bt_conn *conn,
3517 const struct bt_gatt_subscribe_params *params)
3518 {
3519 #if defined(CONFIG_BT_SMP)
3520 return conn->sec_level >= params->min_security;
3521 #endif
3522 return true;
3523 }
3524
bt_gatt_notification(struct bt_conn * conn,uint16_t handle,const void * data,uint16_t length)3525 void bt_gatt_notification(struct bt_conn *conn, uint16_t handle,
3526 const void *data, uint16_t length)
3527 {
3528 struct bt_gatt_subscribe_params *params, *tmp;
3529 struct gatt_sub *sub;
3530
3531 LOG_DBG("handle 0x%04x length %u", handle, length);
3532
3533 sub = gatt_sub_find(conn);
3534 if (!sub) {
3535 return;
3536 }
3537
3538 SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp, node) {
3539 if (handle != params->value_handle) {
3540 continue;
3541 }
3542
3543 if (check_subscribe_security_level(conn, params)) {
3544 if (params->notify(conn, params, data, length) ==
3545 BT_GATT_ITER_STOP) {
3546 bt_gatt_unsubscribe(conn, params);
3547 }
3548 }
3549 }
3550 }
3551
bt_gatt_mult_notification(struct bt_conn * conn,const void * data,uint16_t length)3552 void bt_gatt_mult_notification(struct bt_conn *conn, const void *data,
3553 uint16_t length)
3554 {
3555 struct bt_gatt_subscribe_params *params, *tmp;
3556 const struct bt_att_notify_mult *nfy;
3557 struct net_buf_simple buf;
3558 struct gatt_sub *sub;
3559
3560 LOG_DBG("length %u", length);
3561
3562 sub = gatt_sub_find(conn);
3563 if (!sub) {
3564 return;
3565 }
3566
3567 /* This is fine since there no write operation to the buffer. */
3568 net_buf_simple_init_with_data(&buf, (void *)data, length);
3569
3570 while (buf.len > sizeof(*nfy)) {
3571 uint16_t handle;
3572 uint16_t len;
3573
3574 nfy = net_buf_simple_pull_mem(&buf, sizeof(*nfy));
3575 handle = sys_cpu_to_le16(nfy->handle);
3576 len = sys_cpu_to_le16(nfy->len);
3577
3578 LOG_DBG("handle 0x%02x len %u", handle, len);
3579
3580 if (len > buf.len) {
3581 LOG_ERR("Invalid data len %u > %u", len, length);
3582 return;
3583 }
3584
3585 SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp,
3586 node) {
3587 if (handle != params->value_handle) {
3588 continue;
3589 }
3590
3591 if (check_subscribe_security_level(conn, params)) {
3592 if (params->notify(conn, params, nfy->value, len) ==
3593 BT_GATT_ITER_STOP) {
3594 bt_gatt_unsubscribe(conn, params);
3595 }
3596 }
3597 }
3598
3599 net_buf_simple_pull_mem(&buf, len);
3600 }
3601 }
3602
gatt_sub_update(struct bt_conn * conn,struct gatt_sub * sub)3603 static void gatt_sub_update(struct bt_conn *conn, struct gatt_sub *sub)
3604 {
3605 if (sub->peer.type == BT_ADDR_LE_PUBLIC) {
3606 return;
3607 }
3608
3609 /* Update address */
3610 bt_addr_le_copy(&sub->peer, &conn->le.dst);
3611 }
3612
remove_subscriptions(struct bt_conn * conn)3613 static void remove_subscriptions(struct bt_conn *conn)
3614 {
3615 struct gatt_sub *sub;
3616 struct bt_gatt_subscribe_params *params, *tmp;
3617 sys_snode_t *prev = NULL;
3618
3619 sub = gatt_sub_find(conn);
3620 if (!sub) {
3621 return;
3622 }
3623
3624 /* Lookup existing subscriptions */
3625 SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp, node) {
3626 atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_SENT);
3627
3628 if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) ||
3629 (atomic_test_bit(params->flags,
3630 BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) {
3631 /* Remove subscription */
3632 params->value = 0U;
3633 gatt_sub_remove(conn, sub, prev, params);
3634 } else {
3635 gatt_sub_update(conn, sub);
3636 prev = ¶ms->node;
3637 }
3638 }
3639 }
3640
gatt_mtu_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)3641 static void gatt_mtu_rsp(struct bt_conn *conn, int err, const void *pdu,
3642 uint16_t length, void *user_data)
3643 {
3644 struct bt_gatt_exchange_params *params = user_data;
3645
3646 params->func(conn, att_err_from_int(err), params);
3647 }
3648
gatt_exchange_mtu_encode(struct net_buf * buf,size_t len,void * user_data)3649 static int gatt_exchange_mtu_encode(struct net_buf *buf, size_t len,
3650 void *user_data)
3651 {
3652 struct bt_att_exchange_mtu_req *req;
3653 uint16_t mtu;
3654
3655 mtu = BT_LOCAL_ATT_MTU_UATT;
3656
3657 LOG_DBG("Client MTU %u", mtu);
3658
3659 req = net_buf_add(buf, sizeof(*req));
3660 req->mtu = sys_cpu_to_le16(mtu);
3661
3662 return 0;
3663 }
3664
bt_gatt_exchange_mtu(struct bt_conn * conn,struct bt_gatt_exchange_params * params)3665 int bt_gatt_exchange_mtu(struct bt_conn *conn,
3666 struct bt_gatt_exchange_params *params)
3667 {
3668 int err;
3669
3670 __ASSERT(conn, "invalid parameter\n");
3671 __ASSERT(params && params->func, "invalid parameters\n");
3672
3673 if (conn->state != BT_CONN_CONNECTED) {
3674 return -ENOTCONN;
3675 }
3676
3677 /* This request shall only be sent once during a connection by the client. */
3678 if (atomic_test_and_set_bit(conn->flags, BT_CONN_ATT_MTU_EXCHANGED)) {
3679 return -EALREADY;
3680 }
3681
3682 err = gatt_req_send(conn, gatt_mtu_rsp, params,
3683 gatt_exchange_mtu_encode, BT_ATT_OP_MTU_REQ,
3684 sizeof(struct bt_att_exchange_mtu_req),
3685 BT_ATT_CHAN_OPT_UNENHANCED_ONLY);
3686 if (err) {
3687 atomic_clear_bit(conn->flags, BT_CONN_ATT_MTU_EXCHANGED);
3688 }
3689
3690 return err;
3691 }
3692
gatt_discover_next(struct bt_conn * conn,uint16_t last_handle,struct bt_gatt_discover_params * params)3693 static void gatt_discover_next(struct bt_conn *conn, uint16_t last_handle,
3694 struct bt_gatt_discover_params *params)
3695 {
3696 /* Skip if last_handle is not set */
3697 if (!last_handle)
3698 goto discover;
3699
3700 /* Continue from the last found handle */
3701 params->start_handle = last_handle;
3702 if (params->start_handle < UINT16_MAX) {
3703 params->start_handle++;
3704 } else {
3705 goto done;
3706 }
3707
3708 /* Stop if over the range or the requests */
3709 if (params->start_handle > params->end_handle) {
3710 goto done;
3711 }
3712
3713 discover:
3714 /* Discover next range */
3715 if (!bt_gatt_discover(conn, params)) {
3716 return;
3717 }
3718
3719 done:
3720 params->func(conn, NULL, params);
3721 }
3722
gatt_find_type_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)3723 static void gatt_find_type_rsp(struct bt_conn *conn, int err,
3724 const void *pdu, uint16_t length,
3725 void *user_data)
3726 {
3727 const struct bt_att_handle_group *rsp = pdu;
3728 struct bt_gatt_discover_params *params = user_data;
3729 uint8_t count;
3730 uint16_t end_handle = 0U, start_handle;
3731
3732 LOG_DBG("err %d", err);
3733
3734 if (err || (length % sizeof(struct bt_att_handle_group) != 0)) {
3735 goto done;
3736 }
3737
3738 count = length / sizeof(struct bt_att_handle_group);
3739
3740 /* Parse attributes found */
3741 for (uint8_t i = 0U; i < count; i++) {
3742 struct bt_uuid_16 uuid_svc;
3743 struct bt_gatt_attr attr;
3744 struct bt_gatt_service_val value;
3745
3746 start_handle = sys_le16_to_cpu(rsp[i].start_handle);
3747 end_handle = sys_le16_to_cpu(rsp[i].end_handle);
3748
3749 LOG_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, end_handle);
3750
3751 uuid_svc.uuid.type = BT_UUID_TYPE_16;
3752 if (params->type == BT_GATT_DISCOVER_PRIMARY) {
3753 uuid_svc.val = BT_UUID_GATT_PRIMARY_VAL;
3754 } else {
3755 uuid_svc.val = BT_UUID_GATT_SECONDARY_VAL;
3756 }
3757
3758 value.end_handle = end_handle;
3759 value.uuid = params->uuid;
3760
3761 attr = (struct bt_gatt_attr) {
3762 .uuid = &uuid_svc.uuid,
3763 .user_data = &value,
3764 .handle = start_handle,
3765 };
3766
3767 if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
3768 return;
3769 }
3770 }
3771
3772 gatt_discover_next(conn, end_handle, params);
3773
3774 return;
3775 done:
3776 params->func(conn, NULL, params);
3777 }
3778
gatt_find_type_encode(struct net_buf * buf,size_t len,void * user_data)3779 static int gatt_find_type_encode(struct net_buf *buf, size_t len,
3780 void *user_data)
3781 {
3782 struct bt_gatt_discover_params *params = user_data;
3783 struct bt_att_find_type_req *req;
3784 uint16_t uuid_val;
3785
3786 req = net_buf_add(buf, sizeof(*req));
3787 req->start_handle = sys_cpu_to_le16(params->start_handle);
3788 req->end_handle = sys_cpu_to_le16(params->end_handle);
3789
3790 if (params->type == BT_GATT_DISCOVER_PRIMARY) {
3791 uuid_val = BT_UUID_GATT_PRIMARY_VAL;
3792 } else {
3793 uuid_val = BT_UUID_GATT_SECONDARY_VAL;
3794 }
3795
3796 req->type = sys_cpu_to_le16(uuid_val);
3797
3798 LOG_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x", bt_uuid_str(params->uuid),
3799 params->start_handle, params->end_handle);
3800
3801 switch (params->uuid->type) {
3802 case BT_UUID_TYPE_16:
3803 net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val);
3804 break;
3805 case BT_UUID_TYPE_128:
3806 net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16);
3807 break;
3808 }
3809
3810 return 0;
3811 }
3812
gatt_find_type(struct bt_conn * conn,struct bt_gatt_discover_params * params)3813 static int gatt_find_type(struct bt_conn *conn,
3814 struct bt_gatt_discover_params *params)
3815 {
3816 size_t len;
3817
3818 len = sizeof(struct bt_att_find_type_req);
3819
3820 switch (params->uuid->type) {
3821 case BT_UUID_TYPE_16:
3822 len += BT_UUID_SIZE_16;
3823 break;
3824 case BT_UUID_TYPE_128:
3825 len += BT_UUID_SIZE_128;
3826 break;
3827 default:
3828 LOG_ERR("Unknown UUID type %u", params->uuid->type);
3829 return -EINVAL;
3830 }
3831
3832 return gatt_req_send(conn, gatt_find_type_rsp, params,
3833 gatt_find_type_encode, BT_ATT_OP_FIND_TYPE_REQ,
3834 len, BT_ATT_CHAN_OPT(params));
3835 }
3836
read_included_uuid_cb(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)3837 static void read_included_uuid_cb(struct bt_conn *conn, int err,
3838 const void *pdu, uint16_t length,
3839 void *user_data)
3840 {
3841 struct bt_gatt_discover_params *params = user_data;
3842 struct bt_gatt_include value;
3843 struct bt_gatt_attr attr;
3844 uint16_t handle;
3845 union {
3846 struct bt_uuid uuid;
3847 struct bt_uuid_128 u128;
3848 } u;
3849
3850 if (length != 16U) {
3851 LOG_ERR("Invalid data len %u", length);
3852 params->func(conn, NULL, params);
3853 return;
3854 }
3855
3856 handle = params->_included.attr_handle;
3857 value.start_handle = params->_included.start_handle;
3858 value.end_handle = params->_included.end_handle;
3859 value.uuid = &u.uuid;
3860 u.uuid.type = BT_UUID_TYPE_128;
3861 memcpy(u.u128.val, pdu, length);
3862
3863 LOG_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
3864 "end_handle 0x%04x\n", params->_included.attr_handle,
3865 bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
3866
3867 /* Skip if UUID is set but doesn't match */
3868 if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
3869 goto next;
3870 }
3871
3872 attr = (struct bt_gatt_attr) {
3873 .uuid = BT_UUID_GATT_INCLUDE,
3874 .user_data = &value,
3875 .handle = handle,
3876 };
3877
3878 if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
3879 return;
3880 }
3881 next:
3882 gatt_discover_next(conn, params->start_handle, params);
3883
3884 return;
3885 }
3886
read_included_uuid_encode(struct net_buf * buf,size_t len,void * user_data)3887 static int read_included_uuid_encode(struct net_buf *buf, size_t len,
3888 void *user_data)
3889 {
3890 struct bt_gatt_discover_params *params = user_data;
3891 struct bt_att_read_req *req;
3892
3893 req = net_buf_add(buf, sizeof(*req));
3894 req->handle = sys_cpu_to_le16(params->_included.start_handle);
3895
3896 return 0;
3897 }
3898
read_included_uuid(struct bt_conn * conn,struct bt_gatt_discover_params * params)3899 static int read_included_uuid(struct bt_conn *conn,
3900 struct bt_gatt_discover_params *params)
3901 {
3902 LOG_DBG("handle 0x%04x", params->_included.start_handle);
3903
3904 return gatt_req_send(conn, read_included_uuid_cb, params,
3905 read_included_uuid_encode, BT_ATT_OP_READ_REQ,
3906 sizeof(struct bt_att_read_req), BT_ATT_CHAN_OPT(params));
3907 }
3908
parse_include(struct bt_conn * conn,const void * pdu,struct bt_gatt_discover_params * params,uint16_t length)3909 static uint16_t parse_include(struct bt_conn *conn, const void *pdu,
3910 struct bt_gatt_discover_params *params,
3911 uint16_t length)
3912 {
3913 const struct bt_att_read_type_rsp *rsp = pdu;
3914 uint16_t handle = 0U;
3915 struct bt_gatt_include value;
3916 union {
3917 struct bt_uuid uuid;
3918 struct bt_uuid_16 u16;
3919 struct bt_uuid_128 u128;
3920 } u;
3921
3922 /* Data can be either in UUID16 or UUID128 */
3923 switch (rsp->len) {
3924 case 8: /* UUID16 */
3925 u.uuid.type = BT_UUID_TYPE_16;
3926 break;
3927 case 6: /* UUID128 */
3928 /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550
3929 * To get the included service UUID when the included service
3930 * uses a 128-bit UUID, the Read Request is used.
3931 */
3932 u.uuid.type = BT_UUID_TYPE_128;
3933 break;
3934 default:
3935 LOG_ERR("Invalid data len %u", rsp->len);
3936 goto done;
3937 }
3938
3939 /* Parse include found */
3940 for (length--, pdu = rsp->data; length >= rsp->len;
3941 length -= rsp->len, pdu = (const uint8_t *)pdu + rsp->len) {
3942 struct bt_gatt_attr attr;
3943 const struct bt_att_data *data = pdu;
3944 struct gatt_incl *incl = (void *)data->value;
3945
3946 handle = sys_le16_to_cpu(data->handle);
3947 /* Handle 0 is invalid */
3948 if (!handle) {
3949 goto done;
3950 }
3951
3952 /* Convert include data, bt_gatt_incl and gatt_incl
3953 * have different formats so the conversion have to be done
3954 * field by field.
3955 */
3956 value.start_handle = sys_le16_to_cpu(incl->start_handle);
3957 value.end_handle = sys_le16_to_cpu(incl->end_handle);
3958
3959 switch (u.uuid.type) {
3960 case BT_UUID_TYPE_16:
3961 value.uuid = &u.uuid;
3962 u.u16.val = sys_le16_to_cpu(incl->uuid16);
3963 break;
3964 case BT_UUID_TYPE_128:
3965 params->_included.attr_handle = handle;
3966 params->_included.start_handle = value.start_handle;
3967 params->_included.end_handle = value.end_handle;
3968
3969 return read_included_uuid(conn, params);
3970 }
3971
3972 LOG_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
3973 "end_handle 0x%04x\n", handle, bt_uuid_str(&u.uuid),
3974 value.start_handle, value.end_handle);
3975
3976 /* Skip if UUID is set but doesn't match */
3977 if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
3978 continue;
3979 }
3980
3981 attr = (struct bt_gatt_attr) {
3982 .uuid = BT_UUID_GATT_INCLUDE,
3983 .user_data = &value,
3984 .handle = handle,
3985 };
3986
3987 if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
3988 return 0;
3989 }
3990 }
3991
3992 /* Whole PDU read without error */
3993 if (length == 0U && handle) {
3994 return handle;
3995 }
3996
3997 done:
3998 params->func(conn, NULL, params);
3999 return 0;
4000 }
4001
parse_characteristic(struct bt_conn * conn,const void * pdu,struct bt_gatt_discover_params * params,uint16_t length)4002 static uint16_t parse_characteristic(struct bt_conn *conn, const void *pdu,
4003 struct bt_gatt_discover_params *params,
4004 uint16_t length)
4005 {
4006 const struct bt_att_read_type_rsp *rsp = pdu;
4007 uint16_t handle = 0U;
4008 union {
4009 struct bt_uuid uuid;
4010 struct bt_uuid_16 u16;
4011 struct bt_uuid_128 u128;
4012 } u;
4013
4014 /* Data can be either in UUID16 or UUID128 */
4015 switch (rsp->len) {
4016 case 7: /* UUID16 */
4017 u.uuid.type = BT_UUID_TYPE_16;
4018 break;
4019 case 21: /* UUID128 */
4020 u.uuid.type = BT_UUID_TYPE_128;
4021 break;
4022 default:
4023 LOG_ERR("Invalid data len %u", rsp->len);
4024 goto done;
4025 }
4026
4027 /* Parse characteristics found */
4028 for (length--, pdu = rsp->data; length >= rsp->len;
4029 length -= rsp->len, pdu = (const uint8_t *)pdu + rsp->len) {
4030 struct bt_gatt_attr attr;
4031 struct bt_gatt_chrc value;
4032 const struct bt_att_data *data = pdu;
4033 struct gatt_chrc *chrc = (void *)data->value;
4034
4035 handle = sys_le16_to_cpu(data->handle);
4036 /* Handle 0 is invalid */
4037 if (!handle) {
4038 goto done;
4039 }
4040
4041 switch (u.uuid.type) {
4042 case BT_UUID_TYPE_16:
4043 u.u16.val = sys_le16_to_cpu(chrc->uuid16);
4044 break;
4045 case BT_UUID_TYPE_128:
4046 memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid));
4047 break;
4048 }
4049
4050 LOG_DBG("handle 0x%04x uuid %s properties 0x%02x", handle, bt_uuid_str(&u.uuid),
4051 chrc->properties);
4052
4053 /* Skip if UUID is set but doesn't match */
4054 if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
4055 continue;
4056 }
4057
4058 value = (struct bt_gatt_chrc)BT_GATT_CHRC_INIT(
4059 &u.uuid, sys_le16_to_cpu(chrc->value_handle),
4060 chrc->properties);
4061
4062 attr = (struct bt_gatt_attr) {
4063 .uuid = BT_UUID_GATT_CHRC,
4064 .user_data = &value,
4065 .handle = handle,
4066 };
4067
4068 if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
4069 return 0;
4070 }
4071 }
4072
4073 /* Whole PDU read without error */
4074 if (length == 0U && handle) {
4075 return handle;
4076 }
4077
4078 done:
4079 params->func(conn, NULL, params);
4080 return 0;
4081 }
4082
parse_read_std_char_desc(struct bt_conn * conn,const void * pdu,struct bt_gatt_discover_params * params,uint16_t length)4083 static uint16_t parse_read_std_char_desc(struct bt_conn *conn, const void *pdu,
4084 struct bt_gatt_discover_params *params,
4085 uint16_t length)
4086 {
4087 const struct bt_att_read_type_rsp *rsp = pdu;
4088 uint16_t handle = 0U;
4089 uint16_t uuid_val;
4090
4091 if (params->uuid->type != BT_UUID_TYPE_16) {
4092 goto done;
4093 }
4094
4095 uuid_val = BT_UUID_16(params->uuid)->val;
4096
4097 /* Parse characteristics found */
4098 for (length--, pdu = rsp->data; length >= rsp->len;
4099 length -= rsp->len, pdu = (const uint8_t *)pdu + rsp->len) {
4100 union {
4101 struct bt_gatt_ccc ccc;
4102 struct bt_gatt_cpf cpf;
4103 struct bt_gatt_cep cep;
4104 struct bt_gatt_scc scc;
4105 } value;
4106 const struct bt_att_data *data = pdu;
4107 struct bt_gatt_attr attr;
4108
4109 handle = sys_le16_to_cpu(data->handle);
4110 /* Handle 0 is invalid */
4111 if (!handle) {
4112 goto done;
4113 }
4114
4115 switch (uuid_val) {
4116 case BT_UUID_GATT_CEP_VAL:
4117 value.cep.properties = sys_get_le16(data->value);
4118 break;
4119 case BT_UUID_GATT_CCC_VAL:
4120 value.ccc.flags = sys_get_le16(data->value);
4121 break;
4122 case BT_UUID_GATT_SCC_VAL:
4123 value.scc.flags = sys_get_le16(data->value);
4124 break;
4125 case BT_UUID_GATT_CPF_VAL:
4126 {
4127 struct gatt_cpf *cpf = (struct gatt_cpf *)data->value;
4128
4129 value.cpf.format = cpf->format;
4130 value.cpf.exponent = cpf->exponent;
4131 value.cpf.unit = sys_le16_to_cpu(cpf->unit);
4132 value.cpf.name_space = cpf->name_space;
4133 value.cpf.description = sys_le16_to_cpu(cpf->description);
4134 break;
4135 }
4136 default:
4137 goto done;
4138 }
4139
4140 attr = (struct bt_gatt_attr) {
4141 .uuid = params->uuid,
4142 .user_data = &value,
4143 .handle = handle,
4144 };
4145
4146 if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
4147 return 0;
4148 }
4149 }
4150
4151 /* Whole PDU read without error */
4152 if (length == 0U && handle) {
4153 return handle;
4154 }
4155
4156 done:
4157 params->func(conn, NULL, params);
4158 return 0;
4159 }
4160
gatt_read_type_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4161 static void gatt_read_type_rsp(struct bt_conn *conn, int err,
4162 const void *pdu, uint16_t length,
4163 void *user_data)
4164 {
4165 struct bt_gatt_discover_params *params = user_data;
4166 uint16_t handle;
4167
4168 LOG_DBG("err %d", err);
4169
4170 if (err) {
4171 params->func(conn, NULL, params);
4172 return;
4173 }
4174
4175 if (params->type == BT_GATT_DISCOVER_INCLUDE) {
4176 handle = parse_include(conn, pdu, params, length);
4177 } else if (params->type == BT_GATT_DISCOVER_CHARACTERISTIC) {
4178 handle = parse_characteristic(conn, pdu, params, length);
4179 } else {
4180 handle = parse_read_std_char_desc(conn, pdu, params, length);
4181 }
4182
4183 if (!handle) {
4184 return;
4185 }
4186
4187 gatt_discover_next(conn, handle, params);
4188 }
4189
gatt_read_type_encode(struct net_buf * buf,size_t len,void * user_data)4190 static int gatt_read_type_encode(struct net_buf *buf, size_t len,
4191 void *user_data)
4192 {
4193 struct bt_gatt_discover_params *params = user_data;
4194 struct bt_att_read_type_req *req;
4195
4196 req = net_buf_add(buf, sizeof(*req));
4197 req->start_handle = sys_cpu_to_le16(params->start_handle);
4198 req->end_handle = sys_cpu_to_le16(params->end_handle);
4199
4200 switch (params->type) {
4201 case BT_GATT_DISCOVER_INCLUDE:
4202 net_buf_add_le16(buf, BT_UUID_GATT_INCLUDE_VAL);
4203 break;
4204 case BT_GATT_DISCOVER_CHARACTERISTIC:
4205 net_buf_add_le16(buf, BT_UUID_GATT_CHRC_VAL);
4206 break;
4207 default:
4208 /* Only 16-bit UUIDs supported */
4209 net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val);
4210 break;
4211 }
4212
4213 return 0;
4214 }
4215
gatt_read_type(struct bt_conn * conn,struct bt_gatt_discover_params * params)4216 static int gatt_read_type(struct bt_conn *conn,
4217 struct bt_gatt_discover_params *params)
4218 {
4219 LOG_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
4220
4221 return gatt_req_send(conn, gatt_read_type_rsp, params,
4222 gatt_read_type_encode, BT_ATT_OP_READ_TYPE_REQ,
4223 sizeof(struct bt_att_read_type_req), BT_ATT_CHAN_OPT(params));
4224 }
4225
parse_service(struct bt_conn * conn,const void * pdu,struct bt_gatt_discover_params * params,uint16_t length)4226 static uint16_t parse_service(struct bt_conn *conn, const void *pdu,
4227 struct bt_gatt_discover_params *params,
4228 uint16_t length)
4229 {
4230 const struct bt_att_read_group_rsp *rsp = pdu;
4231 uint16_t start_handle, end_handle = 0U;
4232 union {
4233 struct bt_uuid uuid;
4234 struct bt_uuid_16 u16;
4235 struct bt_uuid_128 u128;
4236 } u;
4237
4238 /* Data can be either in UUID16 or UUID128 */
4239 switch (rsp->len) {
4240 case 6: /* UUID16 */
4241 u.uuid.type = BT_UUID_TYPE_16;
4242 break;
4243 case 20: /* UUID128 */
4244 u.uuid.type = BT_UUID_TYPE_128;
4245 break;
4246 default:
4247 LOG_ERR("Invalid data len %u", rsp->len);
4248 goto done;
4249 }
4250
4251 /* Parse services found */
4252 for (length--, pdu = rsp->data; length >= rsp->len;
4253 length -= rsp->len, pdu = (const uint8_t *)pdu + rsp->len) {
4254 struct bt_uuid_16 uuid_svc;
4255 struct bt_gatt_attr attr = {};
4256 struct bt_gatt_service_val value;
4257 const struct bt_att_group_data *data = pdu;
4258
4259 start_handle = sys_le16_to_cpu(data->start_handle);
4260 if (!start_handle) {
4261 goto done;
4262 }
4263
4264 end_handle = sys_le16_to_cpu(data->end_handle);
4265 if (!end_handle || end_handle < start_handle) {
4266 goto done;
4267 }
4268
4269 switch (u.uuid.type) {
4270 case BT_UUID_TYPE_16:
4271 memcpy(&u.u16.val, data->value, sizeof(u.u16.val));
4272 u.u16.val = sys_le16_to_cpu(u.u16.val);
4273 break;
4274 case BT_UUID_TYPE_128:
4275 memcpy(u.u128.val, data->value, sizeof(u.u128.val));
4276 break;
4277 }
4278
4279 LOG_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", start_handle, end_handle,
4280 bt_uuid_str(&u.uuid));
4281
4282 uuid_svc.uuid.type = BT_UUID_TYPE_16;
4283 if (params->type == BT_GATT_DISCOVER_PRIMARY) {
4284 uuid_svc.val = BT_UUID_GATT_PRIMARY_VAL;
4285 } else {
4286 uuid_svc.val = BT_UUID_GATT_SECONDARY_VAL;
4287 }
4288
4289 value.end_handle = end_handle;
4290 value.uuid = &u.uuid;
4291
4292 attr.uuid = &uuid_svc.uuid;
4293 attr.handle = start_handle;
4294 attr.user_data = &value;
4295
4296 if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
4297 return 0;
4298 }
4299 }
4300
4301 /* Whole PDU read without error */
4302 if (length == 0U && end_handle) {
4303 return end_handle;
4304 }
4305
4306 done:
4307 params->func(conn, NULL, params);
4308 return 0;
4309 }
4310
gatt_read_group_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4311 static void gatt_read_group_rsp(struct bt_conn *conn, int err,
4312 const void *pdu, uint16_t length,
4313 void *user_data)
4314 {
4315 struct bt_gatt_discover_params *params = user_data;
4316 uint16_t handle;
4317
4318 LOG_DBG("err %d", err);
4319
4320 if (err) {
4321 params->func(conn, NULL, params);
4322 return;
4323 }
4324
4325 handle = parse_service(conn, pdu, params, length);
4326 if (!handle) {
4327 return;
4328 }
4329
4330 gatt_discover_next(conn, handle, params);
4331 }
4332
gatt_read_group_encode(struct net_buf * buf,size_t len,void * user_data)4333 static int gatt_read_group_encode(struct net_buf *buf, size_t len,
4334 void *user_data)
4335 {
4336 struct bt_gatt_discover_params *params = user_data;
4337 struct bt_att_read_group_req *req;
4338
4339 req = net_buf_add(buf, sizeof(*req));
4340 req->start_handle = sys_cpu_to_le16(params->start_handle);
4341 req->end_handle = sys_cpu_to_le16(params->end_handle);
4342
4343 if (params->type == BT_GATT_DISCOVER_PRIMARY) {
4344 net_buf_add_le16(buf, BT_UUID_GATT_PRIMARY_VAL);
4345 } else {
4346 net_buf_add_le16(buf, BT_UUID_GATT_SECONDARY_VAL);
4347 }
4348
4349 return 0;
4350 }
4351
gatt_read_group(struct bt_conn * conn,struct bt_gatt_discover_params * params)4352 static int gatt_read_group(struct bt_conn *conn,
4353 struct bt_gatt_discover_params *params)
4354 {
4355 LOG_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
4356
4357 return gatt_req_send(conn, gatt_read_group_rsp, params,
4358 gatt_read_group_encode,
4359 BT_ATT_OP_READ_GROUP_REQ,
4360 sizeof(struct bt_att_read_group_req),
4361 BT_ATT_CHAN_OPT(params));
4362 }
4363
gatt_find_info_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4364 static void gatt_find_info_rsp(struct bt_conn *conn, int err,
4365 const void *pdu, uint16_t length,
4366 void *user_data)
4367 {
4368 const struct bt_att_find_info_rsp *rsp = pdu;
4369 struct bt_gatt_discover_params *params = user_data;
4370 uint16_t handle = 0U;
4371 uint16_t len;
4372 union {
4373 const struct bt_att_info_16 *i16;
4374 const struct bt_att_info_128 *i128;
4375 } info;
4376 union {
4377 struct bt_uuid uuid;
4378 struct bt_uuid_16 u16;
4379 struct bt_uuid_128 u128;
4380 } u;
4381 int i;
4382 bool skip = false;
4383
4384 LOG_DBG("err %d", err);
4385
4386 if (err) {
4387 goto done;
4388 }
4389
4390 /* Data can be either in UUID16 or UUID128 */
4391 switch (rsp->format) {
4392 case BT_ATT_INFO_16:
4393 u.uuid.type = BT_UUID_TYPE_16;
4394 len = sizeof(*info.i16);
4395 break;
4396 case BT_ATT_INFO_128:
4397 u.uuid.type = BT_UUID_TYPE_128;
4398 len = sizeof(*info.i128);
4399 break;
4400 default:
4401 LOG_ERR("Invalid format %u", rsp->format);
4402 goto done;
4403 }
4404
4405 length--;
4406
4407 /* Check if there is a least one descriptor in the response */
4408 if (length < len) {
4409 goto done;
4410 }
4411
4412 /* Parse descriptors found */
4413 for (i = length / len, pdu = rsp->info; i != 0;
4414 i--, pdu = (const uint8_t *)pdu + len) {
4415 struct bt_gatt_attr attr;
4416
4417 info.i16 = pdu;
4418 handle = sys_le16_to_cpu(info.i16->handle);
4419
4420 if (skip) {
4421 skip = false;
4422 continue;
4423 }
4424
4425 switch (u.uuid.type) {
4426 case BT_UUID_TYPE_16:
4427 u.u16.val = sys_le16_to_cpu(info.i16->uuid);
4428 break;
4429 case BT_UUID_TYPE_128:
4430 memcpy(u.u128.val, info.i128->uuid, 16);
4431 break;
4432 }
4433
4434 LOG_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid));
4435
4436 /* Skip if UUID is set but doesn't match */
4437 if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
4438 continue;
4439 }
4440
4441 if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) {
4442 /* Skip attributes that are not considered
4443 * descriptors.
4444 */
4445 if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) ||
4446 !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) ||
4447 !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) {
4448 continue;
4449 }
4450
4451 /* If Characteristic Declaration skip ahead as the next
4452 * entry must be its value.
4453 */
4454 if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) {
4455 skip = true;
4456 continue;
4457 }
4458 }
4459
4460 /* No user_data in this case */
4461 attr = (struct bt_gatt_attr) {
4462 .uuid = &u.uuid,
4463 .handle = handle,
4464 };
4465
4466 if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
4467 return;
4468 }
4469 }
4470
4471 gatt_discover_next(conn, handle, params);
4472
4473 return;
4474
4475 done:
4476 params->func(conn, NULL, params);
4477 }
4478
gatt_find_info_encode(struct net_buf * buf,size_t len,void * user_data)4479 static int gatt_find_info_encode(struct net_buf *buf, size_t len,
4480 void *user_data)
4481 {
4482 struct bt_gatt_discover_params *params = user_data;
4483 struct bt_att_find_info_req *req;
4484
4485 req = net_buf_add(buf, sizeof(*req));
4486 req->start_handle = sys_cpu_to_le16(params->start_handle);
4487 req->end_handle = sys_cpu_to_le16(params->end_handle);
4488
4489 return 0;
4490 }
4491
gatt_find_info(struct bt_conn * conn,struct bt_gatt_discover_params * params)4492 static int gatt_find_info(struct bt_conn *conn,
4493 struct bt_gatt_discover_params *params)
4494 {
4495 LOG_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
4496
4497 return gatt_req_send(conn, gatt_find_info_rsp, params,
4498 gatt_find_info_encode, BT_ATT_OP_FIND_INFO_REQ,
4499 sizeof(struct bt_att_find_info_req),
4500 BT_ATT_CHAN_OPT(params));
4501 }
4502
bt_gatt_discover(struct bt_conn * conn,struct bt_gatt_discover_params * params)4503 int bt_gatt_discover(struct bt_conn *conn,
4504 struct bt_gatt_discover_params *params)
4505 {
4506 __ASSERT(conn, "invalid parameters\n");
4507 __ASSERT(params && params->func, "invalid parameters\n");
4508 __ASSERT((params->start_handle && params->end_handle),
4509 "invalid parameters\n");
4510 __ASSERT((params->start_handle <= params->end_handle),
4511 "invalid parameters\n");
4512
4513 if (conn->state != BT_CONN_CONNECTED) {
4514 return -ENOTCONN;
4515 }
4516
4517 switch (params->type) {
4518 case BT_GATT_DISCOVER_PRIMARY:
4519 case BT_GATT_DISCOVER_SECONDARY:
4520 if (params->uuid) {
4521 return gatt_find_type(conn, params);
4522 }
4523 return gatt_read_group(conn, params);
4524
4525 case BT_GATT_DISCOVER_STD_CHAR_DESC:
4526 if (!(params->uuid && params->uuid->type == BT_UUID_TYPE_16 &&
4527 (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_CEP) ||
4528 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CCC) ||
4529 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SCC) ||
4530 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CPF)))) {
4531 return -EINVAL;
4532 }
4533 __fallthrough;
4534 case BT_GATT_DISCOVER_INCLUDE:
4535 case BT_GATT_DISCOVER_CHARACTERISTIC:
4536 return gatt_read_type(conn, params);
4537 case BT_GATT_DISCOVER_DESCRIPTOR:
4538 /* Only descriptors can be filtered */
4539 if (params->uuid &&
4540 (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) ||
4541 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) ||
4542 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) ||
4543 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) {
4544 return -EINVAL;
4545 }
4546 __fallthrough;
4547 case BT_GATT_DISCOVER_ATTRIBUTE:
4548 return gatt_find_info(conn, params);
4549 default:
4550 LOG_ERR("Invalid discovery type: %u", params->type);
4551 }
4552
4553 return -EINVAL;
4554 }
4555
parse_read_by_uuid(struct bt_conn * conn,struct bt_gatt_read_params * params,const void * pdu,uint16_t length)4556 static void parse_read_by_uuid(struct bt_conn *conn,
4557 struct bt_gatt_read_params *params,
4558 const void *pdu, uint16_t length)
4559 {
4560 const struct bt_att_read_type_rsp *rsp = pdu;
4561
4562 const uint16_t req_start_handle = params->by_uuid.start_handle;
4563 const uint16_t req_end_handle = params->by_uuid.end_handle;
4564
4565 /* Parse values found */
4566 for (length--, pdu = rsp->data; length;
4567 length -= rsp->len, pdu = (const uint8_t *)pdu + rsp->len) {
4568 const struct bt_att_data *data = pdu;
4569 uint16_t handle;
4570 uint16_t len;
4571
4572 handle = sys_le16_to_cpu(data->handle);
4573
4574 /* Handle 0 is invalid */
4575 if (!handle) {
4576 LOG_ERR("Invalid handle");
4577 return;
4578 }
4579
4580 len = rsp->len > length ? length - 2 : rsp->len - 2;
4581
4582 LOG_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len);
4583
4584 if (!IN_RANGE(handle, req_start_handle, req_end_handle)) {
4585 LOG_WRN("Bad peer: ATT read-by-uuid rsp: "
4586 "Handle 0x%04x is outside requested range 0x%04x-0x%04x. "
4587 "Aborting read.",
4588 handle, req_start_handle, req_end_handle);
4589 params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
4590 return;
4591 }
4592
4593 /* Update start_handle */
4594 params->by_uuid.start_handle = handle;
4595
4596 if (params->func(conn, 0, params, data->value, len) ==
4597 BT_GATT_ITER_STOP) {
4598 return;
4599 }
4600
4601 /* Check if long attribute */
4602 if (rsp->len > length) {
4603 break;
4604 }
4605
4606 /* Stop if it's the last handle to be read */
4607 if (params->by_uuid.start_handle == params->by_uuid.end_handle) {
4608 params->func(conn, 0, params, NULL, 0);
4609 return;
4610 }
4611
4612 params->by_uuid.start_handle++;
4613 }
4614
4615 /* Continue reading the attributes */
4616 if (bt_gatt_read(conn, params) < 0) {
4617 params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
4618 }
4619 }
4620
gatt_read_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4621 static void gatt_read_rsp(struct bt_conn *conn, int err, const void *pdu,
4622 uint16_t length, void *user_data)
4623 {
4624 struct bt_gatt_read_params *params = user_data;
4625
4626 LOG_DBG("err %d", err);
4627
4628 if (err || !length) {
4629 params->func(conn, att_err_from_int(err), params, NULL, 0);
4630 return;
4631 }
4632
4633 if (!params->handle_count) {
4634 parse_read_by_uuid(conn, params, pdu, length);
4635 return;
4636 }
4637
4638 if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) {
4639 return;
4640 }
4641
4642 /*
4643 * Core Spec 4.2, Vol. 3, Part G, 4.8.1
4644 * If the Characteristic Value is greater than (ATT_MTU - 1) octets
4645 * in length, the Read Long Characteristic Value procedure may be used
4646 * if the rest of the Characteristic Value is required.
4647 *
4648 * Note: Both BT_ATT_OP_READ_RSP and BT_ATT_OP_READ_BLOB_RSP
4649 * have an overhead of one octet.
4650 */
4651 if (length < (params->_att_mtu - 1)) {
4652 params->func(conn, 0, params, NULL, 0);
4653 return;
4654 }
4655
4656 params->single.offset += length;
4657
4658 /* Continue reading the attribute */
4659 if (bt_gatt_read(conn, params) < 0) {
4660 params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
4661 }
4662 }
4663
gatt_read_blob_encode(struct net_buf * buf,size_t len,void * user_data)4664 static int gatt_read_blob_encode(struct net_buf *buf, size_t len,
4665 void *user_data)
4666 {
4667 struct bt_gatt_read_params *params = user_data;
4668 struct bt_att_read_blob_req *req;
4669
4670 req = net_buf_add(buf, sizeof(*req));
4671 req->handle = sys_cpu_to_le16(params->single.handle);
4672 req->offset = sys_cpu_to_le16(params->single.offset);
4673
4674 return 0;
4675 }
4676
gatt_read_blob(struct bt_conn * conn,struct bt_gatt_read_params * params)4677 static int gatt_read_blob(struct bt_conn *conn,
4678 struct bt_gatt_read_params *params)
4679 {
4680 LOG_DBG("handle 0x%04x offset 0x%04x", params->single.handle, params->single.offset);
4681
4682 return gatt_req_send(conn, gatt_read_rsp, params,
4683 gatt_read_blob_encode, BT_ATT_OP_READ_BLOB_REQ,
4684 sizeof(struct bt_att_read_blob_req),
4685 BT_ATT_CHAN_OPT(params));
4686 }
4687
gatt_read_uuid_encode(struct net_buf * buf,size_t len,void * user_data)4688 static int gatt_read_uuid_encode(struct net_buf *buf, size_t len,
4689 void *user_data)
4690 {
4691 struct bt_gatt_read_params *params = user_data;
4692 struct bt_att_read_type_req *req;
4693
4694 req = net_buf_add(buf, sizeof(*req));
4695 req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle);
4696 req->end_handle = sys_cpu_to_le16(params->by_uuid.end_handle);
4697
4698 if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) {
4699 net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val);
4700 } else {
4701 net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16);
4702 }
4703
4704 return 0;
4705 }
4706
gatt_read_uuid(struct bt_conn * conn,struct bt_gatt_read_params * params)4707 static int gatt_read_uuid(struct bt_conn *conn,
4708 struct bt_gatt_read_params *params)
4709 {
4710 LOG_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", params->by_uuid.start_handle,
4711 params->by_uuid.end_handle, bt_uuid_str(params->by_uuid.uuid));
4712
4713 return gatt_req_send(conn, gatt_read_rsp, params,
4714 gatt_read_uuid_encode, BT_ATT_OP_READ_TYPE_REQ,
4715 sizeof(struct bt_att_read_type_req),
4716 BT_ATT_CHAN_OPT(params));
4717 }
4718
4719 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
gatt_read_mult_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4720 static void gatt_read_mult_rsp(struct bt_conn *conn, int err, const void *pdu,
4721 uint16_t length, void *user_data)
4722 {
4723 struct bt_gatt_read_params *params = user_data;
4724
4725 LOG_DBG("err %d", err);
4726
4727 if (err || !length) {
4728 params->func(conn, att_err_from_int(err), params, NULL, 0);
4729 return;
4730 }
4731
4732 params->func(conn, 0, params, pdu, length);
4733
4734 /* mark read as complete since read multiple is single response */
4735 params->func(conn, 0, params, NULL, 0);
4736 }
4737
gatt_read_mult_encode(struct net_buf * buf,size_t len,void * user_data)4738 static int gatt_read_mult_encode(struct net_buf *buf, size_t len,
4739 void *user_data)
4740 {
4741 struct bt_gatt_read_params *params = user_data;
4742 uint8_t i;
4743
4744 for (i = 0U; i < params->handle_count; i++) {
4745 net_buf_add_le16(buf, params->multiple.handles[i]);
4746 }
4747
4748 return 0;
4749 }
4750
gatt_read_mult(struct bt_conn * conn,struct bt_gatt_read_params * params)4751 static int gatt_read_mult(struct bt_conn *conn,
4752 struct bt_gatt_read_params *params)
4753 {
4754 LOG_DBG("handle_count %zu", params->handle_count);
4755
4756 return gatt_req_send(conn, gatt_read_mult_rsp, params,
4757 gatt_read_mult_encode, BT_ATT_OP_READ_MULT_REQ,
4758 params->handle_count * sizeof(uint16_t),
4759 BT_ATT_CHAN_OPT(params));
4760 }
4761
4762 #else
gatt_read_mult(struct bt_conn * conn,struct bt_gatt_read_params * params)4763 static int gatt_read_mult(struct bt_conn *conn,
4764 struct bt_gatt_read_params *params)
4765 {
4766 return -ENOTSUP;
4767 }
4768 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
4769
4770 #if defined(CONFIG_BT_GATT_READ_MULT_VAR_LEN)
gatt_read_mult_vl_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4771 static void gatt_read_mult_vl_rsp(struct bt_conn *conn, int err,
4772 const void *pdu, uint16_t length,
4773 void *user_data)
4774 {
4775 struct bt_gatt_read_params *params = user_data;
4776 const struct bt_att_read_mult_vl_rsp *rsp;
4777 struct net_buf_simple buf;
4778
4779 LOG_DBG("err %d", err);
4780
4781 if (err || !length) {
4782 params->func(conn, att_err_from_int(err), params, NULL, 0);
4783 return;
4784 }
4785
4786 net_buf_simple_init_with_data(&buf, (void *)pdu, length);
4787
4788 while (buf.len >= sizeof(*rsp)) {
4789 uint16_t len;
4790
4791 rsp = net_buf_simple_pull_mem(&buf, sizeof(*rsp));
4792 len = sys_le16_to_cpu(rsp->len);
4793
4794 /* If a Length Value Tuple is truncated, then the amount of
4795 * Attribute Value will be less than the value of the Value
4796 * Length field.
4797 */
4798 if (len > buf.len) {
4799 len = buf.len;
4800 }
4801
4802 params->func(conn, 0, params, rsp->value, len);
4803
4804 net_buf_simple_pull_mem(&buf, len);
4805 }
4806
4807 /* mark read as complete since read multiple is single response */
4808 params->func(conn, 0, params, NULL, 0);
4809 }
4810
gatt_read_mult_vl_encode(struct net_buf * buf,size_t len,void * user_data)4811 static int gatt_read_mult_vl_encode(struct net_buf *buf, size_t len,
4812 void *user_data)
4813 {
4814 struct bt_gatt_read_params *params = user_data;
4815 uint8_t i;
4816
4817 for (i = 0U; i < params->handle_count; i++) {
4818 net_buf_add_le16(buf, params->multiple.handles[i]);
4819 }
4820
4821 return 0;
4822 }
4823
gatt_read_mult_vl(struct bt_conn * conn,struct bt_gatt_read_params * params)4824 static int gatt_read_mult_vl(struct bt_conn *conn,
4825 struct bt_gatt_read_params *params)
4826 {
4827 LOG_DBG("handle_count %zu", params->handle_count);
4828
4829 return gatt_req_send(conn, gatt_read_mult_vl_rsp, params,
4830 gatt_read_mult_vl_encode,
4831 BT_ATT_OP_READ_MULT_VL_REQ,
4832 params->handle_count * sizeof(uint16_t),
4833 BT_ATT_CHAN_OPT(params));
4834 }
4835
4836 #else
gatt_read_mult_vl(struct bt_conn * conn,struct bt_gatt_read_params * params)4837 static int gatt_read_mult_vl(struct bt_conn *conn,
4838 struct bt_gatt_read_params *params)
4839 {
4840 return -ENOTSUP;
4841 }
4842 #endif /* CONFIG_BT_GATT_READ_MULT_VAR_LEN */
4843
gatt_read_encode(struct net_buf * buf,size_t len,void * user_data)4844 static int gatt_read_encode(struct net_buf *buf, size_t len, void *user_data)
4845 {
4846 struct bt_gatt_read_params *params = user_data;
4847 struct bt_att_read_req *req;
4848
4849 req = net_buf_add(buf, sizeof(*req));
4850 req->handle = sys_cpu_to_le16(params->single.handle);
4851
4852 return 0;
4853 }
4854
bt_gatt_read(struct bt_conn * conn,struct bt_gatt_read_params * params)4855 int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params)
4856 {
4857 __ASSERT(conn, "invalid parameters\n");
4858 __ASSERT(params && params->func, "invalid parameters\n");
4859
4860 if (conn->state != BT_CONN_CONNECTED) {
4861 return -ENOTCONN;
4862 }
4863
4864 if (params->handle_count == 0) {
4865 return gatt_read_uuid(conn, params);
4866 }
4867
4868 if (params->handle_count > 1) {
4869 if (params->multiple.variable) {
4870 return gatt_read_mult_vl(conn, params);
4871 } else {
4872 return gatt_read_mult(conn, params);
4873 }
4874 }
4875
4876 if (params->single.offset) {
4877 return gatt_read_blob(conn, params);
4878 }
4879
4880 LOG_DBG("handle 0x%04x", params->single.handle);
4881
4882 return gatt_req_send(conn, gatt_read_rsp, params, gatt_read_encode,
4883 BT_ATT_OP_READ_REQ, sizeof(struct bt_att_read_req),
4884 BT_ATT_CHAN_OPT(params));
4885 }
4886
gatt_write_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4887 static void gatt_write_rsp(struct bt_conn *conn, int err, const void *pdu,
4888 uint16_t length, void *user_data)
4889 {
4890 struct bt_gatt_write_params *params = user_data;
4891
4892 LOG_DBG("err %d", err);
4893
4894 params->func(conn, att_err_from_int(err), params);
4895 }
4896
bt_gatt_write_without_response_cb(struct bt_conn * conn,uint16_t handle,const void * data,uint16_t length,bool sign,bt_gatt_complete_func_t func,void * user_data)4897 int bt_gatt_write_without_response_cb(struct bt_conn *conn, uint16_t handle,
4898 const void *data, uint16_t length, bool sign,
4899 bt_gatt_complete_func_t func,
4900 void *user_data)
4901 {
4902 struct net_buf *buf;
4903 struct bt_att_write_cmd *cmd;
4904 size_t write;
4905
4906 __ASSERT(conn, "invalid parameters\n");
4907 __ASSERT(handle, "invalid parameters\n");
4908
4909 if (conn->state != BT_CONN_CONNECTED) {
4910 return -ENOTCONN;
4911 }
4912
4913 #if defined(CONFIG_BT_SMP)
4914 if (conn->encrypt) {
4915 /* Don't need to sign if already encrypted */
4916 sign = false;
4917 }
4918 #endif
4919
4920 if (sign) {
4921 buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD,
4922 sizeof(*cmd) + length + 12);
4923 } else {
4924 buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD,
4925 sizeof(*cmd) + length);
4926 }
4927 if (!buf) {
4928 return -ENOMEM;
4929 }
4930
4931 cmd = net_buf_add(buf, sizeof(*cmd));
4932 cmd->handle = sys_cpu_to_le16(handle);
4933
4934 write = net_buf_append_bytes(buf, length, data, K_NO_WAIT, NULL, NULL);
4935 if (write != length) {
4936 LOG_WRN("Unable to allocate length %u: only %zu written", length, write);
4937 net_buf_unref(buf);
4938 return -ENOMEM;
4939 }
4940
4941 LOG_DBG("handle 0x%04x length %u", handle, length);
4942
4943 bt_att_set_tx_meta_data(buf, func, user_data, BT_ATT_CHAN_OPT_NONE);
4944
4945 return bt_att_send(conn, buf);
4946 }
4947
gatt_exec_encode(struct net_buf * buf,size_t len,void * user_data)4948 static int gatt_exec_encode(struct net_buf *buf, size_t len, void *user_data)
4949 {
4950 struct bt_att_exec_write_req *req;
4951
4952 req = net_buf_add(buf, sizeof(*req));
4953 req->flags = BT_ATT_FLAG_EXEC;
4954
4955 return 0;
4956 }
4957
gatt_exec_write(struct bt_conn * conn,struct bt_gatt_write_params * params)4958 static int gatt_exec_write(struct bt_conn *conn,
4959 struct bt_gatt_write_params *params)
4960 {
4961 LOG_DBG("");
4962
4963 return gatt_req_send(conn, gatt_write_rsp, params, gatt_exec_encode,
4964 BT_ATT_OP_EXEC_WRITE_REQ,
4965 sizeof(struct bt_att_exec_write_req),
4966 BT_ATT_CHAN_OPT(params));
4967 }
4968
gatt_cancel_encode(struct net_buf * buf,size_t len,void * user_data)4969 static int gatt_cancel_encode(struct net_buf *buf, size_t len, void *user_data)
4970 {
4971 struct bt_att_exec_write_req *req;
4972
4973 req = net_buf_add(buf, sizeof(*req));
4974 req->flags = BT_ATT_FLAG_CANCEL;
4975
4976 return 0;
4977 }
4978
gatt_cancel_all_writes(struct bt_conn * conn,struct bt_gatt_write_params * params)4979 static int gatt_cancel_all_writes(struct bt_conn *conn,
4980 struct bt_gatt_write_params *params)
4981 {
4982 LOG_DBG("");
4983
4984 return gatt_req_send(conn, gatt_write_rsp, params, gatt_cancel_encode,
4985 BT_ATT_OP_EXEC_WRITE_REQ,
4986 sizeof(struct bt_att_exec_write_req),
4987 BT_ATT_CHAN_OPT(params));
4988 }
4989
gatt_prepare_write_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)4990 static void gatt_prepare_write_rsp(struct bt_conn *conn, int err,
4991 const void *pdu, uint16_t length,
4992 void *user_data)
4993 {
4994 struct bt_gatt_write_params *params = user_data;
4995 const struct bt_att_prepare_write_rsp *rsp = pdu;
4996 size_t len;
4997 bool data_valid;
4998
4999 LOG_DBG("err %d", err);
5000
5001 /* Don't continue in case of error */
5002 if (err) {
5003 params->func(conn, att_err_from_int(err), params);
5004 return;
5005 }
5006
5007 len = length - sizeof(*rsp);
5008 if (len > params->length) {
5009 LOG_ERR("Incorrect length, canceling write");
5010 if (gatt_cancel_all_writes(conn, params)) {
5011 goto fail;
5012 }
5013
5014 return;
5015 }
5016
5017 data_valid = memcmp(params->data, rsp->value, len) == 0;
5018 if (params->offset != rsp->offset || !data_valid) {
5019 LOG_ERR("Incorrect offset or data in response, canceling write");
5020 if (gatt_cancel_all_writes(conn, params)) {
5021 goto fail;
5022 }
5023
5024 return;
5025 }
5026
5027 /* Update params */
5028 params->offset += len;
5029 params->data = (const uint8_t *)params->data + len;
5030 params->length -= len;
5031
5032 /* If there is no more data execute */
5033 if (!params->length) {
5034 if (gatt_exec_write(conn, params)) {
5035 goto fail;
5036 }
5037
5038 return;
5039 }
5040
5041 /* Write next chunk */
5042 if (!bt_gatt_write(conn, params)) {
5043 /* Success */
5044 return;
5045 }
5046
5047 fail:
5048 /* Notify application that the write operation has failed */
5049 params->func(conn, BT_ATT_ERR_UNLIKELY, params);
5050 }
5051
gatt_prepare_write_encode(struct net_buf * buf,size_t len,void * user_data)5052 static int gatt_prepare_write_encode(struct net_buf *buf, size_t len,
5053 void *user_data)
5054 {
5055 struct bt_gatt_write_params *params = user_data;
5056 struct bt_att_prepare_write_req *req;
5057 size_t write;
5058
5059 req = net_buf_add(buf, sizeof(*req));
5060 req->handle = sys_cpu_to_le16(params->handle);
5061 req->offset = sys_cpu_to_le16(params->offset);
5062
5063 write = net_buf_append_bytes(buf, len - sizeof(*req),
5064 (uint8_t *)params->data, K_NO_WAIT, NULL,
5065 NULL);
5066 if (write != (len - sizeof(*req))) {
5067 return -ENOMEM;
5068 }
5069
5070 return 0;
5071 }
5072
gatt_prepare_write(struct bt_conn * conn,struct bt_gatt_write_params * params)5073 static int gatt_prepare_write(struct bt_conn *conn,
5074 struct bt_gatt_write_params *params)
5075 {
5076 uint16_t len, req_len;
5077
5078 req_len = sizeof(struct bt_att_prepare_write_req);
5079
5080 len = bt_att_get_mtu(conn) - req_len - 1;
5081 len = MIN(params->length, len);
5082 len += req_len;
5083
5084 return gatt_req_send(conn, gatt_prepare_write_rsp, params,
5085 gatt_prepare_write_encode,
5086 BT_ATT_OP_PREPARE_WRITE_REQ, len,
5087 BT_ATT_CHAN_OPT(params));
5088 }
5089
gatt_write_encode(struct net_buf * buf,size_t len,void * user_data)5090 static int gatt_write_encode(struct net_buf *buf, size_t len, void *user_data)
5091 {
5092 struct bt_gatt_write_params *params = user_data;
5093 struct bt_att_write_req *req;
5094 size_t write;
5095
5096 req = net_buf_add(buf, sizeof(*req));
5097 req->handle = sys_cpu_to_le16(params->handle);
5098
5099 write = net_buf_append_bytes(buf, params->length, params->data,
5100 K_NO_WAIT, NULL, NULL);
5101 if (write != params->length) {
5102 return -ENOMEM;
5103 }
5104
5105 return 0;
5106 }
5107
bt_gatt_write(struct bt_conn * conn,struct bt_gatt_write_params * params)5108 int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params)
5109 {
5110 size_t len;
5111
5112 __ASSERT(conn, "invalid parameters\n");
5113 __ASSERT(params && params->func, "invalid parameters\n");
5114 __ASSERT(params->handle, "invalid parameters\n");
5115
5116 if (conn->state != BT_CONN_CONNECTED) {
5117 return -ENOTCONN;
5118 }
5119
5120 len = sizeof(struct bt_att_write_req) + params->length;
5121
5122 /* Use Prepare Write if offset is set or Long Write is required */
5123 if (params->offset || len > (bt_att_get_mtu(conn) - 1)) {
5124 return gatt_prepare_write(conn, params);
5125 }
5126
5127 LOG_DBG("handle 0x%04x length %u", params->handle, params->length);
5128
5129 return gatt_req_send(conn, gatt_write_rsp, params, gatt_write_encode,
5130 BT_ATT_OP_WRITE_REQ, len, BT_ATT_CHAN_OPT(params));
5131 }
5132
gatt_write_ccc_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)5133 static void gatt_write_ccc_rsp(struct bt_conn *conn, int err,
5134 const void *pdu, uint16_t length,
5135 void *user_data)
5136 {
5137 struct bt_gatt_subscribe_params *params = user_data;
5138 uint8_t att_err;
5139
5140 LOG_DBG("err %d", err);
5141
5142 atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
5143
5144 /* if write to CCC failed we remove subscription and notify app */
5145 if (err) {
5146 struct gatt_sub *sub;
5147 sys_snode_t *node, *tmp, *prev;
5148
5149 sub = gatt_sub_find(conn);
5150 if (!sub) {
5151 return;
5152 }
5153
5154 prev = NULL;
5155
5156 SYS_SLIST_FOR_EACH_NODE_SAFE(&sub->list, node, tmp) {
5157 if (node == ¶ms->node) {
5158 gatt_sub_remove(conn, sub, prev, params);
5159 break;
5160 }
5161 prev = node;
5162 }
5163 } else if (!params->value) {
5164 /* Notify with NULL data to complete unsubscribe */
5165 params->notify(conn, params, NULL, 0);
5166 }
5167
5168 att_err = att_err_from_int(err);
5169
5170 if (params->subscribe) {
5171 params->subscribe(conn, att_err, params);
5172 } else if (params->write) {
5173 /* TODO: Remove after deprecation */
5174 LOG_WRN("write callback is deprecated, use subscribe cb instead");
5175 params->write(conn, att_err, NULL);
5176 }
5177 }
5178
5179
gatt_write_ccc_buf(struct net_buf * buf,size_t len,void * user_data)5180 static int gatt_write_ccc_buf(struct net_buf *buf, size_t len, void *user_data)
5181 {
5182 struct bt_gatt_subscribe_params *params = user_data;
5183 struct bt_att_write_req *write_req;
5184
5185 write_req = net_buf_add(buf, sizeof(*write_req));
5186 write_req->handle = sys_cpu_to_le16(params->ccc_handle);
5187 net_buf_add_le16(buf, params->value);
5188
5189 atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
5190
5191 return 0;
5192 }
5193
gatt_write_ccc(struct bt_conn * conn,struct bt_gatt_subscribe_params * params,bt_att_func_t rsp)5194 static int gatt_write_ccc(struct bt_conn *conn,
5195 struct bt_gatt_subscribe_params *params,
5196 bt_att_func_t rsp)
5197 {
5198 size_t len = sizeof(struct bt_att_write_req) + sizeof(uint16_t);
5199
5200 LOG_DBG("handle 0x%04x value 0x%04x", params->ccc_handle, params->value);
5201
5202 /* The value of the params doesn't matter, this is just so we don't
5203 * repeat CCC writes when the AUTO_RESUBSCRIBE quirk is enabled.
5204 */
5205 atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_SENT);
5206
5207 return gatt_req_send(conn, rsp, params,
5208 gatt_write_ccc_buf, BT_ATT_OP_WRITE_REQ, len,
5209 BT_ATT_CHAN_OPT(params));
5210 }
5211
5212 #if defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC)
gatt_ccc_discover_cb(struct bt_conn * conn,const struct bt_gatt_attr * attr,struct bt_gatt_discover_params * params)5213 static uint8_t gatt_ccc_discover_cb(struct bt_conn *conn,
5214 const struct bt_gatt_attr *attr,
5215 struct bt_gatt_discover_params *params)
5216 {
5217 struct bt_gatt_subscribe_params *sub_params = params->sub_params;
5218
5219 if (!attr) {
5220 memset(params, 0, sizeof(*params));
5221 sub_params->notify(conn, sub_params, NULL, 0);
5222 return BT_GATT_ITER_STOP;
5223 }
5224
5225 if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) {
5226 memset(params, 0, sizeof(*params));
5227 sub_params->ccc_handle = attr->handle;
5228
5229 if (bt_gatt_subscribe(conn, sub_params)) {
5230 sub_params->notify(conn, sub_params, NULL, 0);
5231 }
5232 /* else if no error occurred, then `bt_gatt_subscribe` will
5233 * call the notify function once subscribed.
5234 */
5235
5236 return BT_GATT_ITER_STOP;
5237 }
5238
5239 return BT_GATT_ITER_CONTINUE;
5240 }
5241
gatt_ccc_discover(struct bt_conn * conn,struct bt_gatt_subscribe_params * params)5242 static int gatt_ccc_discover(struct bt_conn *conn,
5243 struct bt_gatt_subscribe_params *params)
5244 {
5245 int err;
5246 static struct bt_uuid_16 ccc_uuid = BT_UUID_INIT_16(0);
5247
5248 memcpy(&ccc_uuid, BT_UUID_GATT_CCC, sizeof(ccc_uuid));
5249 memset(params->disc_params, 0, sizeof(*params->disc_params));
5250
5251 params->disc_params->sub_params = params;
5252 params->disc_params->uuid = &ccc_uuid.uuid;
5253 params->disc_params->type = BT_GATT_DISCOVER_DESCRIPTOR;
5254 params->disc_params->start_handle = params->value_handle;
5255 params->disc_params->end_handle = params->end_handle;
5256 params->disc_params->func = gatt_ccc_discover_cb;
5257 #if defined(CONFIG_BT_EATT)
5258 params->disc_params->chan_opt = params->chan_opt;
5259 #endif /* CONFIG_BT_EATT */
5260
5261 err = bt_gatt_discover(conn, params->disc_params);
5262 if (err) {
5263 LOG_DBG("CCC Discovery failed (err %d)", err);
5264 return err;
5265 }
5266 return 0;
5267
5268 }
5269 #endif /* CONFIG_BT_GATT_AUTO_DISCOVER_CCC */
5270
bt_gatt_subscribe(struct bt_conn * conn,struct bt_gatt_subscribe_params * params)5271 int bt_gatt_subscribe(struct bt_conn *conn,
5272 struct bt_gatt_subscribe_params *params)
5273 {
5274 struct gatt_sub *sub;
5275 struct bt_gatt_subscribe_params *tmp;
5276 bool has_subscription = false;
5277
5278 __ASSERT(conn, "invalid parameters\n");
5279 __ASSERT(params && params->notify, "invalid parameters\n");
5280 __ASSERT(params->value, "invalid parameters\n");
5281 #if defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC)
5282 __ASSERT(params->ccc_handle ||
5283 (params->end_handle && params->disc_params),
5284 "invalid parameters\n");
5285 #else
5286 __ASSERT(params->ccc_handle, "invalid parameters\n");
5287 #endif
5288
5289 if (conn->state != BT_CONN_CONNECTED) {
5290 return -ENOTCONN;
5291 }
5292
5293 sub = gatt_sub_add(conn);
5294 if (!sub) {
5295 return -ENOMEM;
5296 }
5297
5298 #if defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC)
5299 if (params->disc_params != NULL && params->disc_params->func == gatt_ccc_discover_cb) {
5300 /* Already in progress */
5301 return -EBUSY;
5302 }
5303 #endif
5304
5305 /* Lookup existing subscriptions */
5306 SYS_SLIST_FOR_EACH_CONTAINER(&sub->list, tmp, node) {
5307 /* Fail if entry already exists */
5308 if (tmp == params) {
5309 gatt_sub_remove(conn, sub, NULL, NULL);
5310 return -EALREADY;
5311 }
5312
5313 /* Check if another subscription exists */
5314 if (tmp->value_handle == params->value_handle &&
5315 tmp->value >= params->value) {
5316 has_subscription = true;
5317 }
5318 }
5319
5320 /* Skip write if already subscribed */
5321 if (!has_subscription) {
5322 int err;
5323
5324 #if defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC)
5325 if (!params->ccc_handle) {
5326 return gatt_ccc_discover(conn, params);
5327 }
5328 #endif
5329 err = gatt_write_ccc(conn, params, gatt_write_ccc_rsp);
5330 if (err) {
5331 gatt_sub_remove(conn, sub, NULL, NULL);
5332 return err;
5333 }
5334 }
5335
5336 /*
5337 * Add subscription before write complete as some implementation were
5338 * reported to send notification before reply to CCC write.
5339 */
5340 sys_slist_prepend(&sub->list, ¶ms->node);
5341
5342 return 0;
5343 }
5344
bt_gatt_resubscribe(uint8_t id,const bt_addr_le_t * peer,struct bt_gatt_subscribe_params * params)5345 int bt_gatt_resubscribe(uint8_t id, const bt_addr_le_t *peer,
5346 struct bt_gatt_subscribe_params *params)
5347 {
5348 struct gatt_sub *sub;
5349 struct bt_gatt_subscribe_params *tmp;
5350
5351 __ASSERT(params && params->notify, "invalid parameters\n");
5352 __ASSERT(params->value, "invalid parameters\n");
5353 __ASSERT(params->ccc_handle, "invalid parameters\n");
5354
5355 sub = gatt_sub_add_by_addr(id, peer);
5356 if (!sub) {
5357 return -ENOMEM;
5358 }
5359
5360 /* Lookup existing subscriptions */
5361 SYS_SLIST_FOR_EACH_CONTAINER(&sub->list, tmp, node) {
5362 /* Fail if entry already exists */
5363 if (tmp == params) {
5364 gatt_sub_remove(NULL, sub, NULL, NULL);
5365 return -EALREADY;
5366 }
5367 }
5368
5369 sys_slist_prepend(&sub->list, ¶ms->node);
5370 return 0;
5371 }
5372
bt_gatt_unsubscribe(struct bt_conn * conn,struct bt_gatt_subscribe_params * params)5373 int bt_gatt_unsubscribe(struct bt_conn *conn,
5374 struct bt_gatt_subscribe_params *params)
5375 {
5376 struct gatt_sub *sub;
5377 struct bt_gatt_subscribe_params *tmp;
5378 bool has_subscription = false, found = false;
5379
5380 __ASSERT(conn, "invalid parameters\n");
5381 __ASSERT(params, "invalid parameters\n");
5382
5383 if (conn->state != BT_CONN_CONNECTED) {
5384 return -ENOTCONN;
5385 }
5386
5387 sub = gatt_sub_find(conn);
5388 if (!sub) {
5389 return -EINVAL;
5390 }
5391
5392 /* Lookup existing subscriptions */
5393 SYS_SLIST_FOR_EACH_CONTAINER(&sub->list, tmp, node) {
5394 if (params == tmp) {
5395 found = true;
5396 continue;
5397 }
5398
5399 /* Check if there still remains any other subscription */
5400 if (tmp->value_handle == params->value_handle) {
5401 has_subscription = true;
5402 }
5403 }
5404
5405 if (!found) {
5406 return -EINVAL;
5407 }
5408
5409 /* Attempt to cancel if write is pending */
5410 if (atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) {
5411 bt_gatt_cancel(conn, params);
5412 }
5413
5414 if (!has_subscription) {
5415 int err;
5416
5417 params->value = 0x0000;
5418 err = gatt_write_ccc(conn, params, gatt_write_ccc_rsp);
5419 if (err) {
5420 return err;
5421 }
5422 }
5423
5424 sys_slist_find_and_remove(&sub->list, ¶ms->node);
5425
5426 if (gatt_sub_is_empty(sub)) {
5427 gatt_sub_free(sub);
5428 }
5429
5430 if (has_subscription) {
5431 /* Notify with NULL data to complete unsubscribe */
5432 params->notify(conn, params, NULL, 0);
5433 }
5434
5435 return 0;
5436 }
5437
bt_gatt_cancel(struct bt_conn * conn,void * params)5438 void bt_gatt_cancel(struct bt_conn *conn, void *params)
5439 {
5440 struct bt_att_req *req;
5441 bt_att_func_t func = NULL;
5442
5443 k_sched_lock();
5444
5445 req = bt_att_find_req_by_user_data(conn, params);
5446 if (req) {
5447 func = req->func;
5448 bt_att_req_cancel(conn, req);
5449 }
5450
5451 k_sched_unlock();
5452
5453 if (func) {
5454 func(conn, BT_ATT_ERR_UNLIKELY, NULL, 0, params);
5455 }
5456 }
5457
5458 #if defined(CONFIG_BT_GATT_AUTO_RESUBSCRIBE)
gatt_resub_ccc_rsp(struct bt_conn * conn,int err,const void * pdu,uint16_t length,void * user_data)5459 static void gatt_resub_ccc_rsp(struct bt_conn *conn, int err,
5460 const void *pdu, uint16_t length,
5461 void *user_data)
5462 {
5463 LOG_DBG("err %d", err);
5464
5465 if (err == -ECONNRESET) {
5466 /* The resubscriptions are implicit, thus in the case of ACL
5467 * disconnection during the CCC value ATT Write, there is no
5468 * need to notify the application.
5469 */
5470 return;
5471 }
5472
5473 gatt_write_ccc_rsp(conn, err, pdu, length, user_data);
5474 }
5475
gatt_resub_ccc(struct bt_conn * conn,struct bt_gatt_subscribe_params * params)5476 static int gatt_resub_ccc(struct bt_conn *conn,
5477 struct bt_gatt_subscribe_params *params)
5478 {
5479 return gatt_write_ccc(conn, params, gatt_resub_ccc_rsp);
5480 }
5481
add_subscriptions(struct bt_conn * conn)5482 static void add_subscriptions(struct bt_conn *conn)
5483 {
5484 struct gatt_sub *sub;
5485 struct bt_gatt_subscribe_params *params;
5486
5487 if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
5488 return;
5489 }
5490
5491 sub = gatt_sub_find(conn);
5492 if (!sub) {
5493 return;
5494 }
5495
5496 /* Lookup existing subscriptions */
5497 SYS_SLIST_FOR_EACH_CONTAINER(&sub->list, params, node) {
5498 if (!atomic_test_bit(params->flags,
5499 BT_GATT_SUBSCRIBE_FLAG_SENT) &&
5500 !atomic_test_bit(params->flags,
5501 BT_GATT_SUBSCRIBE_FLAG_NO_RESUB)) {
5502 int err;
5503
5504 /* Force write to CCC to workaround devices that don't
5505 * track it properly.
5506 */
5507 err = gatt_resub_ccc(conn, params);
5508 if (err < 0) {
5509 LOG_WRN("conn %p params %p resub failed (err %d)",
5510 (void *)conn, params, err);
5511 }
5512 }
5513 }
5514 }
5515 #endif /* CONFIG_BT_GATT_AUTO_RESUBSCRIBE */
5516
5517 #if defined(CONFIG_BT_GATT_AUTO_UPDATE_MTU)
gatt_exchange_mtu_func(struct bt_conn * conn,uint8_t err,struct bt_gatt_exchange_params * params)5518 static void gatt_exchange_mtu_func(struct bt_conn *conn, uint8_t err,
5519 struct bt_gatt_exchange_params *params)
5520 {
5521 if (err) {
5522 LOG_WRN("conn %p err 0x%02x", conn, err);
5523 }
5524 }
5525
5526 static struct bt_gatt_exchange_params gatt_exchange_params = {
5527 .func = gatt_exchange_mtu_func,
5528 };
5529 #endif /* CONFIG_BT_GATT_AUTO_UPDATE_MTU */
5530 #endif /* CONFIG_BT_GATT_CLIENT */
5531
5532 #define CCC_STORE_MAX 48
5533
ccc_find_cfg(struct _bt_gatt_ccc * ccc,const bt_addr_le_t * addr,uint8_t id)5534 static struct bt_gatt_ccc_cfg *ccc_find_cfg(struct _bt_gatt_ccc *ccc,
5535 const bt_addr_le_t *addr,
5536 uint8_t id)
5537 {
5538 for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
5539 if (id == ccc->cfg[i].id &&
5540 bt_addr_le_eq(&ccc->cfg[i].peer, addr)) {
5541 return &ccc->cfg[i];
5542 }
5543 }
5544
5545 return NULL;
5546 }
5547
5548 struct addr_with_id {
5549 const bt_addr_le_t *addr;
5550 uint8_t id;
5551 };
5552
5553 struct ccc_load {
5554 struct addr_with_id addr_with_id;
5555 struct ccc_store *entry;
5556 size_t count;
5557 };
5558
ccc_clear(struct _bt_gatt_ccc * ccc,const bt_addr_le_t * addr,uint8_t id)5559 static void ccc_clear(struct _bt_gatt_ccc *ccc,
5560 const bt_addr_le_t *addr,
5561 uint8_t id)
5562 {
5563 struct bt_gatt_ccc_cfg *cfg;
5564
5565 cfg = ccc_find_cfg(ccc, addr, id);
5566 if (!cfg) {
5567 LOG_DBG("Unable to clear CCC: cfg not found");
5568 return;
5569 }
5570
5571 clear_ccc_cfg(cfg);
5572 }
5573
ccc_load(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)5574 static uint8_t ccc_load(const struct bt_gatt_attr *attr, uint16_t handle,
5575 void *user_data)
5576 {
5577 struct ccc_load *load = user_data;
5578 struct _bt_gatt_ccc *ccc;
5579 struct bt_gatt_ccc_cfg *cfg;
5580
5581 /* Check if attribute is a CCC */
5582 if (attr->write != bt_gatt_attr_write_ccc) {
5583 return BT_GATT_ITER_CONTINUE;
5584 }
5585
5586 ccc = attr->user_data;
5587
5588 /* Clear if value was invalidated */
5589 if (!load->entry) {
5590 ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id);
5591 return BT_GATT_ITER_CONTINUE;
5592 } else if (!load->count) {
5593 return BT_GATT_ITER_STOP;
5594 }
5595
5596 /* Skip if value is not for the given attribute */
5597 if (load->entry->handle != handle) {
5598 /* If attribute handle is bigger then it means
5599 * the attribute no longer exists and cannot
5600 * be restored.
5601 */
5602 if (load->entry->handle < handle) {
5603 LOG_DBG("Unable to restore CCC: handle 0x%04x cannot be"
5604 " found", load->entry->handle);
5605 goto next;
5606 }
5607 return BT_GATT_ITER_CONTINUE;
5608 }
5609
5610 LOG_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle,
5611 load->entry->value);
5612
5613 cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id);
5614 if (!cfg) {
5615 cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0);
5616 if (!cfg) {
5617 LOG_DBG("Unable to restore CCC: no cfg left");
5618 goto next;
5619 }
5620 bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr);
5621 cfg->id = load->addr_with_id.id;
5622 }
5623
5624 cfg->value = load->entry->value;
5625
5626 next:
5627 load->entry++;
5628 load->count--;
5629
5630 return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP;
5631 }
5632
ccc_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)5633 static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb,
5634 void *cb_arg)
5635 {
5636 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
5637 struct ccc_store ccc_store[CCC_STORE_MAX];
5638 struct ccc_load load;
5639 bt_addr_le_t addr;
5640 ssize_t len;
5641 int err;
5642 const char *next;
5643
5644 settings_name_next(name, &next);
5645
5646 if (!name) {
5647 LOG_ERR("Insufficient number of arguments");
5648 return -EINVAL;
5649 } else if (!next) {
5650 load.addr_with_id.id = BT_ID_DEFAULT;
5651 } else {
5652 unsigned long next_id = strtoul(next, NULL, 10);
5653
5654 if (next_id >= CONFIG_BT_ID_MAX) {
5655 LOG_ERR("Invalid local identity %lu", next_id);
5656 return -EINVAL;
5657 }
5658
5659 load.addr_with_id.id = (uint8_t)next_id;
5660 }
5661
5662 err = bt_settings_decode_key(name, &addr);
5663 if (err) {
5664 LOG_ERR("Unable to decode address %s", name);
5665 return -EINVAL;
5666 }
5667
5668 load.addr_with_id.addr = &addr;
5669
5670 if (len_rd) {
5671 len = read_cb(cb_arg, ccc_store, sizeof(ccc_store));
5672
5673 if (len < 0) {
5674 LOG_ERR("Failed to decode value (err %zd)", len);
5675 return len;
5676 }
5677
5678 load.entry = ccc_store;
5679 load.count = len / sizeof(*ccc_store);
5680
5681 for (size_t i = 0; i < load.count; i++) {
5682 LOG_DBG("Read CCC: handle 0x%04x value 0x%04x", ccc_store[i].handle,
5683 ccc_store[i].value);
5684 }
5685 } else {
5686 load.entry = NULL;
5687 load.count = 0;
5688 }
5689
5690 bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load);
5691
5692 LOG_DBG("Restored CCC for id:%" PRIu8 " addr:%s", load.addr_with_id.id,
5693 bt_addr_le_str(load.addr_with_id.addr));
5694 }
5695
5696 return 0;
5697 }
5698
ccc_set_cb(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)5699 static int ccc_set_cb(const char *name, size_t len_rd, settings_read_cb read_cb,
5700 void *cb_arg)
5701 {
5702 if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING)) {
5703 /* Only load CCCs on demand */
5704 return 0;
5705 }
5706
5707 return ccc_set(name, len_rd, read_cb, cb_arg);
5708 }
5709
5710 BT_SETTINGS_DEFINE(ccc, "ccc", ccc_set_cb, NULL);
5711
ccc_set_direct(const char * key,size_t len,settings_read_cb read_cb,void * cb_arg,void * param)5712 static int ccc_set_direct(const char *key, size_t len, settings_read_cb read_cb,
5713 void *cb_arg, void *param)
5714 {
5715 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
5716 const char *name;
5717
5718 LOG_DBG("key: %s", (const char *)param);
5719
5720 /* Only "bt/ccc" settings should ever come here */
5721 if (!settings_name_steq((const char *)param, "bt/ccc", &name)) {
5722 LOG_ERR("Invalid key");
5723 return -EINVAL;
5724 }
5725
5726 return ccc_set(name, len, read_cb, cb_arg);
5727 }
5728 return 0;
5729 }
5730
bt_gatt_connected(struct bt_conn * conn)5731 void bt_gatt_connected(struct bt_conn *conn)
5732 {
5733 struct conn_data data;
5734
5735 LOG_DBG("conn %p", conn);
5736
5737 data.conn = conn;
5738 data.sec = BT_SECURITY_L1;
5739
5740 /* Load CCC settings from backend if bonded */
5741 if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) &&
5742 bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
5743 char key[BT_SETTINGS_KEY_MAX];
5744
5745 if (conn->id) {
5746 char id_str[4];
5747
5748 u8_to_dec(id_str, sizeof(id_str), conn->id);
5749 bt_settings_encode_key(key, sizeof(key), "ccc",
5750 &conn->le.dst, id_str);
5751 } else {
5752 bt_settings_encode_key(key, sizeof(key), "ccc",
5753 &conn->le.dst, NULL);
5754 }
5755
5756 settings_load_subtree_direct(key, ccc_set_direct, (void *)key);
5757 }
5758
5759 bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
5760
5761 /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192:
5762 *
5763 * 10.3.1.1 Handling of GATT indications and notifications
5764 *
5765 * A client “requests” a server to send indications and notifications
5766 * by appropriately configuring the server via a Client Characteristic
5767 * Configuration Descriptor. Since the configuration is persistent
5768 * across a disconnection and reconnection, security requirements must
5769 * be checked against the configuration upon a reconnection before
5770 * sending indications or notifications. When a server reconnects to a
5771 * client to send an indication or notification for which security is
5772 * required, the server shall initiate or request encryption with the
5773 * client prior to sending an indication or notification. If the client
5774 * does not have an LTK indicating that the client has lost the bond,
5775 * enabling encryption will fail.
5776 */
5777 if (IS_ENABLED(CONFIG_BT_SMP) &&
5778 (conn->role == BT_HCI_ROLE_CENTRAL ||
5779 IS_ENABLED(CONFIG_BT_GATT_AUTO_SEC_REQ)) &&
5780 bt_conn_get_security(conn) < data.sec) {
5781 int err = bt_conn_set_security(conn, data.sec);
5782
5783 if (err) {
5784 LOG_WRN("Failed to set security for bonded peer (%d)", err);
5785 }
5786 }
5787
5788 #if defined(CONFIG_BT_GATT_AUTO_UPDATE_MTU)
5789 int err;
5790
5791 err = bt_gatt_exchange_mtu(conn, &gatt_exchange_params);
5792 if (err) {
5793 LOG_WRN("MTU Exchange failed (err %d)", err);
5794 }
5795 #endif /* CONFIG_BT_GATT_AUTO_UPDATE_MTU */
5796 }
5797
bt_gatt_att_max_mtu_changed(struct bt_conn * conn,uint16_t tx,uint16_t rx)5798 void bt_gatt_att_max_mtu_changed(struct bt_conn *conn, uint16_t tx, uint16_t rx)
5799 {
5800 struct bt_gatt_cb *cb;
5801
5802 SYS_SLIST_FOR_EACH_CONTAINER(&callback_list, cb, node) {
5803 if (cb->att_mtu_updated) {
5804 cb->att_mtu_updated(conn, tx, rx);
5805 }
5806 }
5807 }
5808
bt_gatt_encrypt_change(struct bt_conn * conn)5809 void bt_gatt_encrypt_change(struct bt_conn *conn)
5810 {
5811 struct conn_data data;
5812
5813 LOG_DBG("conn %p", conn);
5814
5815 data.conn = conn;
5816 data.sec = BT_SECURITY_L1;
5817
5818 #if defined(CONFIG_BT_GATT_AUTO_RESUBSCRIBE)
5819 add_subscriptions(conn);
5820 #endif /* CONFIG_BT_GATT_AUTO_RESUBSCRIBE */
5821
5822 bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
5823
5824 if (!bt_gatt_change_aware(conn, false)) {
5825 /* Send a Service Changed indication if the current peer is
5826 * marked as change-unaware.
5827 */
5828 sc_indicate(0x0001, 0xffff);
5829 }
5830 }
5831
bt_gatt_change_aware(struct bt_conn * conn,bool req)5832 bool bt_gatt_change_aware(struct bt_conn *conn, bool req)
5833 {
5834 #if defined(CONFIG_BT_GATT_CACHING)
5835 struct gatt_cf_cfg *cfg;
5836
5837 cfg = find_cf_cfg(conn);
5838 if (!cfg || !CF_ROBUST_CACHING(cfg)) {
5839 return true;
5840 }
5841
5842 if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) {
5843 return true;
5844 }
5845
5846 /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
5847 * If a change-unaware client sends an ATT command, the server shall
5848 * ignore it.
5849 */
5850 if (!req) {
5851 return false;
5852 }
5853
5854 /* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 3, Part G page 1475:
5855 * 2.5.2.1 Robust Caching
5856 * A change-unaware connected client becomes change-aware when it reads
5857 * the Database Hash characteristic and then the server receives another
5858 * ATT request from the client.
5859 */
5860 if (atomic_test_and_clear_bit(cfg->flags, CF_DB_HASH_READ)) {
5861 bt_att_clear_out_of_sync_sent(conn);
5862 set_change_aware(cfg, true);
5863 return true;
5864 }
5865
5866 /* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 3, Part G page 1476:
5867 * 2.5.2.1 Robust Caching
5868 * ... a change-unaware connected client using exactly one ATT bearer
5869 * becomes change-aware when ...
5870 * The server sends the client a response with the Error Code parameter
5871 * set to Database Out Of Sync (0x12) and then the server receives
5872 * another ATT request from the client.
5873 */
5874 if (bt_att_fixed_chan_only(conn) && bt_att_out_of_sync_sent_on_fixed(conn)) {
5875 atomic_clear_bit(cfg->flags, CF_DB_HASH_READ);
5876 bt_att_clear_out_of_sync_sent(conn);
5877 set_change_aware(cfg, true);
5878 return true;
5879 }
5880
5881 return false;
5882 #else
5883 return true;
5884 #endif
5885 }
5886
find_cf_cfg_by_addr(uint8_t id,const bt_addr_le_t * addr)5887 static struct gatt_cf_cfg *find_cf_cfg_by_addr(uint8_t id,
5888 const bt_addr_le_t *addr)
5889 {
5890 if (IS_ENABLED(CONFIG_BT_GATT_CACHING)) {
5891 int i;
5892
5893 for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
5894 if (id == cf_cfg[i].id &&
5895 bt_addr_le_eq(addr, &cf_cfg[i].peer)) {
5896 return &cf_cfg[i];
5897 }
5898 }
5899 }
5900
5901 return NULL;
5902 }
5903
5904 #if defined(CONFIG_BT_SETTINGS)
5905
5906 struct ccc_save {
5907 struct addr_with_id addr_with_id;
5908 struct ccc_store store[CCC_STORE_MAX];
5909 size_t count;
5910 };
5911
ccc_save(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)5912 static uint8_t ccc_save(const struct bt_gatt_attr *attr, uint16_t handle,
5913 void *user_data)
5914 {
5915 struct ccc_save *save = user_data;
5916 struct _bt_gatt_ccc *ccc;
5917 struct bt_gatt_ccc_cfg *cfg;
5918
5919 /* Check if attribute is a CCC */
5920 if (attr->write != bt_gatt_attr_write_ccc) {
5921 return BT_GATT_ITER_CONTINUE;
5922 }
5923
5924 ccc = attr->user_data;
5925
5926 /* Check if there is a cfg for the peer */
5927 cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id);
5928 if (!cfg) {
5929 return BT_GATT_ITER_CONTINUE;
5930 }
5931
5932 LOG_DBG("Storing CCCs handle 0x%04x value 0x%04x", handle, cfg->value);
5933
5934 save->store[save->count].handle = handle;
5935 save->store[save->count].value = cfg->value;
5936 save->count++;
5937
5938 return BT_GATT_ITER_CONTINUE;
5939 }
5940
bt_gatt_store_ccc(uint8_t id,const bt_addr_le_t * addr)5941 int bt_gatt_store_ccc(uint8_t id, const bt_addr_le_t *addr)
5942 {
5943 struct ccc_save save;
5944 size_t len;
5945 char *str;
5946 int err;
5947
5948 save.addr_with_id.addr = addr;
5949 save.addr_with_id.id = id;
5950 save.count = 0;
5951
5952 bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save);
5953
5954 if (save.count) {
5955 str = (char *)save.store;
5956 len = save.count * sizeof(*save.store);
5957 } else {
5958 /* No entries to encode, just clear */
5959 str = NULL;
5960 len = 0;
5961 }
5962
5963 err = bt_settings_store_ccc(id, addr, str, len);
5964 if (err) {
5965 LOG_ERR("Failed to store CCCs (err %d)", err);
5966 return err;
5967 }
5968
5969 LOG_DBG("Stored CCCs for %s", bt_addr_le_str(addr));
5970 if (len) {
5971 for (size_t i = 0; i < save.count; i++) {
5972 LOG_DBG(" CCC: handle 0x%04x value 0x%04x", save.store[i].handle,
5973 save.store[i].value);
5974 }
5975 } else {
5976 LOG_DBG(" CCC: NULL");
5977 }
5978
5979 return 0;
5980 }
5981
5982 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
sc_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)5983 static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb,
5984 void *cb_arg)
5985 {
5986 struct gatt_sc_cfg *cfg;
5987 uint8_t id;
5988 bt_addr_le_t addr;
5989 ssize_t len;
5990 int err;
5991 const char *next;
5992
5993 if (!name) {
5994 LOG_ERR("Insufficient number of arguments");
5995 return -EINVAL;
5996 }
5997
5998 err = bt_settings_decode_key(name, &addr);
5999 if (err) {
6000 LOG_ERR("Unable to decode address %s", name);
6001 return -EINVAL;
6002 }
6003
6004 settings_name_next(name, &next);
6005
6006 if (!next) {
6007 id = BT_ID_DEFAULT;
6008 } else {
6009 unsigned long next_id = strtoul(next, NULL, 10);
6010
6011 if (next_id >= CONFIG_BT_ID_MAX) {
6012 LOG_ERR("Invalid local identity %lu", next_id);
6013 return -EINVAL;
6014 }
6015
6016 id = (uint8_t)next_id;
6017 }
6018
6019 cfg = find_sc_cfg(id, &addr);
6020 if (!cfg && len_rd) {
6021 /* Find and initialize a free sc_cfg entry */
6022 cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
6023 if (!cfg) {
6024 LOG_ERR("Unable to restore SC: no cfg left");
6025 return -ENOMEM;
6026 }
6027
6028 cfg->id = id;
6029 bt_addr_le_copy(&cfg->peer, &addr);
6030 }
6031
6032 if (len_rd) {
6033 len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data));
6034 if (len < 0) {
6035 LOG_ERR("Failed to decode value (err %zd)", len);
6036 return len;
6037 }
6038
6039 LOG_DBG("Read SC: len %zd", len);
6040
6041 LOG_DBG("Restored SC for %s", bt_addr_le_str(&addr));
6042 } else if (cfg) {
6043 /* Clear configuration */
6044 memset(cfg, 0, sizeof(*cfg));
6045
6046 LOG_DBG("Removed SC for %s", bt_addr_le_str(&addr));
6047 }
6048
6049 return 0;
6050 }
6051
sc_commit(void)6052 static int sc_commit(void)
6053 {
6054 atomic_set_bit(gatt_sc.flags, SC_LOAD);
6055 atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
6056
6057 if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
6058 /* Schedule SC indication since the range has changed */
6059 sc_work_submit(SC_TIMEOUT);
6060 }
6061
6062 return 0;
6063 }
6064
6065 BT_SETTINGS_DEFINE(sc, "sc", sc_set, sc_commit);
6066 #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */
6067
6068 #if defined(CONFIG_BT_GATT_CACHING)
cf_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)6069 static int cf_set(const char *name, size_t len_rd, settings_read_cb read_cb,
6070 void *cb_arg)
6071 {
6072 struct gatt_cf_cfg *cfg;
6073 bt_addr_le_t addr;
6074 const char *next;
6075 ssize_t len;
6076 int err;
6077 uint8_t id;
6078
6079 if (!name) {
6080 LOG_ERR("Insufficient number of arguments");
6081 return -EINVAL;
6082 }
6083
6084 err = bt_settings_decode_key(name, &addr);
6085 if (err) {
6086 LOG_ERR("Unable to decode address %s", name);
6087 return -EINVAL;
6088 }
6089
6090 settings_name_next(name, &next);
6091
6092 if (!next) {
6093 id = BT_ID_DEFAULT;
6094 } else {
6095 unsigned long next_id = strtoul(next, NULL, 10);
6096
6097 if (next_id >= CONFIG_BT_ID_MAX) {
6098 LOG_ERR("Invalid local identity %lu", next_id);
6099 return -EINVAL;
6100 }
6101
6102 id = (uint8_t)next_id;
6103 }
6104
6105 cfg = find_cf_cfg_by_addr(id, &addr);
6106 if (!cfg) {
6107 cfg = find_cf_cfg(NULL);
6108 if (!cfg) {
6109 LOG_ERR("Unable to restore CF: no cfg left");
6110 return -ENOMEM;
6111 }
6112
6113 cfg->id = id;
6114 bt_addr_le_copy(&cfg->peer, &addr);
6115 }
6116
6117 if (len_rd) {
6118 char dst[CF_NUM_BYTES + CF_FLAGS_STORE_LEN];
6119
6120 len = read_cb(cb_arg, dst, sizeof(dst));
6121 if (len < 0) {
6122 LOG_ERR("Failed to decode value (err %zd)", len);
6123 return len;
6124 }
6125
6126 memcpy(cfg->data, dst, sizeof(cfg->data));
6127 LOG_DBG("Read CF: len %zd", len);
6128
6129 if (len != sizeof(dst)) {
6130 LOG_WRN("Change-aware status not found in settings, "
6131 "defaulting peer status to change-unaware");
6132 set_change_aware(cfg, false);
6133 } else {
6134 /* change-aware byte is present in NVS */
6135 uint8_t change_aware = dst[sizeof(cfg->data)];
6136
6137 if (change_aware & ~BIT(CF_CHANGE_AWARE)) {
6138 LOG_WRN("Read back bad change-aware value: 0x%x, "
6139 "defaulting peer status to change-unaware",
6140 change_aware);
6141 set_change_aware(cfg, false);
6142 } else {
6143 set_change_aware_no_store(cfg, change_aware);
6144 }
6145 }
6146 } else {
6147 clear_cf_cfg(cfg);
6148 }
6149
6150 LOG_DBG("Restored CF for %s", bt_addr_le_str(&addr));
6151
6152 return 0;
6153 }
6154
6155 BT_SETTINGS_DEFINE(cf, "cf", cf_set, NULL);
6156
db_hash_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)6157 static int db_hash_set(const char *name, size_t len_rd,
6158 settings_read_cb read_cb, void *cb_arg)
6159 {
6160 ssize_t len;
6161
6162 len = read_cb(cb_arg, db_hash.stored_hash, sizeof(db_hash.stored_hash));
6163 if (len < 0) {
6164 LOG_ERR("Failed to decode value (err %zd)", len);
6165 return len;
6166 }
6167
6168 LOG_HEXDUMP_DBG(db_hash.stored_hash, sizeof(db_hash.stored_hash), "Stored Hash: ");
6169
6170 return 0;
6171 }
6172
db_hash_commit(void)6173 static int db_hash_commit(void)
6174 {
6175 atomic_set_bit(gatt_sc.flags, DB_HASH_LOAD);
6176
6177 /* Calculate the hash and compare it against the value loaded from
6178 * flash. Do it from the current context to avoid any potential race
6179 * conditions.
6180 */
6181 do_db_hash();
6182
6183 return 0;
6184 }
6185
6186 BT_SETTINGS_DEFINE(hash, "hash", db_hash_set, db_hash_commit);
6187 #endif /*CONFIG_BT_GATT_CACHING */
6188 #endif /* CONFIG_BT_SETTINGS */
6189
remove_peer_from_attr(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)6190 static uint8_t remove_peer_from_attr(const struct bt_gatt_attr *attr,
6191 uint16_t handle, void *user_data)
6192 {
6193 const struct addr_with_id *addr_with_id = user_data;
6194 struct _bt_gatt_ccc *ccc;
6195 struct bt_gatt_ccc_cfg *cfg;
6196
6197 /* Check if attribute is a CCC */
6198 if (attr->write != bt_gatt_attr_write_ccc) {
6199 return BT_GATT_ITER_CONTINUE;
6200 }
6201
6202 ccc = attr->user_data;
6203
6204 /* Check if there is a cfg for the peer */
6205 cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id);
6206 if (cfg) {
6207 memset(cfg, 0, sizeof(*cfg));
6208 }
6209
6210 return BT_GATT_ITER_CONTINUE;
6211 }
6212
bt_gatt_clear_ccc(uint8_t id,const bt_addr_le_t * addr)6213 static int bt_gatt_clear_ccc(uint8_t id, const bt_addr_le_t *addr)
6214 {
6215 struct addr_with_id addr_with_id = {
6216 .addr = addr,
6217 .id = id,
6218 };
6219
6220 bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr,
6221 &addr_with_id);
6222
6223 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
6224 return bt_settings_delete_ccc(id, addr);
6225 }
6226
6227 return 0;
6228 }
6229
bt_gatt_clear_cf(uint8_t id,const bt_addr_le_t * addr)6230 static int bt_gatt_clear_cf(uint8_t id, const bt_addr_le_t *addr)
6231 {
6232 struct gatt_cf_cfg *cfg;
6233
6234 cfg = find_cf_cfg_by_addr(id, addr);
6235 if (cfg) {
6236 clear_cf_cfg(cfg);
6237 }
6238
6239 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
6240 return bt_settings_delete_ccc(id, addr);
6241 }
6242
6243 return 0;
6244
6245 }
6246
6247
find_gatt_sub(uint8_t id,const bt_addr_le_t * addr)6248 static struct gatt_sub *find_gatt_sub(uint8_t id, const bt_addr_le_t *addr)
6249 {
6250 for (int i = 0; i < ARRAY_SIZE(subscriptions); i++) {
6251 struct gatt_sub *sub = &subscriptions[i];
6252
6253 if (id == sub->id &&
6254 bt_addr_le_eq(addr, &sub->peer)) {
6255 return sub;
6256 }
6257 }
6258
6259 return NULL;
6260 }
6261
bt_gatt_clear_subscriptions(uint8_t id,const bt_addr_le_t * addr)6262 static void bt_gatt_clear_subscriptions(uint8_t id, const bt_addr_le_t *addr)
6263 {
6264 struct gatt_sub *sub;
6265 struct bt_gatt_subscribe_params *params, *tmp;
6266 sys_snode_t *prev = NULL;
6267
6268 sub = find_gatt_sub(id, addr);
6269 if (!sub) {
6270 return;
6271 }
6272
6273 SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sub->list, params, tmp,
6274 node) {
6275 params->value = 0U;
6276 gatt_sub_remove(NULL, sub, prev, params);
6277 }
6278 }
6279
bt_gatt_clear(uint8_t id,const bt_addr_le_t * addr)6280 int bt_gatt_clear(uint8_t id, const bt_addr_le_t *addr)
6281 {
6282 int err;
6283
6284 err = bt_gatt_clear_ccc(id, addr);
6285 if (err < 0) {
6286 return err;
6287 }
6288
6289 if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
6290 err = bt_gatt_clear_sc(id, addr);
6291 if (err < 0) {
6292 return err;
6293 }
6294 }
6295
6296 if (IS_ENABLED(CONFIG_BT_GATT_CACHING)) {
6297 err = bt_gatt_clear_cf(id, addr);
6298 if (err < 0) {
6299 return err;
6300 }
6301 }
6302
6303 if (IS_ENABLED(CONFIG_BT_GATT_CLIENT)) {
6304 bt_gatt_clear_subscriptions(id, addr);
6305 }
6306
6307 return 0;
6308 }
6309
bt_gatt_disconnected(struct bt_conn * conn)6310 void bt_gatt_disconnected(struct bt_conn *conn)
6311 {
6312 LOG_DBG("conn %p", conn);
6313 bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn);
6314
6315 #if defined(CONFIG_BT_GATT_NOTIFY_MULTIPLE)
6316 /* Clear pending notifications */
6317 cleanup_notify(conn);
6318 #endif /* CONFIG_BT_GATT_NOTIFY_MULTIPLE */
6319
6320 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
6321 gatt_store_ccc_cf(conn->id, &conn->le.dst);
6322 }
6323
6324 /* Make sure to clear the CCC entry when using lazy loading */
6325 if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) &&
6326 bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
6327 struct addr_with_id addr_with_id = {
6328 .addr = &conn->le.dst,
6329 .id = conn->id,
6330 };
6331 bt_gatt_foreach_attr(0x0001, 0xffff,
6332 remove_peer_from_attr,
6333 &addr_with_id);
6334 }
6335
6336 #if defined(CONFIG_BT_GATT_CLIENT)
6337 remove_subscriptions(conn);
6338 #endif /* CONFIG_BT_GATT_CLIENT */
6339
6340 #if defined(CONFIG_BT_GATT_CACHING)
6341 remove_cf_cfg(conn);
6342 #endif
6343 }
6344
bt_gatt_req_set_mtu(struct bt_att_req * req,uint16_t mtu)6345 void bt_gatt_req_set_mtu(struct bt_att_req *req, uint16_t mtu)
6346 {
6347 IF_ENABLED(CONFIG_BT_GATT_CLIENT, ({
6348 if (req->func == gatt_read_rsp) {
6349 struct bt_gatt_read_params *params = req->user_data;
6350
6351 __ASSERT_NO_MSG(params);
6352 params->_att_mtu = mtu;
6353 return;
6354 }
6355 }));
6356
6357 /* Otherwise: This request type does not have an `_att_mtu`
6358 * params field or any other method to get this value, so we can
6359 * just drop it here. Feel free to add this capability to other
6360 * request types if needed.
6361 */
6362 }
6363