1 /*  Bluetooth Scan Delegator */
2 
3 /*
4  * Copyright (c) 2019 Bose Corporation
5  * Copyright (c) 2021-2023 Nordic Semiconductor ASA
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  */
9 
10 #include <errno.h>
11 #include <stdbool.h>
12 #include <stddef.h>
13 #include <stdint.h>
14 #include <string.h>
15 #include <sys/types.h>
16 
17 #include <zephyr/autoconf.h>
18 #include <zephyr/bluetooth/addr.h>
19 #include <zephyr/bluetooth/att.h>
20 #include <zephyr/bluetooth/audio/audio.h>
21 #include <zephyr/bluetooth/audio/bap.h>
22 #include <zephyr/bluetooth/bluetooth.h>
23 #include <zephyr/bluetooth/conn.h>
24 #include <zephyr/bluetooth/gap.h>
25 #include <zephyr/bluetooth/gatt.h>
26 #include <zephyr/bluetooth/hci_types.h>
27 #include <zephyr/bluetooth/iso.h>
28 #include <zephyr/bluetooth/l2cap.h>
29 #include <zephyr/bluetooth/buf.h>
30 #include <zephyr/bluetooth/uuid.h>
31 #include <zephyr/init.h>
32 #include <zephyr/kernel.h>
33 #include <zephyr/logging/log.h>
34 #include <zephyr/net_buf.h>
35 #include <zephyr/sys/__assert.h>
36 #include <zephyr/sys/atomic.h>
37 #include <zephyr/sys/byteorder.h>
38 #include <zephyr/sys/check.h>
39 #include <zephyr/sys/util.h>
40 #include <zephyr/sys/util_macro.h>
41 
42 LOG_MODULE_REGISTER(bt_bap_scan_delegator, CONFIG_BT_BAP_SCAN_DELEGATOR_LOG_LEVEL);
43 
44 #include "common/bt_str.h"
45 
46 #include "audio_internal.h"
47 #include "bap_internal.h"
48 #include "../host/conn_internal.h"
49 #include "../host/hci_core.h"
50 
51 #define PAST_TIMEOUT              K_SECONDS(10)
52 
53 #define SCAN_DELEGATOR_BUF_SEM_TIMEOUT K_MSEC(CONFIG_BT_BAP_SCAN_DELEGATOR_BUF_TIMEOUT)
54 static K_SEM_DEFINE(read_buf_sem, 1, 1);
55 NET_BUF_SIMPLE_DEFINE_STATIC(read_buf, BT_ATT_MAX_ATTRIBUTE_LEN);
56 
57 enum bass_recv_state_internal_flag {
58 	/* TODO: Replace this flag with a k_work_delayable */
59 	BASS_RECV_STATE_INTERNAL_FLAG_NOTIFY_PEND,
60 
61 	BASS_RECV_STATE_INTERNAL_FLAG_NUM,
62 };
63 
64 /* TODO: Merge bass_recv_state_internal_t and bt_bap_scan_delegator_recv_state */
65 struct bass_recv_state_internal {
66 	const struct bt_gatt_attr *attr;
67 
68 	bool active;
69 	uint8_t index;
70 	struct bt_bap_scan_delegator_recv_state state;
71 	uint8_t broadcast_code[BT_ISO_BROADCAST_CODE_SIZE];
72 	struct bt_le_per_adv_sync *pa_sync;
73 	/** Requested BIS sync bitfield for each subgroup */
74 	uint32_t requested_bis_sync[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS];
75 
76 	ATOMIC_DEFINE(flags, BASS_RECV_STATE_INTERNAL_FLAG_NUM);
77 };
78 
79 struct bt_bap_scan_delegator_inst {
80 	uint8_t next_src_id;
81 	struct bass_recv_state_internal recv_states
82 		[CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT];
83 };
84 
85 enum scan_delegator_flag {
86 	SCAN_DELEGATOR_FLAG_REGISTERED_CONN_CB,
87 	SCAN_DELEGATOR_FLAG_REGISTERED_SCAN_DELIGATOR,
88 	SCAN_DELEGATOR_FLAG_REGISTERED_PA_SYNC_CB,
89 
90 	SCAN_DELEGATOR_FLAG_NUM,
91 };
92 
93 static ATOMIC_DEFINE(scan_delegator_flags, SCAN_DELEGATOR_FLAG_NUM);
94 
95 static struct bt_bap_scan_delegator_inst scan_delegator;
96 static struct bt_bap_scan_delegator_cb *scan_delegator_cbs;
97 
98 /**
99  * @brief Returns whether a value's bits is a subset of another value's bits
100  *
101  * @param a The subset to check
102  * @param b The bits to check against
103  *
104  * @return True if @p a is a bitwise subset of @p b
105  */
bits_subset_of(uint32_t a,uint32_t b)106 static bool bits_subset_of(uint32_t a, uint32_t b)
107 {
108 	return (((a) & (~(b))) == 0);
109 }
110 
bis_syncs_unique_or_no_pref(uint32_t requested_bis_syncs,uint32_t aggregated_bis_syncs)111 static bool bis_syncs_unique_or_no_pref(uint32_t requested_bis_syncs,
112 					uint32_t aggregated_bis_syncs)
113 {
114 	if (requested_bis_syncs == 0U || aggregated_bis_syncs == 0U) {
115 		return true;
116 	}
117 
118 	if (requested_bis_syncs == BT_BAP_BIS_SYNC_NO_PREF &&
119 	    aggregated_bis_syncs == BT_BAP_BIS_SYNC_NO_PREF) {
120 		return true;
121 	}
122 
123 	return (requested_bis_syncs & aggregated_bis_syncs) != 0U;
124 }
125 
bt_debug_dump_recv_state(const struct bass_recv_state_internal * recv_state)126 static void bt_debug_dump_recv_state(const struct bass_recv_state_internal *recv_state)
127 {
128 	if (recv_state->active) {
129 		const struct bt_bap_scan_delegator_recv_state *state = &recv_state->state;
130 		const bool is_bad_code = state->encrypt_state == BT_BAP_BIG_ENC_STATE_BAD_CODE;
131 
132 		LOG_DBG("Receive State[%d]: src ID %u, addr %s, adv_sid %u, broadcast_id 0x%06X, "
133 			"pa_sync_state %u, encrypt state %u%s%s, num_subgroups %u",
134 			recv_state->index, state->src_id, bt_addr_le_str(&state->addr),
135 			state->adv_sid, state->broadcast_id, state->pa_sync_state,
136 			state->encrypt_state, is_bad_code ? ", bad code" : "",
137 			is_bad_code ? bt_hex(state->bad_code, sizeof(state->bad_code)) : "",
138 			state->num_subgroups);
139 
140 		for (uint8_t i = 0U; i < state->num_subgroups; i++) {
141 			const struct bt_bap_bass_subgroup *subgroup = &state->subgroups[i];
142 
143 			LOG_DBG("\tSubgroup[%u]: BIS sync %u (requested %u), metadata_len %zu, "
144 				"metadata: %s",
145 				i, subgroup->bis_sync, recv_state->requested_bis_sync[i],
146 				subgroup->metadata_len,
147 				bt_hex(subgroup->metadata, subgroup->metadata_len));
148 		}
149 	} else {
150 		LOG_DBG("Inactive receive state");
151 	}
152 }
153 
bass_notify_receive_state(struct bt_conn * conn,const struct bass_recv_state_internal * internal_state)154 static void bass_notify_receive_state(struct bt_conn *conn,
155 				      const struct bass_recv_state_internal *internal_state)
156 {
157 	const uint8_t att_ntf_header_size = 3; /* opcode (1) + handle (2) */
158 	uint16_t max_ntf_size;
159 	uint16_t ntf_size;
160 	int err;
161 
162 	if (conn != NULL) {
163 		max_ntf_size = bt_gatt_get_mtu(conn) - att_ntf_header_size;
164 	} else {
165 		max_ntf_size = MIN(BT_L2CAP_RX_MTU, BT_L2CAP_TX_MTU) - att_ntf_header_size;
166 	}
167 
168 	ntf_size = MIN(max_ntf_size, read_buf.len);
169 	if (ntf_size < read_buf.len) {
170 		LOG_DBG("Sending truncated notification (%u/%u)", ntf_size, read_buf.len);
171 	}
172 
173 	LOG_DBG("Sending bytes %d", ntf_size);
174 	err = bt_gatt_notify_uuid(NULL, BT_UUID_BASS_RECV_STATE,
175 				  internal_state->attr, read_buf.data,
176 				  ntf_size);
177 
178 	if (err != 0 && err != -ENOTCONN) {
179 		LOG_DBG("Could not notify receive state: %d", err);
180 	}
181 }
182 
net_buf_put_recv_state(const struct bass_recv_state_internal * recv_state)183 static void net_buf_put_recv_state(const struct bass_recv_state_internal *recv_state)
184 {
185 	const struct bt_bap_scan_delegator_recv_state *state = &recv_state->state;
186 
187 	net_buf_simple_reset(&read_buf);
188 
189 	__ASSERT(recv_state, "NULL receive state");
190 
191 	if (!recv_state->active) {
192 		/* Notify empty */
193 
194 		return;
195 	}
196 
197 	(void)net_buf_simple_add_u8(&read_buf, state->src_id);
198 	(void)net_buf_simple_add_u8(&read_buf, state->addr.type);
199 	(void)net_buf_simple_add_mem(&read_buf, &state->addr.a,
200 				     sizeof(state->addr.a));
201 	(void)net_buf_simple_add_u8(&read_buf, state->adv_sid);
202 	(void)net_buf_simple_add_le24(&read_buf, state->broadcast_id);
203 	(void)net_buf_simple_add_u8(&read_buf, state->pa_sync_state);
204 	(void)net_buf_simple_add_u8(&read_buf, state->encrypt_state);
205 	if (state->encrypt_state == BT_BAP_BIG_ENC_STATE_BAD_CODE) {
206 		(void)net_buf_simple_add_mem(&read_buf, &state->bad_code,
207 					     sizeof(state->bad_code));
208 	}
209 	(void)net_buf_simple_add_u8(&read_buf, state->num_subgroups);
210 	for (int i = 0; i < state->num_subgroups; i++) {
211 		const struct bt_bap_bass_subgroup *subgroup = &state->subgroups[i];
212 
213 		(void)net_buf_simple_add_le32(&read_buf, subgroup->bis_sync);
214 		(void)net_buf_simple_add_u8(&read_buf, subgroup->metadata_len);
215 		(void)net_buf_simple_add_mem(&read_buf, subgroup->metadata,
216 					     subgroup->metadata_len);
217 	}
218 }
219 
receive_state_updated(struct bt_conn * conn,const struct bass_recv_state_internal * internal_state)220 static void receive_state_updated(struct bt_conn *conn,
221 				  const struct bass_recv_state_internal *internal_state)
222 {
223 	int err;
224 
225 	/* If something is holding the NOTIFY_PEND flag we should not notify now */
226 	if (atomic_test_bit(internal_state->flags,
227 			    BASS_RECV_STATE_INTERNAL_FLAG_NOTIFY_PEND)) {
228 		return;
229 	}
230 
231 	err = k_sem_take(&read_buf_sem, SCAN_DELEGATOR_BUF_SEM_TIMEOUT);
232 	if (err != 0) {
233 		LOG_DBG("Failed to take read_buf_sem: %d", err);
234 
235 		return;
236 	}
237 
238 	bt_debug_dump_recv_state(internal_state);
239 	net_buf_put_recv_state(internal_state);
240 	bass_notify_receive_state(conn, internal_state);
241 	if (scan_delegator_cbs != NULL &&
242 	    scan_delegator_cbs->recv_state_updated != NULL) {
243 		scan_delegator_cbs->recv_state_updated(conn,
244 						       &internal_state->state);
245 	}
246 
247 	k_sem_give(&read_buf_sem);
248 }
249 
bis_sync_request_updated(struct bt_conn * conn,const struct bass_recv_state_internal * internal_state)250 static void bis_sync_request_updated(struct bt_conn *conn,
251 				     const struct bass_recv_state_internal *internal_state)
252 {
253 	if (scan_delegator_cbs != NULL &&
254 	    scan_delegator_cbs->bis_sync_req != NULL) {
255 		scan_delegator_cbs->bis_sync_req(conn, &internal_state->state,
256 						 internal_state->requested_bis_sync);
257 	} else {
258 		LOG_WRN("bis_sync_req callback is missing");
259 	}
260 }
261 
scan_delegator_security_changed(struct bt_conn * conn,bt_security_t level,enum bt_security_err err)262 static void scan_delegator_security_changed(struct bt_conn *conn,
263 					    bt_security_t level,
264 					    enum bt_security_err err)
265 {
266 
267 	if (err != 0 || level < BT_SECURITY_L2 || !bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
268 		return;
269 	}
270 
271 	/* Notify all receive states after a bonded device reconnects */
272 	for (size_t i = 0; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
273 		const struct bass_recv_state_internal *internal_state =
274 			&scan_delegator.recv_states[i];
275 
276 		if (!internal_state->active) {
277 			continue;
278 		}
279 
280 		err = k_sem_take(&read_buf_sem, SCAN_DELEGATOR_BUF_SEM_TIMEOUT);
281 		if (err != 0) {
282 			LOG_DBG("Failed to take read_buf_sem: %d", err);
283 
284 			return;
285 		}
286 
287 		net_buf_put_recv_state(internal_state);
288 		bass_notify_receive_state(conn, internal_state);
289 
290 		k_sem_give(&read_buf_sem);
291 	}
292 }
293 
294 BT_CONN_CB_DEFINE(conn_callbacks) = {
295 	.security_changed = scan_delegator_security_changed,
296 };
297 
next_src_id(void)298 static uint8_t next_src_id(void)
299 {
300 	uint8_t next_src_id;
301 	bool unique = false;
302 
303 	while (!unique) {
304 		next_src_id = scan_delegator.next_src_id++;
305 		unique = true;
306 		for (size_t i = 0; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
307 			if (scan_delegator.recv_states[i].active &&
308 			    scan_delegator.recv_states[i].state.src_id == next_src_id) {
309 				unique = false;
310 				break;
311 			}
312 		}
313 	}
314 
315 	return next_src_id;
316 }
317 
bass_lookup_src_id(uint8_t src_id)318 static struct bass_recv_state_internal *bass_lookup_src_id(uint8_t src_id)
319 {
320 	for (size_t i = 0; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
321 		if (scan_delegator.recv_states[i].active &&
322 		    scan_delegator.recv_states[i].state.src_id == src_id) {
323 			return &scan_delegator.recv_states[i];
324 		}
325 	}
326 
327 	return NULL;
328 }
329 
bass_lookup_pa_sync(struct bt_le_per_adv_sync * sync)330 static struct bass_recv_state_internal *bass_lookup_pa_sync(struct bt_le_per_adv_sync *sync)
331 {
332 	for (size_t i = 0; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
333 		if (scan_delegator.recv_states[i].pa_sync == sync) {
334 			return &scan_delegator.recv_states[i];
335 		}
336 	}
337 
338 	return NULL;
339 }
340 
bass_lookup_addr(const bt_addr_le_t * addr)341 static struct bass_recv_state_internal *bass_lookup_addr(const bt_addr_le_t *addr)
342 {
343 	for (size_t i = 0; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
344 		if (bt_addr_le_eq(&scan_delegator.recv_states[i].state.addr,
345 				  addr)) {
346 			return &scan_delegator.recv_states[i];
347 		}
348 	}
349 
350 	return NULL;
351 }
352 
get_free_recv_state(void)353 static struct bass_recv_state_internal *get_free_recv_state(void)
354 {
355 	for (size_t i = 0U; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
356 		struct bass_recv_state_internal *free_internal_state =
357 			&scan_delegator.recv_states[i];
358 
359 		if (!free_internal_state->active) {
360 			return free_internal_state;
361 		}
362 	}
363 
364 	return NULL;
365 }
366 
pa_synced(struct bt_le_per_adv_sync * sync,struct bt_le_per_adv_sync_synced_info * info)367 static void pa_synced(struct bt_le_per_adv_sync *sync,
368 		      struct bt_le_per_adv_sync_synced_info *info)
369 {
370 	struct bass_recv_state_internal *internal_state;
371 
372 	LOG_DBG("Synced%s", info->conn ? " via PAST" : "");
373 
374 	internal_state = bass_lookup_addr(info->addr);
375 	if (internal_state == NULL) {
376 		LOG_DBG("BASS receive state not found");
377 		return;
378 	}
379 
380 	internal_state->pa_sync = sync;
381 
382 	if (internal_state->state.pa_sync_state != BT_BAP_PA_STATE_SYNCED) {
383 		internal_state->state.pa_sync_state = BT_BAP_PA_STATE_SYNCED;
384 		receive_state_updated(info->conn, internal_state);
385 	}
386 }
387 
pa_terminated(struct bt_le_per_adv_sync * sync,const struct bt_le_per_adv_sync_term_info * info)388 static void pa_terminated(struct bt_le_per_adv_sync *sync,
389 			  const struct bt_le_per_adv_sync_term_info *info)
390 {
391 	struct bass_recv_state_internal *internal_state = bass_lookup_pa_sync(sync);
392 
393 	LOG_DBG("Terminated");
394 	if (internal_state == NULL) {
395 		LOG_DBG("BASS receive state not found");
396 		return;
397 	}
398 
399 	internal_state->pa_sync = NULL;
400 
401 	if (internal_state->state.pa_sync_state != BT_BAP_PA_STATE_NOT_SYNCED) {
402 		internal_state->state.pa_sync_state = BT_BAP_PA_STATE_NOT_SYNCED;
403 		receive_state_updated(NULL, internal_state);
404 	}
405 }
406 
407 static struct bt_le_per_adv_sync_cb pa_sync_cb =  {
408 	.synced = pa_synced,
409 	.term = pa_terminated,
410 };
411 
supports_past(struct bt_conn * conn,uint8_t pa_sync_val)412 static bool supports_past(struct bt_conn *conn, uint8_t pa_sync_val)
413 {
414 	if (IS_ENABLED(CONFIG_BT_PER_ADV_SYNC_TRANSFER_RECEIVER)) {
415 		LOG_DBG("%p remote %s PAST, local %s PAST (req %u)", (void *)conn,
416 			BT_FEAT_LE_PAST_SEND(conn->le.features) ? "supports" : "does not support",
417 			BT_FEAT_LE_PAST_RECV(bt_dev.le.features) ? "supports" : "does not support",
418 			pa_sync_val);
419 
420 		return pa_sync_val == BT_BAP_BASS_PA_REQ_SYNC_PAST &&
421 		       BT_FEAT_LE_PAST_SEND(conn->le.features) &&
422 		       BT_FEAT_LE_PAST_RECV(bt_dev.le.features);
423 	} else {
424 		return false;
425 	}
426 }
427 
pa_sync_request(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * state,uint8_t pa_sync_val,uint16_t pa_interval)428 static int pa_sync_request(struct bt_conn *conn,
429 			   const struct bt_bap_scan_delegator_recv_state *state,
430 			   uint8_t pa_sync_val, uint16_t pa_interval)
431 {
432 	int err = -EACCES;
433 
434 	if (scan_delegator_cbs != NULL &&
435 	    scan_delegator_cbs->pa_sync_req != NULL) {
436 		const bool past_supported = supports_past(conn, pa_sync_val);
437 
438 		err = scan_delegator_cbs->pa_sync_req(conn, state,
439 						      past_supported,
440 						      pa_interval);
441 	} else {
442 		LOG_WRN("pa_sync_req callback is missing, rejecting PA sync request");
443 	}
444 
445 	return err;
446 }
447 
pa_sync_term_request(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * state)448 static int pa_sync_term_request(struct bt_conn *conn,
449 				const struct bt_bap_scan_delegator_recv_state *state)
450 {
451 	int err = -EACCES;
452 
453 	if (scan_delegator_cbs != NULL &&
454 	    scan_delegator_cbs->pa_sync_req != NULL) {
455 		err = scan_delegator_cbs->pa_sync_term_req(conn, state);
456 	} else {
457 		LOG_WRN("pa_sync_term_req callback is missing, rejecting PA sync term request");
458 	}
459 
460 	return err;
461 }
462 
463 /* BAP 6.5.4 states that the Broadcast Assistant shall not initiate the Add Source operation
464  * if the operation would result in duplicate values for the combined Source_Address_Type,
465  * Source_Adv_SID, and Broadcast_ID fields of any Broadcast Receive State characteristic exposed
466  * by the Scan Delegator.
467  */
bass_source_is_duplicate(uint32_t broadcast_id,uint8_t adv_sid,uint8_t addr_type)468 static bool bass_source_is_duplicate(uint32_t broadcast_id, uint8_t adv_sid, uint8_t addr_type)
469 {
470 	struct bass_recv_state_internal *state;
471 
472 	for (size_t i = 0; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
473 		state = &scan_delegator.recv_states[i];
474 
475 		if (state != NULL && state->state.broadcast_id == broadcast_id &&
476 			state->state.adv_sid == adv_sid && state->state.addr.type == addr_type) {
477 			LOG_DBG("recv_state already exists at src_id=0x%02X", state->state.src_id);
478 
479 			return true;
480 		}
481 	}
482 
483 	return false;
484 }
485 
scan_delegator_add_source(struct bt_conn * conn,struct net_buf_simple * buf)486 static int scan_delegator_add_source(struct bt_conn *conn,
487 				     struct net_buf_simple *buf)
488 {
489 	struct bass_recv_state_internal *internal_state = NULL;
490 	struct bt_bap_scan_delegator_recv_state *state;
491 	bt_addr_t *addr;
492 	uint8_t pa_sync;
493 	uint16_t pa_interval;
494 	uint32_t aggregated_bis_syncs = 0;
495 	uint32_t broadcast_id;
496 	bool bis_sync_requested;
497 
498 	/* subtract 1 as the opcode has already been pulled */
499 	if (buf->len < sizeof(struct bt_bap_bass_cp_add_src) - 1) {
500 		LOG_DBG("Invalid length %u", buf->size);
501 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
502 	}
503 
504 	internal_state = get_free_recv_state();
505 	if (internal_state == NULL) {
506 		LOG_DBG("Could not get free receive state");
507 
508 		return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
509 	}
510 
511 	state = &internal_state->state;
512 
513 	state->src_id = next_src_id();
514 	state->addr.type = net_buf_simple_pull_u8(buf);
515 	if (state->addr.type > BT_ADDR_LE_RANDOM) {
516 		LOG_DBG("Invalid address type %u", state->addr.type);
517 		return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
518 	}
519 
520 	addr = net_buf_simple_pull_mem(buf, sizeof(*addr));
521 	bt_addr_copy(&state->addr.a, addr);
522 
523 	state->adv_sid = net_buf_simple_pull_u8(buf);
524 	if (state->adv_sid > BT_GAP_SID_MAX) {
525 		LOG_DBG("Invalid adv SID %u", state->adv_sid);
526 		return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
527 	}
528 
529 	broadcast_id = net_buf_simple_pull_le24(buf);
530 
531 	if (bass_source_is_duplicate(broadcast_id, state->adv_sid, state->addr.type)) {
532 		LOG_DBG("Adding broadcast_id=0x%06X, adv_sid=0x%02X, and addr.type=0x%02X would "
533 			"result in duplication", state->broadcast_id, state->adv_sid,
534 			state->addr.type);
535 
536 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
537 	}
538 
539 	state->broadcast_id = broadcast_id;
540 
541 	pa_sync = net_buf_simple_pull_u8(buf);
542 	if (pa_sync > BT_BAP_BASS_PA_REQ_SYNC) {
543 		LOG_DBG("Invalid PA sync value %u", pa_sync);
544 		return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
545 	}
546 
547 	pa_interval = net_buf_simple_pull_le16(buf);
548 
549 	state->num_subgroups = net_buf_simple_pull_u8(buf);
550 	if (state->num_subgroups > CONFIG_BT_BAP_BASS_MAX_SUBGROUPS) {
551 		LOG_WRN("Too many subgroups %u/%u", state->num_subgroups,
552 			CONFIG_BT_BAP_BASS_MAX_SUBGROUPS);
553 		return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
554 	}
555 
556 	bis_sync_requested = false;
557 	for (int i = 0; i < state->num_subgroups; i++) {
558 		struct bt_bap_bass_subgroup *subgroup = &state->subgroups[i];
559 		uint8_t *metadata;
560 
561 		if (buf->len < (sizeof(subgroup->bis_sync) + sizeof(subgroup->metadata_len))) {
562 			LOG_DBG("Invalid length %u", buf->size);
563 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
564 		}
565 
566 		internal_state->requested_bis_sync[i] = net_buf_simple_pull_le32(buf);
567 
568 		if (internal_state->requested_bis_sync[i] &&
569 		    pa_sync == BT_BAP_BASS_PA_REQ_NO_SYNC) {
570 			LOG_DBG("Cannot sync to BIS without PA");
571 			return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
572 		}
573 
574 		if (internal_state->requested_bis_sync[i] != 0U) {
575 			bis_sync_requested = true;
576 		}
577 
578 		/* Verify that the request BIS sync indexes are unique or no preference */
579 		if (!bis_syncs_unique_or_no_pref(internal_state->requested_bis_sync[i],
580 						 aggregated_bis_syncs)) {
581 			LOG_DBG("Duplicate BIS index [%d]%x (aggregated %x)",
582 				i, internal_state->requested_bis_sync[i],
583 				aggregated_bis_syncs);
584 
585 			return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
586 		}
587 
588 		if (!valid_bis_syncs(internal_state->requested_bis_sync[i])) {
589 			LOG_DBG("Invalid BIS sync[%d]: 0x%08X", i,
590 				internal_state->requested_bis_sync[i]);
591 
592 			return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
593 		}
594 
595 		aggregated_bis_syncs |= internal_state->requested_bis_sync[i];
596 
597 		subgroup->metadata_len = net_buf_simple_pull_u8(buf);
598 
599 		if (buf->len < subgroup->metadata_len) {
600 			LOG_DBG("Invalid length %u", buf->size);
601 
602 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
603 		}
604 
605 
606 		if (subgroup->metadata_len > CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE) {
607 			LOG_WRN("Metadata too long %u/%u", subgroup->metadata_len,
608 				CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE);
609 
610 			return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
611 		}
612 
613 		metadata = net_buf_simple_pull_mem(buf, subgroup->metadata_len);
614 		(void)memcpy(subgroup->metadata, metadata,
615 			     subgroup->metadata_len);
616 	}
617 
618 	if (buf->len != 0) {
619 		LOG_DBG("Invalid length %u", buf->size);
620 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
621 	}
622 
623 	/* The active flag shall be set before any application callbacks, so that any calls for the
624 	 * receive state can be processed
625 	 */
626 	internal_state->active = true;
627 
628 	/* Set NOTIFY_PEND flag to ensure that we only send 1 notification in case that the upper
629 	 * layer calls another function that changes the state in the pa_sync_request callback
630 	 */
631 	atomic_set_bit(internal_state->flags, BASS_RECV_STATE_INTERNAL_FLAG_NOTIFY_PEND);
632 
633 	if (pa_sync != BT_BAP_BASS_PA_REQ_NO_SYNC) {
634 		int err;
635 
636 		err = pa_sync_request(conn, state, pa_sync, pa_interval);
637 
638 		if (err != 0) {
639 			(void)memset(state, 0, sizeof(*state));
640 			internal_state->active = false;
641 
642 			LOG_DBG("PA sync %u from %p was rejected with reason %d", pa_sync, conn,
643 				err);
644 
645 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
646 		}
647 	}
648 
649 	LOG_DBG("Index %u: New source added: ID 0x%02x",
650 		internal_state->index, state->src_id);
651 
652 	atomic_clear_bit(internal_state->flags,
653 			 BASS_RECV_STATE_INTERNAL_FLAG_NOTIFY_PEND);
654 
655 	receive_state_updated(conn, internal_state);
656 
657 	if (bis_sync_requested) {
658 		bis_sync_request_updated(conn, internal_state);
659 	}
660 
661 	return 0;
662 }
663 
scan_delegator_mod_src(struct bt_conn * conn,struct net_buf_simple * buf)664 static int scan_delegator_mod_src(struct bt_conn *conn,
665 				  struct net_buf_simple *buf)
666 {
667 	struct bt_bap_scan_delegator_recv_state backup_state;
668 	struct bass_recv_state_internal *internal_state;
669 	struct bt_bap_scan_delegator_recv_state *state;
670 	uint8_t src_id;
671 	bool state_changed = false;
672 	uint16_t pa_interval;
673 	uint8_t num_subgroups;
674 	struct bt_bap_bass_subgroup
675 		subgroups[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS] = { 0 };
676 	uint8_t pa_sync;
677 	uint32_t aggregated_bis_syncs = 0;
678 	bool bis_sync_change_requested;
679 
680 	/* subtract 1 as the opcode has already been pulled */
681 	if (buf->len < sizeof(struct bt_bap_bass_cp_mod_src) - 1) {
682 		LOG_DBG("Invalid length %u", buf->len);
683 
684 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
685 	}
686 
687 	src_id = net_buf_simple_pull_u8(buf);
688 	internal_state = bass_lookup_src_id(src_id);
689 
690 	LOG_DBG("src_id %u", src_id);
691 
692 	if (internal_state == NULL) {
693 		LOG_DBG("Could not find state by src id %u", src_id);
694 
695 		return BT_GATT_ERR(BT_BAP_BASS_ERR_INVALID_SRC_ID);
696 	}
697 
698 	pa_sync = net_buf_simple_pull_u8(buf);
699 	if (pa_sync > BT_BAP_BASS_PA_REQ_SYNC) {
700 		LOG_DBG("Invalid PA sync value %u", pa_sync);
701 
702 		return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
703 	}
704 
705 	pa_interval = net_buf_simple_pull_le16(buf);
706 
707 	num_subgroups = net_buf_simple_pull_u8(buf);
708 	if (num_subgroups > CONFIG_BT_BAP_BASS_MAX_SUBGROUPS) {
709 		LOG_WRN("Too many subgroups %u/%u", num_subgroups,
710 			CONFIG_BT_BAP_BASS_MAX_SUBGROUPS);
711 
712 		return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
713 	}
714 
715 	bis_sync_change_requested = false;
716 	for (int i = 0; i < num_subgroups; i++) {
717 		struct bt_bap_bass_subgroup *subgroup = &subgroups[i];
718 		uint32_t old_bis_sync_req;
719 		uint8_t *metadata;
720 
721 		if (buf->len < (sizeof(subgroup->bis_sync) + sizeof(subgroup->metadata_len))) {
722 			LOG_DBG("Invalid length %u", buf->len);
723 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
724 		}
725 
726 		old_bis_sync_req = internal_state->requested_bis_sync[i];
727 
728 		internal_state->requested_bis_sync[i] = net_buf_simple_pull_le32(buf);
729 
730 		if (internal_state->requested_bis_sync[i] &&
731 		    pa_sync == BT_BAP_BASS_PA_REQ_NO_SYNC) {
732 			LOG_DBG("Cannot sync to BIS without PA");
733 			return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
734 		}
735 
736 		if (old_bis_sync_req != internal_state->requested_bis_sync[i]) {
737 			bis_sync_change_requested = true;
738 		}
739 
740 		/* Verify that the request BIS sync indexes are unique or no preference */
741 		if (!bis_syncs_unique_or_no_pref(internal_state->requested_bis_sync[i],
742 						 aggregated_bis_syncs)) {
743 			LOG_DBG("Duplicate BIS index [%d]%x (aggregated %x)",
744 				i, internal_state->requested_bis_sync[i],
745 				aggregated_bis_syncs);
746 
747 			return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
748 		}
749 
750 		if (!valid_bis_syncs(internal_state->requested_bis_sync[i])) {
751 			return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
752 		}
753 		aggregated_bis_syncs |= internal_state->requested_bis_sync[i];
754 
755 		subgroup->metadata_len = net_buf_simple_pull_u8(buf);
756 
757 		if (buf->len < subgroup->metadata_len) {
758 			LOG_DBG("Invalid length %u", buf->len);
759 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
760 		}
761 
762 		if (subgroup->metadata_len > CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE) {
763 			LOG_WRN("Metadata too long %u/%u", subgroup->metadata_len,
764 				CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE);
765 			return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
766 		}
767 
768 		metadata = net_buf_simple_pull_mem(buf, subgroup->metadata_len);
769 
770 		(void)memcpy(subgroup->metadata, metadata,
771 			     subgroup->metadata_len);
772 	}
773 
774 	if (buf->len != 0) {
775 		LOG_DBG("Invalid length %u", buf->size);
776 
777 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
778 	}
779 
780 	/* All input has been validated; update receive state and check for changes */
781 	state = &internal_state->state;
782 
783 	/* Store backup in case upper layers rejects */
784 	(void)memcpy(&backup_state, state, sizeof(backup_state));
785 
786 	if (state->num_subgroups != num_subgroups) {
787 		state->num_subgroups = num_subgroups;
788 		state_changed = true;
789 	}
790 
791 	for (int i = 0; i < num_subgroups; i++) {
792 		const bool metadata_len_changed =
793 			subgroups[i].metadata_len != state->subgroups[i].metadata_len;
794 
795 		if (metadata_len_changed) {
796 			state->subgroups[i].metadata_len = subgroups[i].metadata_len;
797 			state_changed = true;
798 		}
799 
800 		if (metadata_len_changed ||
801 		    memcmp(subgroups[i].metadata, state->subgroups[i].metadata,
802 			   sizeof(subgroups[i].metadata)) != 0) {
803 
804 			if (state->subgroups[i].metadata_len == 0U) {
805 				memset(state->subgroups[i].metadata, 0,
806 				       state->subgroups[i].metadata_len);
807 			} else {
808 				(void)memcpy(state->subgroups[i].metadata, subgroups[i].metadata,
809 					     state->subgroups[i].metadata_len);
810 			}
811 
812 			state_changed = true;
813 		}
814 	}
815 
816 	/* Set NOTIFY_PEND flag to ensure that we only send 1 notification in case that the upper
817 	 * layer calls another function that changes the state in the pa_sync_request callback
818 	 */
819 	atomic_set_bit(internal_state->flags, BASS_RECV_STATE_INTERNAL_FLAG_NOTIFY_PEND);
820 
821 	/* Only send the sync request to upper layers if it is requested, and
822 	 * we are not already synced to the device
823 	 */
824 	if (pa_sync != BT_BAP_BASS_PA_REQ_NO_SYNC &&
825 	    state->pa_sync_state != BT_BAP_PA_STATE_SYNCED) {
826 		const uint8_t pa_sync_state = state->pa_sync_state;
827 		const int err = pa_sync_request(conn, state, pa_sync,
828 						pa_interval);
829 
830 		if (err != 0) {
831 			/* Restore backup */
832 			(void)memcpy(state, &backup_state,
833 				     sizeof(backup_state));
834 
835 			LOG_DBG("PA sync %u from %p was rejected with reason %d", pa_sync, conn,
836 				err);
837 
838 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
839 		} else if (pa_sync_state != state->pa_sync_state) {
840 			/* Temporary work around if the state is changed when pa_sync_request is
841 			 * called. See https://github.com/zephyrproject-rtos/zephyr/issues/79308 for
842 			 * more information about this issue.
843 			 */
844 			state_changed = true;
845 		}
846 	} else if (pa_sync == BT_BAP_BASS_PA_REQ_NO_SYNC &&
847 		   (state->pa_sync_state == BT_BAP_PA_STATE_INFO_REQ ||
848 		    state->pa_sync_state == BT_BAP_PA_STATE_SYNCED)) {
849 		/* Terminate PA sync */
850 		const int err = pa_sync_term_request(conn, &internal_state->state);
851 
852 		if (err != 0) {
853 			LOG_DBG("PA sync term from %p was rejected with reason %d", conn, err);
854 
855 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
856 		}
857 
858 		state_changed = true;
859 	}
860 
861 	atomic_clear_bit(internal_state->flags, BASS_RECV_STATE_INTERNAL_FLAG_NOTIFY_PEND);
862 
863 	/* Notify if changed */
864 	if (state_changed) {
865 		LOG_DBG("Index %u: Source modified: ID 0x%02x",
866 			internal_state->index, state->src_id);
867 
868 		receive_state_updated(conn, internal_state);
869 	}
870 
871 	if (bis_sync_change_requested) {
872 		bis_sync_request_updated(conn, internal_state);
873 	}
874 
875 	return 0;
876 }
877 
scan_delegator_broadcast_code(struct bt_conn * conn,struct net_buf_simple * buf)878 static int scan_delegator_broadcast_code(struct bt_conn *conn,
879 					 struct net_buf_simple *buf)
880 {
881 	struct bass_recv_state_internal *internal_state;
882 	uint8_t src_id;
883 	const uint8_t *broadcast_code;
884 
885 	/* subtract 1 as the opcode has already been pulled */
886 	if (buf->len != sizeof(struct bt_bap_bass_cp_broadcase_code) - 1) {
887 		LOG_DBG("Invalid length %u", buf->size);
888 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
889 	}
890 
891 	src_id = net_buf_simple_pull_u8(buf);
892 	internal_state = bass_lookup_src_id(src_id);
893 
894 	if (internal_state == NULL) {
895 		LOG_DBG("Could not find state by src id %u", src_id);
896 		return BT_GATT_ERR(BT_BAP_BASS_ERR_INVALID_SRC_ID);
897 	}
898 
899 	broadcast_code = net_buf_simple_pull_mem(buf, sizeof(internal_state->broadcast_code));
900 
901 	(void)memcpy(internal_state->broadcast_code, broadcast_code,
902 		     sizeof(internal_state->broadcast_code));
903 
904 	LOG_DBG("Index %u: broadcast code added: %s", internal_state->index,
905 		bt_hex(internal_state->broadcast_code, sizeof(internal_state->broadcast_code)));
906 
907 	if (scan_delegator_cbs != NULL &&
908 	    scan_delegator_cbs->broadcast_code != NULL) {
909 		scan_delegator_cbs->broadcast_code(conn, &internal_state->state,
910 						   broadcast_code);
911 	}
912 
913 	return 0;
914 }
915 
scan_delegator_rem_src(struct bt_conn * conn,struct net_buf_simple * buf)916 static int scan_delegator_rem_src(struct bt_conn *conn,
917 				  struct net_buf_simple *buf)
918 {
919 	struct bass_recv_state_internal *internal_state;
920 	struct bt_bap_scan_delegator_recv_state *state;
921 	bool bis_sync_was_requested;
922 	uint8_t src_id;
923 
924 	/* subtract 1 as the opcode has already been pulled */
925 	if (buf->len != sizeof(struct bt_bap_bass_cp_rem_src) - 1) {
926 		LOG_DBG("Invalid length %u", buf->size);
927 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
928 	}
929 
930 	src_id = net_buf_simple_pull_u8(buf);
931 	internal_state = bass_lookup_src_id(src_id);
932 
933 	if (internal_state == NULL) {
934 		LOG_DBG("Could not find state by src id %u", src_id);
935 		return BT_GATT_ERR(BT_BAP_BASS_ERR_INVALID_SRC_ID);
936 	}
937 
938 	state = &internal_state->state;
939 
940 	/* If conn == NULL then it's a local operation and we do not need to ask the application */
941 	if (conn != NULL && (state->pa_sync_state == BT_BAP_PA_STATE_INFO_REQ ||
942 			     state->pa_sync_state == BT_BAP_PA_STATE_SYNCED)) {
943 		int err;
944 
945 		/* Terminate PA sync */
946 		err = pa_sync_term_request(conn, &internal_state->state);
947 		if (err != 0) {
948 			LOG_DBG("PA sync term from %p was rejected with reason %d", conn, err);
949 
950 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
951 		}
952 	}
953 
954 	bis_sync_was_requested = false;
955 	for (uint8_t i = 0U; i < state->num_subgroups; i++) {
956 		if (internal_state->requested_bis_sync[i] != 0U) {
957 			bis_sync_was_requested = true;
958 			break;
959 		}
960 	}
961 
962 	LOG_DBG("Index %u: Removed source with ID 0x%02x",
963 		internal_state->index, src_id);
964 
965 	internal_state->active = false;
966 	internal_state->pa_sync = NULL;
967 	(void)memset(&internal_state->state, 0, sizeof(internal_state->state));
968 	(void)memset(internal_state->broadcast_code, 0,
969 		     sizeof(internal_state->broadcast_code));
970 	(void)memset(internal_state->requested_bis_sync, 0,
971 		     sizeof(internal_state->requested_bis_sync));
972 
973 	if (bis_sync_was_requested) {
974 		bis_sync_request_updated(conn, internal_state);
975 	}
976 	receive_state_updated(conn, internal_state);
977 
978 	return 0;
979 }
980 
write_control_point(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * data,uint16_t len,uint16_t offset,uint8_t flags)981 static ssize_t write_control_point(struct bt_conn *conn,
982 				   const struct bt_gatt_attr *attr,
983 				   const void *data, uint16_t len,
984 				   uint16_t offset, uint8_t flags)
985 {
986 	struct net_buf_simple buf;
987 	uint8_t opcode;
988 	int err;
989 
990 	if (offset != 0) {
991 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
992 	} else if (len == 0) {
993 		return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
994 	}
995 
996 	net_buf_simple_init_with_data(&buf, (void *)data, len);
997 
998 	opcode = net_buf_simple_pull_u8(&buf);
999 
1000 	if (!BT_BAP_BASS_VALID_OPCODE(opcode)) {
1001 		return BT_GATT_ERR(BT_BAP_BASS_ERR_OPCODE_NOT_SUPPORTED);
1002 	}
1003 
1004 	LOG_HEXDUMP_DBG(data, len, "Data");
1005 
1006 	switch (opcode) {
1007 	case BT_BAP_BASS_OP_SCAN_STOP:
1008 		LOG_DBG("Assistant stopping scanning");
1009 
1010 		if (buf.len != 0) {
1011 			LOG_DBG("Invalid length %u", buf.size);
1012 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
1013 		}
1014 
1015 		if (scan_delegator_cbs != NULL && scan_delegator_cbs->scanning_state != NULL) {
1016 			scan_delegator_cbs->scanning_state(conn, false);
1017 		}
1018 
1019 		break;
1020 	case BT_BAP_BASS_OP_SCAN_START:
1021 		LOG_DBG("Assistant starting scanning");
1022 
1023 		if (buf.len != 0) {
1024 			return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
1025 		}
1026 
1027 		if (scan_delegator_cbs != NULL && scan_delegator_cbs->scanning_state != NULL) {
1028 			scan_delegator_cbs->scanning_state(conn, true);
1029 		}
1030 
1031 		break;
1032 	case BT_BAP_BASS_OP_ADD_SRC:
1033 		LOG_DBG("Assistant adding source");
1034 
1035 		err = scan_delegator_add_source(conn, &buf);
1036 		if (err != 0) {
1037 			LOG_DBG("Could not add source %d", err);
1038 			return err;
1039 		}
1040 
1041 		break;
1042 	case BT_BAP_BASS_OP_MOD_SRC:
1043 		LOG_DBG("Assistant modifying source");
1044 
1045 		err = scan_delegator_mod_src(conn, &buf);
1046 		if (err != 0) {
1047 			LOG_DBG("Could not modify source %d", err);
1048 			return err;
1049 		}
1050 
1051 		break;
1052 	case BT_BAP_BASS_OP_BROADCAST_CODE:
1053 		LOG_DBG("Assistant setting broadcast code");
1054 
1055 		err = scan_delegator_broadcast_code(conn, &buf);
1056 		if (err != 0) {
1057 			LOG_DBG("Could not set broadcast code");
1058 			return err;
1059 		}
1060 
1061 		break;
1062 	case BT_BAP_BASS_OP_REM_SRC:
1063 		LOG_DBG("Assistant removing source");
1064 
1065 		err = scan_delegator_rem_src(conn, &buf);
1066 		if (err != 0) {
1067 			LOG_DBG("Could not remove source %d", err);
1068 			return err;
1069 		}
1070 
1071 		break;
1072 	default:
1073 		break;
1074 	}
1075 
1076 	return len;
1077 }
1078 
recv_state_cfg_changed(const struct bt_gatt_attr * attr,uint16_t value)1079 static void recv_state_cfg_changed(const struct bt_gatt_attr *attr,
1080 				   uint16_t value)
1081 {
1082 	LOG_DBG("value 0x%04x", value);
1083 }
1084 
read_recv_state(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)1085 static ssize_t read_recv_state(struct bt_conn *conn,
1086 			       const struct bt_gatt_attr *attr, void *buf,
1087 			       uint16_t len, uint16_t offset)
1088 {
1089 	uint8_t idx = POINTER_TO_UINT(BT_AUDIO_CHRC_USER_DATA(attr));
1090 	struct bass_recv_state_internal *recv_state = &scan_delegator.recv_states[idx];
1091 	struct bt_bap_scan_delegator_recv_state *state = &recv_state->state;
1092 
1093 	if (recv_state->active) {
1094 		ssize_t ret_val;
1095 		int err;
1096 
1097 		LOG_DBG("Index %u: Source ID 0x%02x", idx, state->src_id);
1098 
1099 		err = k_sem_take(&read_buf_sem, SCAN_DELEGATOR_BUF_SEM_TIMEOUT);
1100 		if (err != 0) {
1101 			LOG_DBG("Failed to take read_buf_sem: %d", err);
1102 
1103 			return err;
1104 		}
1105 
1106 		bt_debug_dump_recv_state(recv_state);
1107 		net_buf_put_recv_state(recv_state);
1108 
1109 		ret_val = bt_gatt_attr_read(conn, attr, buf, len, offset,
1110 					    read_buf.data, read_buf.len);
1111 
1112 		k_sem_give(&read_buf_sem);
1113 
1114 		return ret_val;
1115 	}
1116 	LOG_DBG("Index %u: Not active", idx);
1117 	return bt_gatt_attr_read(conn, attr, buf, len, offset, NULL, 0);
1118 
1119 }
1120 
1121 #define RECEIVE_STATE_CHARACTERISTIC(idx) \
1122 	BT_AUDIO_CHRC(BT_UUID_BASS_RECV_STATE, \
1123 		      BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,\
1124 		      BT_GATT_PERM_READ_ENCRYPT, \
1125 		      read_recv_state, NULL, UINT_TO_POINTER(idx)), \
1126 	BT_AUDIO_CCC(recv_state_cfg_changed)
1127 
1128 static struct bt_gatt_attr attr_bass_svc[] = {
1129 	BT_GATT_PRIMARY_SERVICE(BT_UUID_BASS),
1130 	BT_AUDIO_CHRC(BT_UUID_BASS_CONTROL_POINT,
1131 		      BT_GATT_CHRC_WRITE_WITHOUT_RESP | BT_GATT_CHRC_WRITE,
1132 		      BT_GATT_PERM_WRITE_ENCRYPT,
1133 		      NULL, write_control_point, NULL),
1134 	RECEIVE_STATE_CHARACTERISTIC(0),
1135 #if CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 1
1136 	RECEIVE_STATE_CHARACTERISTIC(1),
1137 #if CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 2
1138 	RECEIVE_STATE_CHARACTERISTIC(2)
1139 #endif /* CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 2 */
1140 #endif /* CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 1 */
1141 };
1142 
1143 static struct bt_gatt_service bass_svc = BT_GATT_SERVICE(attr_bass_svc);
1144 
bass_register(void)1145 static int bass_register(void)
1146 {
1147 	int err;
1148 
1149 	err = bt_gatt_service_register(&bass_svc);
1150 	if (err) {
1151 		LOG_DBG("Failed to register BASS service (err %d)", err);
1152 		return err;
1153 	}
1154 
1155 	LOG_DBG("BASS service registered");
1156 
1157 	return 0;
1158 }
1159 
bass_unregister(void)1160 static int bass_unregister(void)
1161 {
1162 	int err;
1163 
1164 	err = bt_gatt_service_unregister(&bass_svc);
1165 	if (err) {
1166 		LOG_DBG("Failed to unregister BASS service (err %d)", err);
1167 		return err;
1168 	}
1169 
1170 	LOG_DBG("BASS service unregistered");
1171 
1172 	return 0;
1173 }
1174 
1175 /****************************** PUBLIC API ******************************/
bt_bap_scan_delegator_register(struct bt_bap_scan_delegator_cb * cb)1176 int bt_bap_scan_delegator_register(struct bt_bap_scan_delegator_cb *cb)
1177 {
1178 	int err;
1179 
1180 	if (atomic_test_and_set_bit(scan_delegator_flags,
1181 				    SCAN_DELEGATOR_FLAG_REGISTERED_SCAN_DELIGATOR)) {
1182 		LOG_DBG("Scan delegator already registered");
1183 		return -EALREADY;
1184 	}
1185 
1186 	err = bass_register();
1187 	if (err) {
1188 		atomic_clear_bit(scan_delegator_flags,
1189 				 SCAN_DELEGATOR_FLAG_REGISTERED_SCAN_DELIGATOR);
1190 		return err;
1191 	}
1192 
1193 	/* Store the pointer to the first characteristic in each receive state */
1194 	scan_delegator.recv_states[0].attr = &bass_svc.attrs[3];
1195 	scan_delegator.recv_states[0].index = 0;
1196 #if CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 1
1197 	scan_delegator.recv_states[1].attr = &bass_svc.attrs[6];
1198 	scan_delegator.recv_states[1].index = 1;
1199 #if CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 2
1200 	scan_delegator.recv_states[2].attr = &bass_svc.attrs[9];
1201 	scan_delegator.recv_states[2].index = 2;
1202 #endif /* CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 2 */
1203 #endif /* CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT > 1 */
1204 
1205 	if (!atomic_test_and_set_bit(scan_delegator_flags,
1206 				     SCAN_DELEGATOR_FLAG_REGISTERED_PA_SYNC_CB)) {
1207 		err = bt_le_per_adv_sync_cb_register(&pa_sync_cb);
1208 		if (err) {
1209 			atomic_clear_bit(scan_delegator_flags,
1210 					 SCAN_DELEGATOR_FLAG_REGISTERED_PA_SYNC_CB);
1211 			atomic_clear_bit(scan_delegator_flags,
1212 					 SCAN_DELEGATOR_FLAG_REGISTERED_SCAN_DELIGATOR);
1213 			return err;
1214 		}
1215 	}
1216 
1217 	scan_delegator_cbs = cb;
1218 
1219 	return 0;
1220 }
1221 
bt_bap_scan_delegator_unregister(void)1222 int bt_bap_scan_delegator_unregister(void)
1223 {
1224 	int err;
1225 
1226 	if (!atomic_test_and_clear_bit(scan_delegator_flags,
1227 				       SCAN_DELEGATOR_FLAG_REGISTERED_SCAN_DELIGATOR)) {
1228 		LOG_DBG("Scan delegator not yet registered");
1229 		return -EALREADY;
1230 	}
1231 
1232 	err = bass_unregister();
1233 	if (err) {
1234 		atomic_set_bit(scan_delegator_flags,
1235 			       SCAN_DELEGATOR_FLAG_REGISTERED_SCAN_DELIGATOR);
1236 		return err;
1237 	}
1238 
1239 	scan_delegator_cbs = NULL;
1240 
1241 	return 0;
1242 }
1243 
bt_bap_scan_delegator_set_pa_state(uint8_t src_id,enum bt_bap_pa_state pa_state)1244 int bt_bap_scan_delegator_set_pa_state(uint8_t src_id,
1245 				       enum bt_bap_pa_state pa_state)
1246 {
1247 	struct bass_recv_state_internal *internal_state = bass_lookup_src_id(src_id);
1248 	struct bt_bap_scan_delegator_recv_state *recv_state;
1249 
1250 	if (internal_state == NULL) {
1251 		LOG_DBG("Could not find recv_state by src_id %u", src_id);
1252 		return -EINVAL;
1253 	}
1254 
1255 	recv_state = &internal_state->state;
1256 
1257 	if (recv_state->pa_sync_state != pa_state) {
1258 		recv_state->pa_sync_state = pa_state;
1259 		receive_state_updated(NULL, internal_state);
1260 	}
1261 
1262 	return 0;
1263 }
1264 
bt_bap_scan_delegator_set_bis_sync_state(uint8_t src_id,uint32_t bis_synced[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS])1265 int bt_bap_scan_delegator_set_bis_sync_state(
1266 	uint8_t src_id,
1267 	uint32_t bis_synced[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS])
1268 {
1269 	struct bass_recv_state_internal *internal_state = bass_lookup_src_id(src_id);
1270 	bool notify = false;
1271 
1272 	if (internal_state == NULL) {
1273 		LOG_DBG("Could not find recv_state by src_id %u", src_id);
1274 		return -EINVAL;
1275 	}
1276 
1277 	if (internal_state->state.pa_sync_state != BT_BAP_PA_STATE_SYNCED) {
1278 		LOG_DBG("PA for src_id %u isn't synced, cannot be BIG synced",
1279 			src_id);
1280 		return -EINVAL;
1281 	}
1282 
1283 	/* Verify state for all subgroups before assigning any data */
1284 	for (uint8_t i = 0U; i < internal_state->state.num_subgroups; i++) {
1285 		if (i >= CONFIG_BT_BAP_BASS_MAX_SUBGROUPS) {
1286 			break;
1287 		}
1288 
1289 		if (bis_synced[i] == BT_BAP_BIS_SYNC_NO_PREF ||
1290 		    !bits_subset_of(bis_synced[i],
1291 				    internal_state->requested_bis_sync[i])) {
1292 			LOG_DBG("Subgroup[%u] invalid bis_sync value %x for %x",
1293 				i, bis_synced[i], internal_state->requested_bis_sync[i]);
1294 
1295 			return -EINVAL;
1296 		}
1297 	}
1298 
1299 	for (uint8_t i = 0U; i < internal_state->state.num_subgroups; i++) {
1300 		struct bt_bap_bass_subgroup *subgroup =
1301 			&internal_state->state.subgroups[i];
1302 
1303 		if (i >= CONFIG_BT_BAP_BASS_MAX_SUBGROUPS) {
1304 			break;
1305 		}
1306 
1307 		if (bis_synced[i] != subgroup->bis_sync) {
1308 			notify = true;
1309 			subgroup->bis_sync = bis_synced[i];
1310 		}
1311 	}
1312 
1313 	LOG_DBG("Index %u: Source ID 0x%02x synced",
1314 		internal_state->index, src_id);
1315 
1316 	if (internal_state->state.encrypt_state == BT_BAP_BIG_ENC_STATE_BAD_CODE) {
1317 		(void)memcpy(internal_state->state.bad_code,
1318 			     internal_state->broadcast_code,
1319 			     sizeof(internal_state->state.bad_code));
1320 	}
1321 
1322 	if (notify) {
1323 		receive_state_updated(NULL, internal_state);
1324 	}
1325 
1326 	return 0;
1327 }
1328 
valid_bt_bap_scan_delegator_add_src_param(const struct bt_bap_scan_delegator_add_src_param * param)1329 static bool valid_bt_bap_scan_delegator_add_src_param(
1330 	const struct bt_bap_scan_delegator_add_src_param *param)
1331 {
1332 	uint32_t aggregated_bis_syncs = 0U;
1333 
1334 	if (param->broadcast_id > BT_AUDIO_BROADCAST_ID_MAX) {
1335 		LOG_DBG("Invalid broadcast_id: %u", param->broadcast_id);
1336 
1337 		return false;
1338 	}
1339 
1340 	CHECKIF(param->addr.type > BT_ADDR_LE_RANDOM) {
1341 		LOG_DBG("param->addr.type %u is invalid", param->addr.type);
1342 		return false;
1343 	}
1344 
1345 	CHECKIF(param->sid > BT_GAP_SID_MAX) {
1346 		LOG_DBG("param->sid %d is invalid", param->sid);
1347 		return false;
1348 	}
1349 
1350 	if (param->num_subgroups > CONFIG_BT_BAP_BASS_MAX_SUBGROUPS) {
1351 		LOG_WRN("Too many subgroups %u/%u",
1352 			param->num_subgroups,
1353 			CONFIG_BT_BAP_BASS_MAX_SUBGROUPS);
1354 
1355 		return false;
1356 	}
1357 
1358 	for (uint8_t i = 0U; i < param->num_subgroups; i++) {
1359 		const struct bt_bap_bass_subgroup *subgroup = &param->subgroups[i];
1360 
1361 		if (!bis_syncs_unique_or_no_pref(subgroup->bis_sync,
1362 						 aggregated_bis_syncs)) {
1363 			LOG_DBG("Invalid BIS sync: %u", subgroup->bis_sync);
1364 
1365 			return false;
1366 		}
1367 
1368 		if (subgroup->metadata_len > CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE) {
1369 			LOG_DBG("subgroup[%u]: Invalid metadata_len: %u",
1370 				i, subgroup->metadata_len);
1371 
1372 			return false;
1373 		}
1374 	}
1375 
1376 	return true;
1377 }
1378 
bt_bap_scan_delegator_add_src(const struct bt_bap_scan_delegator_add_src_param * param)1379 int bt_bap_scan_delegator_add_src(const struct bt_bap_scan_delegator_add_src_param *param)
1380 {
1381 	struct bass_recv_state_internal *internal_state = NULL;
1382 	struct bt_bap_scan_delegator_recv_state *state;
1383 	struct bt_le_per_adv_sync *pa_sync;
1384 
1385 	CHECKIF(!valid_bt_bap_scan_delegator_add_src_param(param)) {
1386 		return -EINVAL;
1387 	}
1388 
1389 	pa_sync = bt_le_per_adv_sync_lookup_addr(&param->addr, param->sid);
1390 
1391 	if (pa_sync != NULL) {
1392 		internal_state = bass_lookup_pa_sync(pa_sync);
1393 		if (internal_state != NULL) {
1394 			LOG_DBG("PA Sync already in a receive state with src_id %u",
1395 				internal_state->state.src_id);
1396 
1397 			return -EALREADY;
1398 		}
1399 	}
1400 
1401 	internal_state = get_free_recv_state();
1402 	if (internal_state == NULL) {
1403 		LOG_DBG("Could not get free receive state");
1404 
1405 		return -ENOMEM;
1406 	}
1407 
1408 	state = &internal_state->state;
1409 
1410 	state->src_id = next_src_id();
1411 	bt_addr_le_copy(&state->addr, &param->addr);
1412 	state->adv_sid = param->sid;
1413 	state->broadcast_id = param->broadcast_id;
1414 	state->pa_sync_state =
1415 		pa_sync == NULL ? BT_BAP_PA_STATE_NOT_SYNCED : BT_BAP_PA_STATE_SYNCED;
1416 	state->num_subgroups = param->num_subgroups;
1417 	if (state->num_subgroups > 0U) {
1418 		(void)memcpy(state->subgroups, param->subgroups,
1419 			     sizeof(state->subgroups));
1420 	} else {
1421 		(void)memset(state->subgroups, 0, sizeof(state->subgroups));
1422 	}
1423 
1424 	internal_state->active = true;
1425 	internal_state->pa_sync = pa_sync;
1426 
1427 	/* Set all requested_bis_sync to BT_BAP_BIS_SYNC_NO_PREF, as no
1428 	 * Broadcast Assistant has set any requests yet
1429 	 */
1430 	for (size_t i = 0U; i < ARRAY_SIZE(internal_state->requested_bis_sync); i++) {
1431 		internal_state->requested_bis_sync[i] = BT_BAP_BIS_SYNC_NO_PREF;
1432 	}
1433 
1434 	LOG_DBG("Index %u: New source added: ID 0x%02x",
1435 		internal_state->index, state->src_id);
1436 
1437 	receive_state_updated(NULL, internal_state);
1438 
1439 	return state->src_id;
1440 }
1441 
valid_bt_bap_scan_delegator_mod_src_param(const struct bt_bap_scan_delegator_mod_src_param * param)1442 static bool valid_bt_bap_scan_delegator_mod_src_param(
1443 	const struct bt_bap_scan_delegator_mod_src_param *param)
1444 {
1445 	uint32_t aggregated_bis_syncs = 0U;
1446 
1447 	if (param->broadcast_id > BT_AUDIO_BROADCAST_ID_MAX) {
1448 		LOG_DBG("Invalid broadcast_id: %u", param->broadcast_id);
1449 
1450 		return false;
1451 	}
1452 
1453 	if (param->num_subgroups > CONFIG_BT_BAP_BASS_MAX_SUBGROUPS) {
1454 		LOG_WRN("Too many subgroups %u/%u",
1455 			param->num_subgroups,
1456 			CONFIG_BT_BAP_BASS_MAX_SUBGROUPS);
1457 
1458 		return false;
1459 	}
1460 
1461 	for (uint8_t i = 0U; i < param->num_subgroups; i++) {
1462 		const struct bt_bap_bass_subgroup *subgroup = &param->subgroups[i];
1463 
1464 		if (subgroup->bis_sync != BT_BAP_BIS_SYNC_FAILED &&
1465 		    !bis_syncs_unique_or_no_pref(subgroup->bis_sync, aggregated_bis_syncs)) {
1466 			LOG_DBG("Invalid BIS sync: %u", subgroup->bis_sync);
1467 
1468 			return false;
1469 		}
1470 
1471 		if (subgroup->metadata_len > CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE) {
1472 			LOG_DBG("subgroup[%u]: Invalid metadata_len: %u",
1473 				i, subgroup->metadata_len);
1474 
1475 			return false;
1476 		}
1477 	}
1478 
1479 	return true;
1480 }
1481 
bt_bap_scan_delegator_mod_src(const struct bt_bap_scan_delegator_mod_src_param * param)1482 int bt_bap_scan_delegator_mod_src(const struct bt_bap_scan_delegator_mod_src_param *param)
1483 {
1484 	struct bass_recv_state_internal *internal_state = NULL;
1485 	struct bt_bap_scan_delegator_recv_state *state;
1486 	bool state_changed = false;
1487 
1488 	CHECKIF(!valid_bt_bap_scan_delegator_mod_src_param(param)) {
1489 		return -EINVAL;
1490 	}
1491 
1492 	internal_state = bass_lookup_src_id(param->src_id);
1493 	if (internal_state == NULL) {
1494 		LOG_DBG("Could not find receive state with src_id %u", param->src_id);
1495 
1496 		return -ENOENT;
1497 	}
1498 
1499 	state = &internal_state->state;
1500 
1501 	if (state->broadcast_id != param->broadcast_id) {
1502 		state->broadcast_id = param->broadcast_id;
1503 		state_changed = true;
1504 	}
1505 
1506 	if (state->num_subgroups != param->num_subgroups) {
1507 		state->num_subgroups = param->num_subgroups;
1508 		state_changed = true;
1509 	}
1510 
1511 	if (state->encrypt_state != param->encrypt_state) {
1512 		state->encrypt_state = param->encrypt_state;
1513 
1514 		if (state->encrypt_state == BT_BAP_BIG_ENC_STATE_BAD_CODE) {
1515 			(void)memcpy(state->bad_code, internal_state->broadcast_code,
1516 				     sizeof(internal_state->state.bad_code));
1517 		}
1518 
1519 		state_changed = true;
1520 	}
1521 
1522 	/* Verify that the BIS sync values is acceptable for the receive state */
1523 	for (uint8_t i = 0U; i < state->num_subgroups; i++) {
1524 		const uint32_t bis_sync = param->subgroups[i].bis_sync;
1525 		const uint32_t bis_sync_requested = internal_state->requested_bis_sync[i];
1526 
1527 		if (bis_sync != BT_BAP_BIS_SYNC_FAILED &&
1528 		    !bits_subset_of(bis_sync, bis_sync_requested)) {
1529 			LOG_DBG("Subgroup[%d] invalid bis_sync value %x for %x",
1530 				i, bis_sync, bis_sync_requested);
1531 
1532 			return -EINVAL;
1533 		}
1534 	}
1535 
1536 	for (uint8_t i = 0U; i < state->num_subgroups; i++) {
1537 		const struct bt_bap_bass_subgroup *param_subgroup = &param->subgroups[i];
1538 		struct bt_bap_bass_subgroup *subgroup = &state->subgroups[i];
1539 
1540 		if (subgroup->bis_sync != param_subgroup->bis_sync) {
1541 			subgroup->bis_sync = param_subgroup->bis_sync;
1542 			state_changed = true;
1543 		}
1544 
1545 		/* If the metadata len is 0, we shall not overwrite the existing metadata */
1546 		if (param_subgroup->metadata_len == 0U) {
1547 			continue;
1548 		}
1549 
1550 		if (subgroup->metadata_len != param_subgroup->metadata_len) {
1551 			subgroup->metadata_len = param_subgroup->metadata_len;
1552 			state_changed = true;
1553 		}
1554 
1555 		if (subgroup->metadata_len != param_subgroup->metadata_len ||
1556 		    memcmp(subgroup->metadata, param_subgroup->metadata,
1557 			   param_subgroup->metadata_len) != 0) {
1558 			(void)memcpy(subgroup->metadata,
1559 				     param_subgroup->metadata,
1560 				     param_subgroup->metadata_len);
1561 			subgroup->metadata_len = param_subgroup->metadata_len;
1562 			state_changed = true;
1563 		}
1564 	}
1565 
1566 	if (state_changed) {
1567 		LOG_DBG("Index %u: Source modified: ID 0x%02x",
1568 			internal_state->index, state->src_id);
1569 
1570 		receive_state_updated(NULL, internal_state);
1571 	}
1572 
1573 	return 0;
1574 }
1575 
bt_bap_scan_delegator_rem_src(uint8_t src_id)1576 int bt_bap_scan_delegator_rem_src(uint8_t src_id)
1577 {
1578 	struct net_buf_simple buf;
1579 
1580 	net_buf_simple_init_with_data(&buf, (void *)&src_id, sizeof(src_id));
1581 
1582 	if (scan_delegator_rem_src(NULL, &buf) == 0) {
1583 		return 0;
1584 	} else {
1585 		return -EINVAL;
1586 	}
1587 }
1588 
bt_bap_scan_delegator_foreach_state(bt_bap_scan_delegator_state_func_t func,void * user_data)1589 void bt_bap_scan_delegator_foreach_state(bt_bap_scan_delegator_state_func_t func, void *user_data)
1590 {
1591 	for (size_t i = 0U; i < ARRAY_SIZE(scan_delegator.recv_states); i++) {
1592 		if (scan_delegator.recv_states[i].active) {
1593 			bool stop;
1594 
1595 			stop = func(&scan_delegator.recv_states[i].state, user_data);
1596 			if (stop) {
1597 				return;
1598 			}
1599 		}
1600 	}
1601 }
1602 
1603 struct scan_delegator_state_find_state_param {
1604 	const struct bt_bap_scan_delegator_recv_state *recv_state;
1605 	bt_bap_scan_delegator_state_func_t func;
1606 	void *user_data;
1607 };
1608 
1609 static bool
scan_delegator_state_find_state_cb(const struct bt_bap_scan_delegator_recv_state * recv_state,void * user_data)1610 scan_delegator_state_find_state_cb(const struct bt_bap_scan_delegator_recv_state *recv_state,
1611 				   void *user_data)
1612 {
1613 	struct scan_delegator_state_find_state_param *param = user_data;
1614 	bool found;
1615 
1616 	found = param->func(recv_state, param->user_data);
1617 	if (found) {
1618 		param->recv_state = recv_state;
1619 
1620 		return true;
1621 	}
1622 
1623 	return false;
1624 }
1625 
1626 const struct bt_bap_scan_delegator_recv_state *
bt_bap_scan_delegator_find_state(bt_bap_scan_delegator_state_func_t func,void * user_data)1627 bt_bap_scan_delegator_find_state(bt_bap_scan_delegator_state_func_t func, void *user_data)
1628 {
1629 	struct scan_delegator_state_find_state_param param = {
1630 		.recv_state = NULL,
1631 		.func = func,
1632 		.user_data = user_data,
1633 	};
1634 
1635 	bt_bap_scan_delegator_foreach_state(scan_delegator_state_find_state_cb, &param);
1636 
1637 	return param.recv_state;
1638 }
1639 
bt_bap_scan_delegator_lookup_src_id(uint8_t src_id)1640 const struct bt_bap_scan_delegator_recv_state *bt_bap_scan_delegator_lookup_src_id(uint8_t src_id)
1641 {
1642 	const struct bass_recv_state_internal *internal_state = bass_lookup_src_id(src_id);
1643 
1644 	if (internal_state != NULL) {
1645 		return &internal_state->state;
1646 	}
1647 
1648 	return NULL;
1649 }
1650