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