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