1use core::cell::RefCell;
39
40use crate::clusters::generated::groupcast as spec_gc;
41use crate::config::Config;
42use crate::crypto::{SYMMETRIC_KEY_LENGTH_BYTES, SymmetricKey};
43use crate::dm::spec::{Conforming, Optional};
44use crate::dm::{Resolved, ResolvedCommand};
45use crate::group::keys::{EpochKey, GroupKeySecurityPolicy, GroupKeySet, GroupKeys, KeySetId};
46use crate::im::{
47 ClusterHandler, ClusterId, CommandId, EndpointId, InteractionContext, Status, StatusIb,
48};
49use crate::msg::{FabricIndex, GroupId};
50use crate::tlv::{Tag, TlvWriter};
51
52use super::Cluster;
53
54pub use spec_gc::attribute::{
55 FABRIC_UNDER_TEST, MAX_MCAST_ADDR_COUNT, MAX_MEMBERSHIP_COUNT, MEMBERSHIP,
56 USED_MCAST_ADDR_COUNT,
57};
58pub use spec_gc::command::{
59 CONFIGURE_AUXILIARY_ACL, JOIN_GROUP, LEAVE_GROUP, LEAVE_GROUP_RESPONSE, UPDATE_GROUP_KEY,
60};
61pub use spec_gc::{ID, MulticastAddrPolicyEnum, PICS, REVISION};
62
63pub const FEATURE_LISTENER: u32 = 1 << 0;
65
66pub const FEATURE_SENDER: u32 = 1 << 1;
68
69pub const FEATURE_PER_GROUP_ADDRESS: u32 = 1 << 2;
71
72pub const MAX_JOIN_ENDPOINTS: usize = 20;
75
76pub const MIN_MEMBERSHIP_COUNT: u16 = 10;
78
79pub const OPTIONAL: Optional<'static> = Optional {
90 attributes: &[
91 MEMBERSHIP,
92 MAX_MEMBERSHIP_COUNT,
93 MAX_MCAST_ADDR_COUNT,
94 USED_MCAST_ADDR_COUNT,
95 FABRIC_UNDER_TEST,
96 ],
97 commands: &[
98 JOIN_GROUP,
99 LEAVE_GROUP,
100 LEAVE_GROUP_RESPONSE,
101 UPDATE_GROUP_KEY,
102 CONFIGURE_AUXILIARY_ACL,
103 ],
104 events: &[],
105};
106
107#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Membership<const E: usize> {
110 pub fabric_index: FabricIndex,
112 pub group: GroupId,
114 pub endpoints: heapless::Vec<EndpointId, E>,
116 pub key_set: KeySetId,
119 pub has_auxiliary_acl: bool,
121 pub policy: MulticastAddrPolicyEnum,
123}
124
125#[derive(Debug)]
132pub struct Groupcast<
133 'a,
134 C: Config,
135 const M: usize,
136 const E: usize,
137 const K: usize = 15,
138 const G: usize = 20,
139> {
140 keys: &'a RefCell<GroupKeys<C, K, G>>,
141 memberships: RefCell<heapless::Vec<Membership<E>, M>>,
142 feature_map: u32,
143 max_membership: u16,
144 max_addresses: u16,
145 fabric_under_test: core::cell::Cell<FabricIndex>,
146}
147
148impl<'a, C: Config, const M: usize, const E: usize, const K: usize, const G: usize>
149 Groupcast<'a, C, M, E, K, G>
150{
151 #[must_use]
157 #[expect(
158 clippy::cast_possible_truncation,
159 reason = "§11.27.6.2's MaxMembershipCount is a uint16, and the branch above holds M to it"
160 )]
161 pub const fn new(keys: &'a RefCell<GroupKeys<C, K, G>>, feature_map: u32) -> Self {
162 Self {
163 keys,
164 memberships: RefCell::new(heapless::Vec::new()),
165 feature_map,
166 max_membership: if M > u16::MAX as usize {
167 u16::MAX
168 } else {
169 M as u16
170 },
171 max_addresses: 1,
172 fabric_under_test: core::cell::Cell::new(FabricIndex(0)),
173 }
174 }
175
176 #[must_use]
182 pub const fn with_max_addresses(mut self, max: u16) -> Self {
183 self.max_addresses = max;
184 self
185 }
186
187 pub fn conforming(
189 feature_map: u32,
190 optional: &Optional<'_>,
191 ) -> crate::error::Result<Conforming<5, 6, 1, 1>> {
192 Conforming::new(&spec_gc::CLUSTER, feature_map, optional)
193 }
194
195 #[must_use]
197 pub fn memberships(&self) -> core::cell::Ref<'_, heapless::Vec<Membership<E>, M>> {
198 self.memberships.borrow()
199 }
200
201 #[must_use]
203 pub const fn is_listener(&self) -> bool {
204 self.feature_map & FEATURE_LISTENER != 0
205 }
206
207 #[must_use]
209 pub const fn is_sender(&self) -> bool {
210 self.feature_map & FEATURE_SENDER != 0
211 }
212
213 #[must_use]
220 pub const fn per_fabric_limit(&self) -> usize {
221 (self.max_membership / 2) as usize
222 }
223
224 pub fn remove_fabric(&self, fabric: FabricIndex) {
226 self.memberships
227 .borrow_mut()
228 .retain(|m| m.fabric_index != fabric);
229 }
230
231 fn count_groups(&self, fabric: FabricIndex) -> usize {
232 self.memberships
233 .borrow()
234 .iter()
235 .filter(|m| m.fabric_index == fabric)
236 .count()
237 }
238}
239
240impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize> ClusterHandler
241 for Groupcast<'_, C, M, E, K, G>
242{
243 fn on_lifecycle(&self, event: crate::im::Lifecycle) {
246 if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
247 self.remove_fabric(fabric);
248 }
249 }
250 fn read(
251 &self,
252 resolved: &Resolved<'_>,
253 ctx: &InteractionContext<'_>,
254 w: &mut TlvWriter<'_>,
255 tag: Tag,
256 ) -> core::result::Result<(), Status> {
257 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
258 match resolved.attribute {
259 MAX_MEMBERSHIP_COUNT => full(w.unsigned(tag, u64::from(self.max_membership))),
260 MAX_MCAST_ADDR_COUNT => full(w.unsigned(tag, u64::from(self.max_addresses))),
261 USED_MCAST_ADDR_COUNT => {
262 let memberships = self.memberships.borrow();
266 let per_group = memberships
267 .iter()
268 .filter(|m| m.policy == MulticastAddrPolicyEnum::PerGroup)
269 .count();
270 let iana = usize::from(
271 memberships
272 .iter()
273 .any(|m| m.policy == MulticastAddrPolicyEnum::IanaAddr),
274 );
275 full(w.unsigned(tag, (per_group.saturating_add(iana)) as u64))
276 }
277 FABRIC_UNDER_TEST => full(w.unsigned(tag, u64::from(self.fabric_under_test.get().0))),
278 MEMBERSHIP => {
279 let memberships = self.memberships.borrow();
280 full(w.start_array(tag))?;
281 for entry in memberships
282 .iter()
283 .filter(|m| !ctx.fabric_filtered || ctx.fabric_index == Some(m.fabric_index))
284 {
285 full(w.start_structure(Tag::Anonymous))?;
286 full(w.unsigned(Tag::Context(0), u64::from(entry.group.0)))?;
287 if self.is_listener() {
288 full(w.start_array(Tag::Context(1)))?;
289 for endpoint in &entry.endpoints {
290 full(w.unsigned(Tag::Anonymous, u64::from(*endpoint)))?;
291 }
292 full(w.end_container())?;
293 }
294 full(w.unsigned(Tag::Context(2), u64::from(entry.key_set)))?;
295 if self.is_listener() {
296 full(w.bool(Tag::Context(3), entry.has_auxiliary_acl))?;
297 }
298 full(w.unsigned(Tag::Context(4), u64::from(entry.policy.value())))?;
299 full(w.unsigned(Tag::Context(254), u64::from(entry.fabric_index.0)))?;
300 full(w.end_container())?;
301 }
302 full(w.end_container())
303 }
304 _ => Err(Status::UnsupportedAttribute),
305 }
306 }
307
308 fn invoke(
309 &self,
310 resolved: &ResolvedCommand<'_>,
311 fields: Option<&[u8]>,
312 ctx: &InteractionContext<'_>,
313 w: &mut TlvWriter<'_>,
314 tag: Tag,
315 ) -> core::result::Result<Option<CommandId>, StatusIb> {
316 let fabric = ctx
318 .fabric_index
319 .filter(|f| f.0 != 0)
320 .ok_or(StatusIb::from(Status::UnsupportedAccess))?;
321 let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
322 match resolved.command.id {
323 JOIN_GROUP => self.join(fabric, payload, ctx),
324 LEAVE_GROUP => self.leave(fabric, payload, w, tag),
325 UPDATE_GROUP_KEY => self.update_key(fabric, payload),
326 CONFIGURE_AUXILIARY_ACL => self.configure_auxiliary_acl(fabric, payload),
327 _ => Err(Status::UnsupportedCommand.into()),
328 }
329 }
330}
331
332impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize>
333 Groupcast<'_, C, M, E, K, G>
334{
335 fn join(
337 &self,
338 fabric: FabricIndex,
339 payload: &[u8],
340 ctx: &InteractionContext<'_>,
341 ) -> core::result::Result<Option<CommandId>, StatusIb> {
342 let decoded: spec_gc::JoinGroupFields<'_> = super::decode_fields(payload)?;
343 if decoded.group_id.0 == 0 || decoded.key_set_id == 0 {
346 return Err(Status::ConstraintError.into());
347 }
348
349 let mut endpoints: heapless::Vec<EndpointId, E> = heapless::Vec::new();
350 for endpoint in decoded.endpoints.iter() {
351 let endpoint = endpoint.map_err(|_| StatusIb::from(Status::InvalidCommand))?;
352 if endpoint == 0 {
356 return Err(Status::UnsupportedEndpoint.into());
357 }
358 if endpoints.contains(&endpoint) {
359 continue;
361 }
362 if endpoints.len() >= MAX_JOIN_ENDPOINTS {
363 return Err(Status::ConstraintError.into());
364 }
365 endpoints
366 .push(endpoint)
367 .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
368 }
369
370 if endpoints.is_empty() && !self.is_sender() {
372 return Err(Status::ConstraintError.into());
373 }
374 if !endpoints.is_empty() && !self.is_listener() {
375 return Err(Status::ConstraintError.into());
376 }
377 if decoded.use_auxiliary_acl.is_some()
383 && !ctx
384 .privilege
385 .is_some_and(|granted| granted.grants(crate::dm::access::Privilege::Administer))
386 {
387 return Err(Status::UnsupportedAccess.into());
388 }
389 let policy = decoded
390 .mcast_addr_policy
391 .unwrap_or(MulticastAddrPolicyEnum::IanaAddr);
392 if policy == MulticastAddrPolicyEnum::PerGroup
393 && self.feature_map & FEATURE_PER_GROUP_ADDRESS == 0
394 {
395 return Err(Status::ConstraintError.into());
396 }
397
398 self.install_key(fabric, decoded.key_set_id, decoded.key)?;
399
400 let existing = self.find(fabric, decoded.group_id);
401 if existing.is_none() {
402 if self.count_groups(fabric) >= self.per_fabric_limit() {
404 return Err(Status::ResourceExhausted.into());
405 }
406 }
407
408 let mut memberships = self.memberships.borrow_mut();
409 match memberships
410 .iter_mut()
411 .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
412 {
413 Some(entry) => {
414 if decoded.replace_endpoints == Some(true) {
417 entry.endpoints.clear();
418 }
419 for endpoint in &endpoints {
420 if !entry.endpoints.contains(endpoint)
421 && entry.endpoints.push(*endpoint).is_err()
422 {
423 return Err(Status::ResourceExhausted.into());
424 }
425 }
426 entry.key_set = decoded.key_set_id;
427 entry.policy = policy;
428 if let Some(use_acl) = decoded.use_auxiliary_acl {
429 entry.has_auxiliary_acl = use_acl;
430 }
431 }
432 None => {
433 memberships
434 .push(Membership {
435 fabric_index: fabric,
436 group: decoded.group_id,
437 endpoints,
438 key_set: decoded.key_set_id,
439 has_auxiliary_acl: decoded.use_auxiliary_acl.unwrap_or(false),
440 policy,
441 })
442 .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
443 }
444 }
445 drop(memberships);
446
447 self.keys
450 .borrow_mut()
451 .map_group(fabric, decoded.group_id, decoded.key_set_id)?;
452 Ok(None)
453 }
454
455 fn leave(
457 &self,
458 fabric: FabricIndex,
459 payload: &[u8],
460 w: &mut TlvWriter<'_>,
461 tag: Tag,
462 ) -> core::result::Result<Option<CommandId>, StatusIb> {
463 let decoded: spec_gc::LeaveGroupFields<'_> = super::decode_fields(payload)?;
464 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
465
466 if decoded.group_id.0 == 0 {
468 if self.count_groups(fabric) == 0 {
469 return Err(Status::NotFound.into());
470 }
471 let groups: heapless::Vec<GroupId, M> = self
472 .memberships
473 .borrow()
474 .iter()
475 .filter(|m| m.fabric_index == fabric)
476 .map(|m| m.group)
477 .collect();
478 for group in groups {
479 self.forget(fabric, group);
480 }
481 full(w.start_structure(tag))?;
485 full(w.unsigned(Tag::Context(0), 0))?;
486 full(w.start_array(Tag::Context(1)))?;
487 full(w.end_container())?;
488 full(w.end_container())?;
489 return Ok(Some(LEAVE_GROUP_RESPONSE));
490 }
491
492 if self.find(fabric, decoded.group_id).is_none() {
494 return Err(Status::NotFound.into());
495 }
496
497 let mut removed: heapless::Vec<EndpointId, E> = heapless::Vec::new();
498 match decoded.endpoints {
499 Some(list) => {
501 let mut memberships = self.memberships.borrow_mut();
502 if let Some(entry) = memberships
503 .iter_mut()
504 .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
505 {
506 for endpoint in list.iter() {
507 let Ok(endpoint) = endpoint else { continue };
508 if entry.endpoints.contains(&endpoint) {
512 entry.endpoints.retain(|e| *e != endpoint);
513 let _ = removed.push(endpoint);
514 }
515 }
516 }
517 let emptied = memberships.iter().any(|m| {
518 m.fabric_index == fabric
519 && m.group == decoded.group_id
520 && m.endpoints.is_empty()
521 });
522 drop(memberships);
523 if emptied && !self.is_sender() {
527 self.forget(fabric, decoded.group_id);
528 }
529 }
530 None => {
532 if let Some(entry) = self.find(fabric, decoded.group_id) {
533 removed = entry.endpoints;
534 }
535 self.forget(fabric, decoded.group_id);
536 }
537 }
538
539 full(w.start_structure(tag))?;
540 full(w.unsigned(Tag::Context(0), u64::from(decoded.group_id.0)))?;
541 full(w.start_array(Tag::Context(1)))?;
542 for endpoint in &removed {
543 full(w.unsigned(Tag::Anonymous, u64::from(*endpoint)))?;
544 }
545 full(w.end_container())?;
546 full(w.end_container())?;
547 Ok(Some(LEAVE_GROUP_RESPONSE))
548 }
549
550 fn update_key(
552 &self,
553 fabric: FabricIndex,
554 payload: &[u8],
555 ) -> core::result::Result<Option<CommandId>, StatusIb> {
556 let decoded: spec_gc::UpdateGroupKeyFields<'_> = super::decode_fields(payload)?;
557 if decoded.group_id.0 == 0 || decoded.key_set_id == 0 {
558 return Err(Status::ConstraintError.into());
559 }
560 if self.find(fabric, decoded.group_id).is_none() {
563 return Err(Status::NotFound.into());
564 }
565 self.install_key(fabric, decoded.key_set_id, decoded.key)?;
566 if let Some(entry) = self
567 .memberships
568 .borrow_mut()
569 .iter_mut()
570 .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
571 {
572 entry.key_set = decoded.key_set_id;
573 }
574 self.keys
575 .borrow_mut()
576 .map_group(fabric, decoded.group_id, decoded.key_set_id)?;
577 Ok(None)
578 }
579
580 fn configure_auxiliary_acl(
582 &self,
583 fabric: FabricIndex,
584 payload: &[u8],
585 ) -> core::result::Result<Option<CommandId>, StatusIb> {
586 let decoded: spec_gc::ConfigureAuxiliaryACLFields = super::decode_fields(payload)?;
587 let mut memberships = self.memberships.borrow_mut();
588 let Some(entry) = memberships
589 .iter_mut()
590 .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
591 else {
592 return Err(Status::NotFound.into());
593 };
594 entry.has_auxiliary_acl = decoded.use_auxiliary_acl;
595 Ok(None)
596 }
597
598 fn install_key(
604 &self,
605 fabric: FabricIndex,
606 key_set: KeySetId,
607 key: Option<&[u8]>,
608 ) -> core::result::Result<(), Status> {
609 let mut keys = self.keys.borrow_mut();
610 match key {
611 Some(key) => {
612 if key.len() != SYMMETRIC_KEY_LENGTH_BYTES {
613 return Err(Status::ConstraintError);
614 }
615 if keys.key_set(fabric, key_set).is_some() {
618 return Err(Status::AlreadyExists);
619 }
620 let bytes = <[u8; SYMMETRIC_KEY_LENGTH_BYTES]>::try_from(key)
621 .map_err(|_| Status::ConstraintError)?;
622 let mut epoch_keys = heapless::Vec::new();
623 epoch_keys
624 .push(EpochKey {
625 key: SymmetricKey::new(bytes),
626 start_time_us: 1,
629 })
630 .map_err(|_| Status::ResourceExhausted)?;
631 keys.write_key_set(GroupKeySet {
632 fabric_index: fabric,
633 id: key_set,
634 policy: GroupKeySecurityPolicy::TrustFirst,
635 epoch_keys,
636 })
637 }
638 None if keys.key_set(fabric, key_set).is_none() => Err(Status::NotFound),
641 None => Ok(()),
642 }
643 }
644
645 fn find(&self, fabric: FabricIndex, group: GroupId) -> Option<Membership<E>> {
646 self.memberships
647 .borrow()
648 .iter()
649 .find(|m| m.fabric_index == fabric && m.group == group)
650 .cloned()
651 }
652
653 fn forget(&self, fabric: FabricIndex, group: GroupId) {
655 let key_set = self.find(fabric, group).map(|m| m.key_set);
656 self.memberships
657 .borrow_mut()
658 .retain(|m| !(m.fabric_index == fabric && m.group == group));
659 let mut keys = self.keys.borrow_mut();
660 let remaining: heapless::Vec<_, 32> = keys
661 .map()
662 .iter()
663 .filter(|(f, g, _)| *f == fabric && *g != group)
664 .map(|(_, g, set)| (*g, *set))
665 .collect();
666 let _ = keys.replace_map(fabric, &remaining);
667 if let Some(key_set) = key_set
671 && !self
672 .memberships
673 .borrow()
674 .iter()
675 .any(|m| m.fabric_index == fabric && m.key_set == key_set)
676 {
677 let _ = keys.remove_key_set(fabric, key_set);
678 }
679 }
680}
681
682impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize> Cluster
684 for Groupcast<'_, C, M, E, K, G>
685{
686 const ID: ClusterId = ID;
687}