use crate::dm::{AttributeQualities, Node, Privilege};
use crate::error::{ErrorCode, Result, bail};
use crate::im::ib::{
AttributeData, AttributeReport, AttributeStatus, CommandData, CommandStatus, InvokeResponse,
StatusIb,
};
use crate::im::path::AttributePath;
use crate::im::status::Status;
use crate::tlv::{ContainerKind, Tag, TlvWriter};
pub trait AccessControl {
fn allows(&self, path: &AttributePath, required: Privilege) -> Outcome;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Outcome {
Granted,
Denied,
Restricted,
}
impl Outcome {
#[must_use]
pub const fn status(self) -> Option<Status> {
match self {
Self::Granted => None,
Self::Denied => Some(Status::UnsupportedAccess),
Self::Restricted => Some(Status::AccessRestricted),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct AllowAll;
impl AccessControl for AllowAll {
fn allows(&self, _path: &AttributePath, _required: Privilege) -> Outcome {
Outcome::Granted
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum WriteOp {
#[default]
Replace,
Append,
}
impl WriteOp {
const fn of(path: &AttributePath) -> Option<Self> {
match path.list_index {
None => Some(Self::Replace),
Some(crate::im::ListIndex::Append) => Some(Self::Append),
Some(crate::im::ListIndex::At(_)) => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Lifecycle {
FabricRemoved(crate::msg::FabricIndex),
FailSafeExpired {
fabric: Option<crate::msg::FabricIndex>,
},
CommissioningComplete(crate::msg::FabricIndex),
}
pub trait ClusterHandler {
fn read(
&self,
resolved: &crate::dm::Resolved<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> core::result::Result<(), Status>;
fn data_version(&self, _resolved: &crate::dm::Resolved<'_>) -> Option<u32> {
None
}
fn write(
&self,
_resolved: &crate::dm::Resolved<'_>,
_data: &[u8],
_op: WriteOp,
_ctx: &InteractionContext<'_>,
) -> core::result::Result<(), Status> {
Err(Status::UnsupportedWrite)
}
fn invoke(
&self,
_resolved: &crate::dm::ResolvedCommand<'_>,
_fields: Option<&[u8]>,
_ctx: &InteractionContext<'_>,
_w: &mut TlvWriter<'_>,
_tag: Tag,
) -> core::result::Result<Option<crate::im::CommandId>, StatusIb> {
Err(Status::UnsupportedCommand.into())
}
fn on_lifecycle(&self, _event: Lifecycle) {}
}
impl<T: ClusterHandler + ?Sized> ClusterHandler for &T {
fn read(
&self,
resolved: &crate::dm::Resolved<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> core::result::Result<(), Status> {
(**self).read(resolved, ctx, w, tag)
}
fn data_version(&self, resolved: &crate::dm::Resolved<'_>) -> Option<u32> {
(**self).data_version(resolved)
}
fn write(
&self,
resolved: &crate::dm::Resolved<'_>,
data: &[u8],
op: WriteOp,
ctx: &InteractionContext<'_>,
) -> core::result::Result<(), Status> {
(**self).write(resolved, data, op, ctx)
}
fn invoke(
&self,
resolved: &crate::dm::ResolvedCommand<'_>,
fields: Option<&[u8]>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> core::result::Result<Option<crate::im::CommandId>, StatusIb> {
(**self).invoke(resolved, fields, ctx, w, tag)
}
fn on_lifecycle(&self, event: Lifecycle) {
(**self).on_lifecycle(event);
}
}
#[derive(Debug, Clone, Copy)]
pub struct InteractionContext<'a> {
pub timed: bool,
pub fabric_index: Option<crate::msg::FabricIndex>,
pub large_messages: bool,
pub fabric_filtered: bool,
pub now: crate::platform::Instant,
pub vendor_id_verified: bool,
pub session: Option<crate::msg::SessionId>,
pub atomic: Option<crate::im::atomic::ClaimRef<'a>>,
pub peer_node_id: Option<crate::msg::NodeId>,
pub attestation_challenge: Option<&'a crate::crypto::SymmetricKey>,
pub privilege: Option<Privilege>,
pub group: Option<crate::msg::GroupId>,
pub event_filters: Option<&'a [u8]>,
pub data_version_filters: Option<&'a [u8]>,
}
impl Default for InteractionContext<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> InteractionContext<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
timed: false,
fabric_index: None,
large_messages: false,
fabric_filtered: false,
now: crate::platform::Instant::ZERO,
session: None,
atomic: None,
peer_node_id: None,
attestation_challenge: None,
privilege: None,
group: None,
vendor_id_verified: false,
data_version_filters: None,
event_filters: None,
}
}
#[must_use]
pub const fn with_event_filters(mut self, filters: &'a [u8]) -> Self {
self.event_filters = Some(filters);
self
}
#[must_use]
pub const fn with_data_version_filters(mut self, filters: &'a [u8]) -> Self {
self.data_version_filters = Some(filters);
self
}
#[must_use]
pub const fn with_group(mut self, group: crate::msg::GroupId) -> Self {
self.group = Some(group);
self
}
#[must_use]
pub const fn with_privilege(mut self, privilege: Privilege) -> Self {
self.privilege = Some(privilege);
self
}
#[must_use]
pub const fn with_vendor_id_verified(mut self) -> Self {
self.vendor_id_verified = true;
self
}
#[must_use]
pub const fn timed(mut self) -> Self {
self.timed = true;
self
}
#[must_use]
pub const fn with_fabric(mut self, fabric_index: crate::msg::FabricIndex) -> Self {
self.fabric_index = Some(fabric_index);
self
}
#[must_use]
pub const fn with_large_messages(mut self) -> Self {
self.large_messages = true;
self
}
#[must_use]
pub const fn fabric_filtered(mut self) -> Self {
self.fabric_filtered = true;
self
}
#[must_use]
pub const fn at(mut self, now: crate::platform::Instant) -> Self {
self.now = now;
self
}
#[must_use]
pub const fn on_session(mut self, session: crate::msg::SessionId) -> Self {
self.session = Some(session);
self
}
#[must_use]
pub const fn under_claim(mut self, claim: crate::im::atomic::ClaimRef<'a>) -> Self {
self.atomic = Some(claim);
self
}
#[must_use]
pub const fn from_peer(mut self, peer_node_id: crate::msg::NodeId) -> Self {
self.peer_node_id = Some(peer_node_id);
self
}
#[must_use]
pub const fn with_attestation_challenge(
mut self,
challenge: &'a crate::crypto::SymmetricKey,
) -> Self {
self.attestation_challenge = Some(challenge);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadOutcome {
pub reports: usize,
pub truncated: bool,
pub events_through: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadCursor {
path: usize,
expansion: crate::dm::ExpandCursor,
list: Option<u32>,
event_path: usize,
event_from: u64,
done: bool,
}
impl ReadCursor {
pub const fn set_event_from(&mut self, number: u64) {
self.event_from = number;
}
#[must_use]
pub const fn event_from(&self) -> u64 {
self.event_from
}
pub const START: Self = Self {
path: 0,
expansion: crate::dm::ExpandCursor::START,
list: None,
event_path: 0,
event_from: 0,
done: false,
};
#[must_use]
pub const fn is_done(&self) -> bool {
self.done
}
}
impl Default for ReadCursor {
fn default() -> Self {
Self::START
}
}
struct ListItems<'a> {
reader: crate::tlv::TlvReader<'a>,
done: bool,
}
impl<'a> ListItems<'a> {
fn new(encoded: &'a [u8]) -> Option<Self> {
let mut reader = crate::tlv::TlvReader::new_in(encoded, ContainerKind::Structure);
let first = reader.next_element().ok()??;
if first.value.container() != Some(ContainerKind::Array) {
return None;
}
Some(Self {
reader,
done: false,
})
}
}
impl<'a> Iterator for ListItems<'a> {
type Item = Result<&'a [u8]>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
let start = self.reader.position();
let element = match self.reader.next_element() {
Ok(Some(element)) => element,
Ok(None) => {
self.done = true;
return None;
}
Err(e) => {
self.done = true;
return Some(Err(e));
}
};
if element.value == crate::tlv::Value::EndOfContainer {
self.done = true;
return None;
}
if let Err(e) = self.reader.skip_value(&element) {
self.done = true;
return Some(Err(e));
}
match self.reader.slice_from(start) {
Ok(bytes) => Some(Ok(bytes)),
Err(e) => {
self.done = true;
Some(Err(e))
}
}
}
}
struct Chunk<'w, 'b> {
w: &'w mut TlvWriter<'b>,
reports: usize,
limit: usize,
full: bool,
}
fn put_block(
w: &mut TlvWriter<'_>,
responses: &mut usize,
limit: usize,
f: impl FnOnce(&mut TlvWriter<'_>) -> Result<()>,
) -> Result<bool> {
if *responses >= limit {
return Ok(false);
}
let checkpoint = w.checkpoint();
match f(w) {
Ok(()) => {
*responses = responses.saturating_add(1);
Ok(true)
}
Err(e) if e.code() == ErrorCode::BufferTooSmall => {
w.rollback(&checkpoint);
Ok(false)
}
Err(e) => Err(e),
}
}
impl Chunk<'_, '_> {
fn put(&mut self, f: impl FnOnce(&mut TlvWriter<'_>) -> Result<()>) -> Result<bool> {
let mut reports = self.reports;
let fitted = put_block(self.w, &mut reports, self.limit, f)?;
self.reports = reports;
if !fitted {
self.full = true;
}
Ok(fitted)
}
const fn is_empty(&self) -> bool {
self.reports == 0
}
}
#[derive(Debug, Clone, Copy)]
pub struct Server<'a, A, H> {
pub node: Node<'a>,
pub access: &'a A,
pub handler: &'a H,
pub limit: usize,
pub versions: Option<&'a dyn crate::dm::DataVersionSource>,
pub events: Option<&'a dyn crate::dm::events::EventSource>,
}
impl<'a, A: AccessControl, H: ClusterHandler> Server<'a, A, H> {
#[must_use]
pub const fn new(node: Node<'a>, access: &'a A, handler: &'a H, limit: usize) -> Self {
Self {
node,
access,
handler,
limit,
versions: None,
events: None,
}
}
#[must_use]
pub const fn with_data_versions(
mut self,
versions: &'a dyn crate::dm::DataVersionSource,
) -> Self {
self.versions = Some(versions);
self
}
#[must_use]
pub const fn with_events(mut self, events: &'a dyn crate::dm::events::EventSource) -> Self {
self.events = Some(events);
self
}
fn serve_path_chunked(
&self,
path: &AttributePath,
ctx: &InteractionContext<'_>,
chunk: &mut Chunk<'_, '_>,
cursor: &mut ReadCursor,
scratch: &mut [u8],
) -> Result<bool> {
if path.enable_tag_compression {
return if path.concrete().is_some() {
self.write_status(chunk, path, Status::InvalidAction)
} else {
Ok(true)
};
}
match path.concrete() {
Some(concrete) => {
self.serve_concrete(path, concrete, ctx, chunk, cursor, scratch)
}
None => {
let mut expand = self.node.expand_from(path, cursor.expansion);
loop {
let resume = expand.cursor();
let Some(resolved) = expand.next() else {
cursor.expansion = crate::dm::ExpandCursor::START;
return Ok(true);
};
let concrete = resolved.path();
let Some(descriptor) = resolved.cluster.attribute(resolved.attribute) else {
continue;
};
let Some(required) = descriptor.access.read else {
continue;
};
if self.access.allows(&concrete, required) != Outcome::Granted {
continue;
}
if !self.write_data(&resolved, ctx, chunk, cursor, scratch)? {
cursor.expansion = resume;
return Ok(false);
}
}
}
}
}
fn serve_concrete(
&self,
path: &AttributePath,
concrete: (
crate::im::EndpointId,
crate::im::ClusterId,
crate::im::AttributeId,
),
ctx: &InteractionContext<'_>,
chunk: &mut Chunk<'_, '_>,
cursor: &mut ReadCursor,
scratch: &mut [u8],
) -> Result<bool> {
let (endpoint, cluster, attribute) = concrete;
if let Some(status) = self.access.allows(path, Privilege::View).status() {
return self.write_status(chunk, path, status);
}
let resolved = match self.node.resolve(endpoint, cluster, attribute) {
Ok(resolved) => resolved,
Err(missing) => return self.write_status(chunk, path, missing.status()),
};
let Some(descriptor) = resolved.cluster.attribute(attribute) else {
return self.write_status(chunk, path, Status::UnsupportedAttribute);
};
let Some(required) = descriptor.access.read else {
return self.write_status(chunk, path, Status::UnsupportedRead);
};
if let Some(status) = self.access.allows(path, required).status() {
return self.write_status(chunk, path, status);
}
self.write_data(&resolved, ctx, chunk, cursor, scratch)
}
fn already_held(
&self,
resolved: &crate::dm::Resolved<'_>,
ctx: &InteractionContext<'_>,
data_version: Option<u32>,
) -> bool {
let (Some(filters), Some(version)) = (ctx.data_version_filters, data_version) else {
return false;
};
let Ok(entries) = crate::im::ArrayIter::new(
filters,
ContainerKind::Structure,
crate::im::DataVersionFilter::decode,
) else {
return false;
};
let mut matched = false;
for entry in entries {
let Ok(entry) = entry else {
return false;
};
let path = &entry.path;
if path.endpoint.is_some_and(|e| e != resolved.endpoint)
|| path.cluster.is_some_and(|c| c != resolved.cluster.id)
{
continue;
}
matched = true;
if entry.data_version != version {
return false;
}
}
matched
}
fn write_data(
&self,
resolved: &crate::dm::Resolved<'_>,
ctx: &InteractionContext<'_>,
chunk: &mut Chunk<'_, '_>,
cursor: &mut ReadCursor,
scratch: &mut [u8],
) -> Result<bool> {
let path = resolved.path();
let data_version = self.handler.data_version(resolved).or_else(|| {
self.versions
.map(|v| v.version(resolved.endpoint, resolved.cluster.id))
});
if self.already_held(resolved, ctx, data_version) {
return Ok(true);
}
let mut value = TlvWriter::new_in(scratch, ContainerKind::Structure);
let global_written = crate::dm::global::encode(
resolved.cluster,
resolved.attribute,
&mut value,
Tag::Context(2),
)?;
if !global_written
&& let Err(status) = self
.handler
.read(resolved, ctx, &mut value, Tag::Context(2))
{
return self.write_status(chunk, &path, status);
}
let Ok(encoded) = value.finish() else {
return self.write_status(chunk, &path, Status::Failure);
};
if cursor.list.is_none() {
let fitted = chunk.put(|w| {
AttributeReport::Data(AttributeData {
data_version,
path,
data: encoded,
})
.encode(w)
})?;
if fitted {
return Ok(true);
}
if !chunk.is_empty() {
return Ok(false);
}
}
self.write_list_in_chunks(&path, data_version, encoded, chunk, cursor)
}
fn write_list_in_chunks(
&self,
path: &AttributePath,
data_version: Option<u32>,
encoded: &[u8],
chunk: &mut Chunk<'_, '_>,
cursor: &mut ReadCursor,
) -> Result<bool> {
let Some(items) = ListItems::new(encoded) else {
cursor.list = None;
return self.write_status(chunk, path, Status::ResourceExhausted);
};
if cursor.list.is_none() {
let fitted = chunk.put(|w| {
let mut empty = [0u8; 4];
let mut v = TlvWriter::new_in(&mut empty, ContainerKind::Structure);
v.start_array(Tag::Context(2))?;
v.end_container()?;
let empty = v.finish()?;
AttributeReport::Data(AttributeData {
data_version,
path: *path,
data: empty,
})
.encode(w)
})?;
if !fitted {
return Ok(false);
}
cursor.list = Some(0);
}
let sent = cursor.list.unwrap_or(0);
for (index, item) in items.enumerate().skip(sent as usize) {
let item = item?;
let mut append = *path;
append.list_index = Some(crate::im::ListIndex::Append);
let fitted = chunk.put(|w| {
w.start_structure(Tag::Anonymous)?;
w.start_structure(Tag::Context(1))?;
if let Some(version) = data_version {
w.unsigned(Tag::Context(0), u64::from(version))?;
}
append.encode(w, Tag::Context(1))?;
w.raw_element_retagged(item, Tag::Context(2))?;
w.end_container()?;
w.end_container()
})?;
if !fitted {
if chunk.is_empty() {
cursor.list = None;
return self.write_status(chunk, path, Status::ResourceExhausted);
}
cursor.list = Some(u32::try_from(index).unwrap_or(u32::MAX));
return Ok(false);
}
}
cursor.list = None;
Ok(true)
}
fn write_status(
&self,
chunk: &mut Chunk<'_, '_>,
path: &AttributePath,
status: Status,
) -> Result<bool> {
chunk.put(|w| {
AttributeReport::Status(AttributeStatus {
path: *path,
status: StatusIb::new(status),
})
.encode(w)
})
}
pub fn any_readable(
&self,
paths: impl IntoIterator<Item = Result<AttributePath>>,
) -> Result<bool> {
for path in paths {
let path = path?;
for resolved in self.node.expand(&path) {
let Some(descriptor) = resolved.cluster.attribute(resolved.attribute) else {
continue;
};
let Some(required) = descriptor.access.read else {
continue;
};
if self
.access
.allows(&resolved.path(), required)
.status()
.is_none()
{
return Ok(true);
}
}
}
Ok(false)
}
fn serve_event_path(
&self,
path: &crate::im::EventPath,
ctx: &InteractionContext<'_>,
chunk: &mut Chunk<'_, '_>,
from: &mut u64,
) -> Result<bool> {
let concrete = path.endpoint.zip(path.cluster).zip(path.event);
if let Some(((endpoint, cluster), event)) = concrete {
match self.node.resolve_event(endpoint, cluster, event) {
Err(missing) => {
let status = match missing {
crate::dm::Missing::Endpoint => Status::UnsupportedEndpoint,
crate::dm::Missing::Cluster => Status::UnsupportedCluster,
crate::dm::Missing::Attribute => Status::UnsupportedEvent,
};
return self.write_event_status(chunk, path, status);
}
Ok(resolved) => {
if let Some(required) = resolved.event.access.read {
let attribute_path = AttributePath::attribute(endpoint, cluster, 0);
if let Some(status) = self.access.allows(&attribute_path, required).status()
{
return self.write_event_status(chunk, path, status);
}
}
}
}
}
let Some(source) = self.events else {
return Ok(true);
};
let floor = (*from).max(self.event_floor(ctx));
let mut fitted = true;
let mut next = floor;
let mut previous: Option<crate::dm::events::Timestamp> = None;
source.each_matching(path, ctx.fabric_index, floor, &mut |record| {
let data = crate::im::EventData {
path: crate::im::EventPath {
node: None,
endpoint: Some(record.endpoint),
cluster: Some(record.cluster),
event: Some(record.event),
is_urgent: None,
},
number: record.number,
priority: record.priority as u8,
timestamp: previous
.and_then(|before| record.timestamp.delta_from(before))
.unwrap_or_else(|| record.timestamp.absolute()),
data: &record.data,
};
match chunk.put(|w| crate::im::EventReport::Data(data).encode(w)) {
Ok(true) => {
next = record.number.saturating_add(1);
previous = Some(record.timestamp);
true
}
Ok(false) | Err(_) => {
fitted = false;
false
}
}
});
*from = next;
Ok(fitted)
}
fn event_floor(&self, ctx: &InteractionContext<'_>) -> u64 {
let Some(filters) = ctx.event_filters else {
return 0;
};
let Ok(entries) = crate::im::ArrayIter::new(
filters,
ContainerKind::Structure,
crate::im::EventFilter::decode,
) else {
return 0;
};
let mut floor = 0;
for entry in entries {
let Ok(entry) = entry else {
return 0;
};
if entry.node.is_none() {
floor = floor.max(entry.event_min);
}
}
floor
}
fn write_event_status(
&self,
chunk: &mut Chunk<'_, '_>,
path: &crate::im::EventPath,
status: Status,
) -> Result<bool> {
chunk.put(|w| {
crate::im::EventReport::Status(crate::im::EventStatus {
path: *path,
status: StatusIb::new(status),
})
.encode(w)
})
}
pub fn serve<'b>(
&self,
paths: impl IntoIterator<Item = Result<AttributePath>>,
ctx: &InteractionContext<'_>,
subscription_id: Option<u32>,
scratch: &mut [u8],
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
let mut cursor = ReadCursor::START;
let (bytes, outcome) =
self.serve_chunk(paths, ctx, subscription_id, &mut cursor, scratch, buf)?;
if outcome.truncated {
bail!(ReportWouldChunk)
}
Ok((bytes, outcome))
}
pub fn serve_chunk<'b>(
&self,
paths: impl IntoIterator<Item = Result<AttributePath>>,
ctx: &InteractionContext<'_>,
subscription_id: Option<u32>,
cursor: &mut ReadCursor,
scratch: &mut [u8],
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
self.serve_chunk_with_events(
paths,
core::iter::empty::<Result<crate::im::EventPath>>(),
ctx,
subscription_id,
cursor,
scratch,
buf,
)
}
#[allow(clippy::too_many_arguments)]
pub fn serve_chunk_with_events<'b>(
&self,
paths: impl IntoIterator<Item = Result<AttributePath>>,
events: impl IntoIterator<Item = Result<crate::im::EventPath>>,
ctx: &InteractionContext<'_>,
subscription_id: Option<u32>,
cursor: &mut ReadCursor,
scratch: &mut [u8],
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
if let Some(id) = subscription_id {
w.unsigned(Tag::Context(0), u64::from(id))?;
}
w.start_array(Tag::Context(1))?;
let start = cursor.path;
let mut truncated = false;
let mut events_closed = false;
let mut events_through = 0u64;
let mut reports;
{
let mut chunk = Chunk {
w: &mut w,
reports: 0,
limit: self.limit,
full: false,
};
for (index, path) in paths.into_iter().enumerate() {
let path = path?;
if index < start {
continue;
}
cursor.path = index;
if !self.serve_path_chunked(&path, ctx, &mut chunk, cursor, scratch)? {
truncated = true;
break;
}
cursor.path = index.saturating_add(1);
cursor.expansion = crate::dm::ExpandCursor::START;
cursor.list = None;
}
reports = chunk.reports;
}
if !truncated {
w.end_container()?;
let mut opened = false;
let mut event_chunk = Chunk {
w: &mut w,
reports,
limit: self.limit,
full: false,
};
for (index, path) in events.into_iter().enumerate() {
let path = path?;
if index < cursor.event_path {
continue;
}
if !opened {
event_chunk.w.start_array(Tag::Context(2))?;
opened = true;
}
cursor.event_path = index;
let mut from = cursor.event_from;
let fitted = self.serve_event_path(&path, ctx, &mut event_chunk, &mut from)?;
cursor.event_from = from;
events_through = events_through.max(from);
if !fitted {
truncated = true;
break;
}
cursor.event_path = index.saturating_add(1);
cursor.event_from = 0;
}
reports = event_chunk.reports;
if opened {
w.end_container()?;
}
events_closed = true;
}
if truncated && reports == 0 {
bail!(BufferTooSmall)
}
if !events_closed {
w.end_container()?;
}
if truncated {
w.bool(Tag::Context(3), true)?;
} else {
cursor.done = true;
}
w.unsigned(
Tag::Context(crate::im::REVISION_TAG),
u64::from(crate::im::INTERACTION_MODEL_REVISION),
)?;
w.end_container()?;
let bytes = w.finish()?;
Ok((
bytes,
ReadOutcome {
reports,
truncated,
events_through,
},
))
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct WriteAction {
granted: Option<(
crate::im::EndpointId,
crate::im::ClusterId,
crate::im::AttributeId,
)>,
}
impl WriteAction {
#[must_use]
pub const fn new() -> Self {
Self { granted: None }
}
const fn already_granted(
&self,
endpoint: crate::im::EndpointId,
cluster: crate::im::ClusterId,
attribute: crate::im::AttributeId,
) -> bool {
match self.granted {
Some((e, c, a)) => e == endpoint && c == cluster && a == attribute,
None => false,
}
}
const fn grant(
&mut self,
endpoint: crate::im::EndpointId,
cluster: crate::im::ClusterId,
attribute: crate::im::AttributeId,
) {
self.granted = Some((endpoint, cluster, attribute));
}
}
impl<A: AccessControl, H: ClusterHandler> Server<'_, A, H> {
pub fn serve_write_path(
&self,
data: &AttributeData<'_>,
ctx: &InteractionContext<'_>,
action: &mut WriteAction,
w: &mut TlvWriter<'_>,
responses: &mut usize,
) -> Result<bool> {
let path = data.path;
if path.enable_tag_compression {
return if path.concrete().is_some() {
self.write_response_status(w, &path, Status::InvalidAction, responses)
} else {
Ok(true)
};
}
let Some(op) = WriteOp::of(&path) else {
return if path.concrete().is_some() {
self.write_response_status(w, &path, Status::InvalidAction, responses)
} else {
Ok(true)
};
};
match path.concrete() {
Some((endpoint, cluster, attribute)) => self.write_concrete(
data, endpoint, cluster, attribute, op, ctx, action, w, responses,
),
None => {
for resolved in self.node.expand(&path) {
let concrete = resolved.path();
let Some(descriptor) = resolved.cluster.attribute(resolved.attribute) else {
continue;
};
let Some(required) = descriptor.access.write else {
continue;
};
if self.access.allows(&concrete, required) != Outcome::Granted {
continue;
}
if descriptor.access.needs_timed() && !ctx.timed {
continue;
}
if descriptor.qualities.contains(AttributeQualities::ATOMIC)
&& !ctx.atomic.is_some_and(|claim| {
claim.covers(resolved.endpoint, resolved.cluster.id, resolved.attribute)
})
{
continue;
}
let status = match self.handler.write(&resolved, data.data, op, ctx) {
Ok(()) => Status::Success,
Err(status) => status,
};
if !self.write_response_status(w, &concrete, status, responses)? {
return Ok(false);
}
}
Ok(true)
}
}
}
#[expect(
clippy::too_many_arguments,
reason = "the endpoint, cluster and attribute are the path's own parts, already \
destructured by the caller"
)]
fn write_concrete(
&self,
data: &AttributeData<'_>,
endpoint: crate::im::EndpointId,
cluster: crate::im::ClusterId,
attribute: crate::im::AttributeId,
op: WriteOp,
ctx: &InteractionContext<'_>,
action: &mut WriteAction,
w: &mut TlvWriter<'_>,
responses: &mut usize,
) -> Result<bool> {
let path = data.path;
let carried = action.already_granted(endpoint, cluster, attribute);
if !carried && let Some(status) = self.access.allows(&path, Privilege::View).status() {
return self.write_response_status(w, &path, status, responses);
}
let resolved = match self.node.resolve(endpoint, cluster, attribute) {
Ok(resolved) => resolved,
Err(missing) => {
return self.write_response_status(w, &path, missing.status(), responses);
}
};
let Some(descriptor) = resolved.cluster.attribute(attribute) else {
return self.write_response_status(w, &path, Status::UnsupportedAttribute, responses);
};
let Some(required) = descriptor.access.write else {
return self.write_response_status(w, &path, Status::UnsupportedWrite, responses);
};
if !carried {
if let Some(status) = self.access.allows(&path, required).status() {
return self.write_response_status(w, &path, status, responses);
}
action.grant(endpoint, cluster, attribute);
}
if descriptor.qualities.contains(AttributeQualities::ATOMIC)
&& !ctx
.atomic
.is_some_and(|claim| claim.covers(endpoint, cluster, attribute))
{
return self.write_response_status(w, &path, Status::InvalidInState, responses);
}
if descriptor.access.needs_timed() && !ctx.timed {
return self.write_response_status(w, &path, Status::NeedsTimedInteraction, responses);
}
if descriptor.access.is_fabric_scoped() && ctx.fabric_index.is_none() {
return self.write_response_status(w, &path, Status::UnsupportedAccess, responses);
}
if let (Some(expected), Some(actual)) =
(data.data_version, self.handler.data_version(&resolved))
&& expected != actual
{
return self.write_response_status(w, &path, Status::DataVersionMismatch, responses);
}
let status = match self.handler.write(&resolved, data.data, op, ctx) {
Ok(()) => {
if let Some(versions) = self.versions {
versions.touch(resolved.endpoint, resolved.cluster.id);
}
Status::Success
}
Err(status) => status,
};
self.write_response_status(w, &path, status, responses)
}
pub fn serve_write<'b>(
&self,
writes: impl IntoIterator<Item = Result<AttributeData<'b>>>,
ctx: &InteractionContext<'_>,
more_chunked: bool,
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
if more_chunked && ctx.timed {
bail!(InvalidAction)
}
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.start_array(Tag::Context(0))?;
let mut responses = 0usize;
let mut truncated = false;
let mut action = WriteAction::new();
for data in writes {
let data = data?;
if !self.serve_write_path(&data, ctx, &mut action, &mut w, &mut responses)? {
truncated = true;
break;
}
}
w.end_container()?;
w.unsigned(
Tag::Context(crate::im::REVISION_TAG),
u64::from(crate::im::INTERACTION_MODEL_REVISION),
)?;
w.end_container()?;
let bytes = w.finish()?;
Ok((
bytes,
ReadOutcome {
reports: responses,
truncated,
events_through: 0,
},
))
}
}
impl<A: AccessControl, H: ClusterHandler> Server<'_, A, H> {
pub fn serve_invoke_command(
&self,
command: &CommandData<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
responses: &mut usize,
scratch: &mut [u8],
) -> Result<bool> {
let path = command.path;
match path.concrete() {
Some((endpoint, cluster, id)) => {
self.invoke_concrete(command, endpoint, cluster, id, ctx, w, responses, scratch)
}
None => {
for resolved in self.node.expand_commands(&path) {
let concrete = resolved.path();
let Some(required) = resolved.command.access.invoke else {
continue;
};
let attribute_path = command_as_attribute_path(&concrete);
if self.access.allows(&attribute_path, required) != Outcome::Granted {
continue;
}
if resolved.command.access.needs_large_messages() && !ctx.large_messages {
continue;
}
if resolved.command.access.is_fabric_scoped() && ctx.fabric_index.is_none() {
continue;
}
if resolved.command.access.needs_timed() && !ctx.timed {
continue;
}
if !self.run_command(&resolved, command, ctx, w, responses, scratch)? {
return Ok(false);
}
}
Ok(true)
}
}
}
#[expect(
clippy::too_many_arguments,
reason = "the endpoint, cluster and command are the path's own parts, already \
destructured by the caller"
)]
fn invoke_concrete(
&self,
command: &CommandData<'_>,
endpoint: crate::im::EndpointId,
cluster: crate::im::ClusterId,
id: crate::im::CommandId,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
responses: &mut usize,
scratch: &mut [u8],
) -> Result<bool> {
let path = command.path;
let attribute_path = command_as_attribute_path(&path);
if let Some(status) = self
.access
.allows(&attribute_path, Privilege::Operate)
.status()
{
return self.command_status(w, &path, status, command.command_ref, responses);
}
let resolved = match self.node.resolve_command(endpoint, cluster, id) {
Ok(resolved) => resolved,
Err(missing) => {
return self.command_status(
w,
&path,
missing.status(),
command.command_ref,
responses,
);
}
};
let Some(required) = resolved.command.access.invoke else {
return self.command_status(
w,
&path,
Status::UnsupportedCommand,
command.command_ref,
responses,
);
};
if let Some(status) = self.access.allows(&attribute_path, required).status() {
return self.command_status(w, &path, status, command.command_ref, responses);
}
if resolved.command.access.needs_large_messages() && !ctx.large_messages {
return self.command_status(
w,
&path,
Status::InvalidTransportType,
command.command_ref,
responses,
);
}
if resolved.command.access.is_fabric_scoped() && ctx.fabric_index.is_none() {
return self.command_status(
w,
&path,
Status::UnsupportedAccess,
command.command_ref,
responses,
);
}
if resolved.command.access.needs_timed() && !ctx.timed {
return self.command_status(
w,
&path,
Status::NeedsTimedInteraction,
command.command_ref,
responses,
);
}
self.run_command(&resolved, command, ctx, w, responses, scratch)
}
fn run_command(
&self,
resolved: &crate::dm::ResolvedCommand<'_>,
command: &CommandData<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
responses: &mut usize,
scratch: &mut [u8],
) -> Result<bool> {
if *responses >= self.limit {
return Ok(false);
}
let path = resolved.path();
let mut fields = TlvWriter::new_in(scratch, ContainerKind::Structure);
let outcome =
self.handler
.invoke(resolved, command.fields, ctx, &mut fields, Tag::Context(1));
if outcome.is_ok()
&& let Some(versions) = self.versions
{
versions.touch(resolved.endpoint, resolved.cluster.id);
}
match outcome {
Ok(Some(response_id)) => {
let Ok(encoded) = fields.finish() else {
return self.command_status(
w,
&path,
Status::Failure,
command.command_ref,
responses,
);
};
let response = CommandData {
path: crate::im::CommandPath::command(
resolved.endpoint,
resolved.cluster.id,
response_id,
),
fields: Some(encoded),
command_ref: command.command_ref,
};
if put_block(w, responses, self.limit, |w| {
InvokeResponse::Command(response).encode(w)
})? {
return Ok(true);
}
self.command_status(
w,
&path,
Status::ResourceExhausted,
command.command_ref,
responses,
)
}
Ok(None) => {
self.command_status(w, &path, Status::Success, command.command_ref, responses)
}
Err(status) => self.command_status(w, &path, status, command.command_ref, responses),
}
}
fn write_response_status(
&self,
w: &mut TlvWriter<'_>,
path: &AttributePath,
status: Status,
responses: &mut usize,
) -> Result<bool> {
put_block(w, responses, self.limit, |w| {
AttributeStatus {
path: *path,
status: StatusIb::new(status),
}
.encode(w, Tag::Anonymous)
})
}
fn command_status(
&self,
w: &mut TlvWriter<'_>,
path: &crate::im::CommandPath,
status: impl Into<StatusIb>,
command_ref: Option<u16>,
responses: &mut usize,
) -> Result<bool> {
let status = status.into();
put_block(w, responses, self.limit, |w| {
InvokeResponse::Status(CommandStatus {
path: *path,
status,
command_ref,
})
.encode(w)
})
}
pub fn serve_invoke<'b>(
&self,
commands: impl IntoIterator<Item = Result<CommandData<'b>>>,
ctx: &InteractionContext<'_>,
suppress_response: bool,
scratch: &mut [u8],
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.bool(Tag::Context(0), suppress_response)?;
w.start_array(Tag::Context(1))?;
let mut responses = 0usize;
let mut truncated = false;
for command in commands {
let command = command?;
if !self.serve_invoke_command(&command, ctx, &mut w, &mut responses, scratch)? {
truncated = true;
break;
}
}
w.end_container()?;
if truncated {
w.bool(Tag::Context(2), true)?;
}
w.unsigned(
Tag::Context(crate::im::REVISION_TAG),
u64::from(crate::im::INTERACTION_MODEL_REVISION),
)?;
w.end_container()?;
let bytes = w.finish()?;
Ok((
bytes,
ReadOutcome {
reports: responses,
truncated,
events_through: 0,
},
))
}
}
fn command_as_attribute_path(path: &crate::im::CommandPath) -> AttributePath {
AttributePath {
endpoint: path.endpoint,
cluster: path.cluster,
..AttributePath::wildcard()
}
}
impl<A: AccessControl, H: ClusterHandler> Server<'_, A, H> {
pub fn prime<'b>(
&self,
subscription_id: u32,
paths: impl IntoIterator<Item = Result<AttributePath>>,
ctx: &InteractionContext<'_>,
scratch: &mut [u8],
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
self.serve(paths, ctx, Some(subscription_id), scratch, buf)
}
pub fn report<'b, const P: usize>(
&self,
subscription: &mut crate::im::subscription::Subscription<P>,
reason: crate::im::subscription::ReportReason,
ctx: &InteractionContext<'_>,
scratch: &mut [u8],
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
let (bytes, outcome) = self.report_chunk(subscription, reason, ctx, scratch, buf)?;
if outcome.truncated {
subscription.cursor = ReadCursor::START;
bail!(ReportWouldChunk)
}
Ok((bytes, outcome))
}
pub fn report_chunk<'b, const P: usize>(
&self,
subscription: &mut crate::im::subscription::Subscription<P>,
reason: crate::im::subscription::ReportReason,
ctx: &InteractionContext<'_>,
scratch: &mut [u8],
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
use crate::im::subscription::ReportReason;
let id = subscription.id;
match reason {
ReportReason::KeepAlive => {
subscription.cursor.done = true;
self.empty_report(id, buf)
}
ReportReason::Data => {
let (paths, events, from, cursor) = subscription.report_source();
if cursor.is_done() {
*cursor = ReadCursor::START;
}
if *cursor == ReadCursor::START {
cursor.set_event_from(from);
}
let served = self.serve_chunk_with_events(
paths.iter().copied().map(Ok),
events.iter().copied().map(Ok),
ctx,
Some(id),
cursor,
scratch,
buf,
);
if let Ok((_, outcome)) = &served {
subscription.note_reported_through(outcome.events_through);
}
served
}
}
}
fn empty_report<'b>(
&self,
subscription_id: u32,
buf: &'b mut [u8],
) -> Result<(&'b [u8], ReadOutcome)> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.unsigned(Tag::Context(0), u64::from(subscription_id))?;
w.bool(Tag::Context(4), true)?;
w.unsigned(
Tag::Context(crate::im::REVISION_TAG),
u64::from(crate::im::INTERACTION_MODEL_REVISION),
)?;
w.end_container()?;
let bytes = w.finish()?;
Ok((
bytes,
ReadOutcome {
reports: 0,
truncated: false,
events_through: 0,
},
))
}
}