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