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