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