use core::cell::RefCell;
use crate::clusters::generated::groupcast as spec_gc;
use crate::config::Config;
use crate::crypto::{SYMMETRIC_KEY_LENGTH_BYTES, SymmetricKey};
use crate::dm::spec::{Conforming, Optional};
use crate::dm::{Resolved, ResolvedCommand};
use crate::group::keys::{EpochKey, GroupKeySecurityPolicy, GroupKeySet, GroupKeys, KeySetId};
use crate::im::{
ClusterHandler, ClusterId, CommandId, EndpointId, InteractionContext, Status, StatusIb,
};
use crate::msg::{FabricIndex, GroupId};
use crate::tlv::{Tag, TlvWriter};
use super::Cluster;
pub use spec_gc::attribute::{
FABRIC_UNDER_TEST, MAX_MCAST_ADDR_COUNT, MAX_MEMBERSHIP_COUNT, MEMBERSHIP,
USED_MCAST_ADDR_COUNT,
};
pub use spec_gc::command::{
CONFIGURE_AUXILIARY_ACL, JOIN_GROUP, LEAVE_GROUP, LEAVE_GROUP_RESPONSE, UPDATE_GROUP_KEY,
};
pub use spec_gc::{ID, MulticastAddrPolicyEnum, PICS, REVISION};
pub const FEATURE_LISTENER: u32 = 1 << 0;
pub const FEATURE_SENDER: u32 = 1 << 1;
pub const FEATURE_PER_GROUP_ADDRESS: u32 = 1 << 2;
pub const MAX_JOIN_ENDPOINTS: usize = 20;
pub const MIN_MEMBERSHIP_COUNT: u16 = 10;
pub const OPTIONAL: Optional<'static> = Optional {
attributes: &[
MEMBERSHIP,
MAX_MEMBERSHIP_COUNT,
MAX_MCAST_ADDR_COUNT,
USED_MCAST_ADDR_COUNT,
FABRIC_UNDER_TEST,
],
commands: &[
JOIN_GROUP,
LEAVE_GROUP,
LEAVE_GROUP_RESPONSE,
UPDATE_GROUP_KEY,
CONFIGURE_AUXILIARY_ACL,
],
events: &[],
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Membership<const E: usize> {
pub fabric_index: FabricIndex,
pub group: GroupId,
pub endpoints: heapless::Vec<EndpointId, E>,
pub key_set: KeySetId,
pub has_auxiliary_acl: bool,
pub policy: MulticastAddrPolicyEnum,
}
#[derive(Debug)]
pub struct Groupcast<
'a,
C: Config,
const M: usize,
const E: usize,
const K: usize = 15,
const G: usize = 20,
> {
keys: &'a RefCell<GroupKeys<C, K, G>>,
memberships: RefCell<heapless::Vec<Membership<E>, M>>,
feature_map: u32,
max_membership: u16,
max_addresses: u16,
fabric_under_test: core::cell::Cell<FabricIndex>,
}
impl<'a, C: Config, const M: usize, const E: usize, const K: usize, const G: usize>
Groupcast<'a, C, M, E, K, G>
{
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "§11.27.6.2's MaxMembershipCount is a uint16, and the branch above holds M to it"
)]
pub const fn new(keys: &'a RefCell<GroupKeys<C, K, G>>, feature_map: u32) -> Self {
Self {
keys,
memberships: RefCell::new(heapless::Vec::new()),
feature_map,
max_membership: if M > u16::MAX as usize {
u16::MAX
} else {
M as u16
},
max_addresses: 1,
fabric_under_test: core::cell::Cell::new(FabricIndex(0)),
}
}
#[must_use]
pub const fn with_max_addresses(mut self, max: u16) -> Self {
self.max_addresses = max;
self
}
pub fn conforming(
feature_map: u32,
optional: &Optional<'_>,
) -> crate::error::Result<Conforming<5, 6, 1, 1>> {
Conforming::new(&spec_gc::CLUSTER, feature_map, optional)
}
#[must_use]
pub fn memberships(&self) -> core::cell::Ref<'_, heapless::Vec<Membership<E>, M>> {
self.memberships.borrow()
}
#[must_use]
pub const fn is_listener(&self) -> bool {
self.feature_map & FEATURE_LISTENER != 0
}
#[must_use]
pub const fn is_sender(&self) -> bool {
self.feature_map & FEATURE_SENDER != 0
}
#[must_use]
pub const fn per_fabric_limit(&self) -> usize {
(self.max_membership / 2) as usize
}
pub fn remove_fabric(&self, fabric: FabricIndex) {
self.memberships
.borrow_mut()
.retain(|m| m.fabric_index != fabric);
}
fn count_groups(&self, fabric: FabricIndex) -> usize {
self.memberships
.borrow()
.iter()
.filter(|m| m.fabric_index == fabric)
.count()
}
}
impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize> ClusterHandler
for Groupcast<'_, C, M, E, K, G>
{
fn on_lifecycle(&self, event: crate::im::Lifecycle) {
if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
self.remove_fabric(fabric);
}
}
fn read(
&self,
resolved: &Resolved<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> core::result::Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
match resolved.attribute {
MAX_MEMBERSHIP_COUNT => full(w.unsigned(tag, u64::from(self.max_membership))),
MAX_MCAST_ADDR_COUNT => full(w.unsigned(tag, u64::from(self.max_addresses))),
USED_MCAST_ADDR_COUNT => {
let memberships = self.memberships.borrow();
let per_group = memberships
.iter()
.filter(|m| m.policy == MulticastAddrPolicyEnum::PerGroup)
.count();
let iana = usize::from(
memberships
.iter()
.any(|m| m.policy == MulticastAddrPolicyEnum::IanaAddr),
);
full(w.unsigned(tag, (per_group.saturating_add(iana)) as u64))
}
FABRIC_UNDER_TEST => full(w.unsigned(tag, u64::from(self.fabric_under_test.get().0))),
MEMBERSHIP => {
let memberships = self.memberships.borrow();
full(w.start_array(tag))?;
for entry in memberships
.iter()
.filter(|m| !ctx.fabric_filtered || ctx.fabric_index == Some(m.fabric_index))
{
full(w.start_structure(Tag::Anonymous))?;
full(w.unsigned(Tag::Context(0), u64::from(entry.group.0)))?;
if self.is_listener() {
full(w.start_array(Tag::Context(1)))?;
for endpoint in &entry.endpoints {
full(w.unsigned(Tag::Anonymous, u64::from(*endpoint)))?;
}
full(w.end_container())?;
}
full(w.unsigned(Tag::Context(2), u64::from(entry.key_set)))?;
if self.is_listener() {
full(w.bool(Tag::Context(3), entry.has_auxiliary_acl))?;
}
full(w.unsigned(Tag::Context(4), u64::from(entry.policy.value())))?;
full(w.unsigned(Tag::Context(254), u64::from(entry.fabric_index.0)))?;
full(w.end_container())?;
}
full(w.end_container())
}
_ => Err(Status::UnsupportedAttribute),
}
}
fn invoke(
&self,
resolved: &ResolvedCommand<'_>,
fields: Option<&[u8]>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> core::result::Result<Option<CommandId>, StatusIb> {
let fabric = ctx
.fabric_index
.filter(|f| f.0 != 0)
.ok_or(StatusIb::from(Status::UnsupportedAccess))?;
let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
match resolved.command.id {
JOIN_GROUP => self.join(fabric, payload, ctx),
LEAVE_GROUP => self.leave(fabric, payload, w, tag),
UPDATE_GROUP_KEY => self.update_key(fabric, payload),
CONFIGURE_AUXILIARY_ACL => self.configure_auxiliary_acl(fabric, payload),
_ => Err(Status::UnsupportedCommand.into()),
}
}
}
impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize>
Groupcast<'_, C, M, E, K, G>
{
fn join(
&self,
fabric: FabricIndex,
payload: &[u8],
ctx: &InteractionContext<'_>,
) -> core::result::Result<Option<CommandId>, StatusIb> {
let decoded: spec_gc::JoinGroupFields<'_> = super::decode_fields(payload)?;
if decoded.group_id.0 == 0 || decoded.key_set_id == 0 {
return Err(Status::ConstraintError.into());
}
let mut endpoints: heapless::Vec<EndpointId, E> = heapless::Vec::new();
for endpoint in decoded.endpoints.iter() {
let endpoint = endpoint.map_err(|_| StatusIb::from(Status::InvalidCommand))?;
if endpoint == 0 {
return Err(Status::UnsupportedEndpoint.into());
}
if endpoints.contains(&endpoint) {
continue;
}
if endpoints.len() >= MAX_JOIN_ENDPOINTS {
return Err(Status::ConstraintError.into());
}
endpoints
.push(endpoint)
.map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
}
if endpoints.is_empty() && !self.is_sender() {
return Err(Status::ConstraintError.into());
}
if !endpoints.is_empty() && !self.is_listener() {
return Err(Status::ConstraintError.into());
}
if decoded.use_auxiliary_acl.is_some()
&& !ctx
.privilege
.is_some_and(|granted| granted.grants(crate::dm::access::Privilege::Administer))
{
return Err(Status::UnsupportedAccess.into());
}
let policy = decoded
.mcast_addr_policy
.unwrap_or(MulticastAddrPolicyEnum::IanaAddr);
if policy == MulticastAddrPolicyEnum::PerGroup
&& self.feature_map & FEATURE_PER_GROUP_ADDRESS == 0
{
return Err(Status::ConstraintError.into());
}
self.install_key(fabric, decoded.key_set_id, decoded.key)?;
let existing = self.find(fabric, decoded.group_id);
if existing.is_none() {
if self.count_groups(fabric) >= self.per_fabric_limit() {
return Err(Status::ResourceExhausted.into());
}
}
let mut memberships = self.memberships.borrow_mut();
match memberships
.iter_mut()
.find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
{
Some(entry) => {
if decoded.replace_endpoints == Some(true) {
entry.endpoints.clear();
}
for endpoint in &endpoints {
if !entry.endpoints.contains(endpoint)
&& entry.endpoints.push(*endpoint).is_err()
{
return Err(Status::ResourceExhausted.into());
}
}
entry.key_set = decoded.key_set_id;
entry.policy = policy;
if let Some(use_acl) = decoded.use_auxiliary_acl {
entry.has_auxiliary_acl = use_acl;
}
}
None => {
memberships
.push(Membership {
fabric_index: fabric,
group: decoded.group_id,
endpoints,
key_set: decoded.key_set_id,
has_auxiliary_acl: decoded.use_auxiliary_acl.unwrap_or(false),
policy,
})
.map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
}
}
drop(memberships);
self.keys
.borrow_mut()
.map_group(fabric, decoded.group_id, decoded.key_set_id)?;
Ok(None)
}
fn leave(
&self,
fabric: FabricIndex,
payload: &[u8],
w: &mut TlvWriter<'_>,
tag: Tag,
) -> core::result::Result<Option<CommandId>, StatusIb> {
let decoded: spec_gc::LeaveGroupFields<'_> = super::decode_fields(payload)?;
let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
if decoded.group_id.0 == 0 {
if self.count_groups(fabric) == 0 {
return Err(Status::NotFound.into());
}
let groups: heapless::Vec<GroupId, M> = self
.memberships
.borrow()
.iter()
.filter(|m| m.fabric_index == fabric)
.map(|m| m.group)
.collect();
for group in groups {
self.forget(fabric, group);
}
full(w.start_structure(tag))?;
full(w.unsigned(Tag::Context(0), 0))?;
full(w.start_array(Tag::Context(1)))?;
full(w.end_container())?;
full(w.end_container())?;
return Ok(Some(LEAVE_GROUP_RESPONSE));
}
if self.find(fabric, decoded.group_id).is_none() {
return Err(Status::NotFound.into());
}
let mut removed: heapless::Vec<EndpointId, E> = heapless::Vec::new();
match decoded.endpoints {
Some(list) => {
let mut memberships = self.memberships.borrow_mut();
if let Some(entry) = memberships
.iter_mut()
.find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
{
for endpoint in list.iter() {
let Ok(endpoint) = endpoint else { continue };
if entry.endpoints.contains(&endpoint) {
entry.endpoints.retain(|e| *e != endpoint);
let _ = removed.push(endpoint);
}
}
}
let emptied = memberships.iter().any(|m| {
m.fabric_index == fabric
&& m.group == decoded.group_id
&& m.endpoints.is_empty()
});
drop(memberships);
if emptied && !self.is_sender() {
self.forget(fabric, decoded.group_id);
}
}
None => {
if let Some(entry) = self.find(fabric, decoded.group_id) {
removed = entry.endpoints;
}
self.forget(fabric, decoded.group_id);
}
}
full(w.start_structure(tag))?;
full(w.unsigned(Tag::Context(0), u64::from(decoded.group_id.0)))?;
full(w.start_array(Tag::Context(1)))?;
for endpoint in &removed {
full(w.unsigned(Tag::Anonymous, u64::from(*endpoint)))?;
}
full(w.end_container())?;
full(w.end_container())?;
Ok(Some(LEAVE_GROUP_RESPONSE))
}
fn update_key(
&self,
fabric: FabricIndex,
payload: &[u8],
) -> core::result::Result<Option<CommandId>, StatusIb> {
let decoded: spec_gc::UpdateGroupKeyFields<'_> = super::decode_fields(payload)?;
if decoded.group_id.0 == 0 || decoded.key_set_id == 0 {
return Err(Status::ConstraintError.into());
}
if self.find(fabric, decoded.group_id).is_none() {
return Err(Status::NotFound.into());
}
self.install_key(fabric, decoded.key_set_id, decoded.key)?;
if let Some(entry) = self
.memberships
.borrow_mut()
.iter_mut()
.find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
{
entry.key_set = decoded.key_set_id;
}
self.keys
.borrow_mut()
.map_group(fabric, decoded.group_id, decoded.key_set_id)?;
Ok(None)
}
fn configure_auxiliary_acl(
&self,
fabric: FabricIndex,
payload: &[u8],
) -> core::result::Result<Option<CommandId>, StatusIb> {
let decoded: spec_gc::ConfigureAuxiliaryACLFields = super::decode_fields(payload)?;
let mut memberships = self.memberships.borrow_mut();
let Some(entry) = memberships
.iter_mut()
.find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
else {
return Err(Status::NotFound.into());
};
entry.has_auxiliary_acl = decoded.use_auxiliary_acl;
Ok(None)
}
fn install_key(
&self,
fabric: FabricIndex,
key_set: KeySetId,
key: Option<&[u8]>,
) -> core::result::Result<(), Status> {
let mut keys = self.keys.borrow_mut();
match key {
Some(key) => {
if key.len() != SYMMETRIC_KEY_LENGTH_BYTES {
return Err(Status::ConstraintError);
}
if keys.key_set(fabric, key_set).is_some() {
return Err(Status::AlreadyExists);
}
let bytes = <[u8; SYMMETRIC_KEY_LENGTH_BYTES]>::try_from(key)
.map_err(|_| Status::ConstraintError)?;
let mut epoch_keys = heapless::Vec::new();
epoch_keys
.push(EpochKey {
key: SymmetricKey::new(bytes),
start_time_us: 1,
})
.map_err(|_| Status::ResourceExhausted)?;
keys.write_key_set(GroupKeySet {
fabric_index: fabric,
id: key_set,
policy: GroupKeySecurityPolicy::TrustFirst,
epoch_keys,
})
}
None if keys.key_set(fabric, key_set).is_none() => Err(Status::NotFound),
None => Ok(()),
}
}
fn find(&self, fabric: FabricIndex, group: GroupId) -> Option<Membership<E>> {
self.memberships
.borrow()
.iter()
.find(|m| m.fabric_index == fabric && m.group == group)
.cloned()
}
fn forget(&self, fabric: FabricIndex, group: GroupId) {
let key_set = self.find(fabric, group).map(|m| m.key_set);
self.memberships
.borrow_mut()
.retain(|m| !(m.fabric_index == fabric && m.group == group));
let mut keys = self.keys.borrow_mut();
let remaining: heapless::Vec<_, 32> = keys
.map()
.iter()
.filter(|(f, g, _)| *f == fabric && *g != group)
.map(|(_, g, set)| (*g, *set))
.collect();
let _ = keys.replace_map(fabric, &remaining);
if let Some(key_set) = key_set
&& !self
.memberships
.borrow()
.iter()
.any(|m| m.fabric_index == fabric && m.key_set == key_set)
{
let _ = keys.remove_key_set(fabric, key_set);
}
}
}
impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize> Cluster
for Groupcast<'_, C, M, E, K, G>
{
const ID: ClusterId = ID;
}