1use crate::clusters::generated::tls_client_management as spec_tls;
28use crate::dm::spec::{Conforming, Optional};
29use crate::dm::{Resolved, ResolvedCommand};
30use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
31use crate::msg::FabricIndex;
32use crate::tlv::{Tag, TlvWriter, ToTlv};
33
34use super::{EndpointEntry, HOSTNAME_MAX, HOSTNAME_MIN, TlsEndpointId, TlsTables, visible};
35use crate::clusters::Cluster;
36
37pub use spec_tls::attribute::{MAX_PROVISIONED, PROVISIONED_ENDPOINTS};
38pub use spec_tls::command::{
39 FIND_ENDPOINT, FIND_ENDPOINT_RESPONSE, PROVISION_ENDPOINT, PROVISION_ENDPOINT_RESPONSE,
40 REMOVE_ENDPOINT,
41};
42pub use spec_tls::{ID, PICS, REVISION, StatusCodeEnum};
43
44#[derive(Debug)]
49pub struct ClientManagement<'a, const R: usize, const C: usize, const E: usize> {
50 tables: &'a TlsTables<R, C, E>,
51}
52
53impl<'a, const R: usize, const C: usize, const E: usize> ClientManagement<'a, R, C, E> {
54 #[must_use]
56 pub const fn new(tables: &'a TlsTables<R, C, E>) -> Self {
57 Self { tables }
58 }
59
60 pub fn conforming(
62 feature_map: u32,
63 optional: &Optional<'_>,
64 ) -> crate::error::Result<Conforming<2, 3, 2, 0>> {
65 Conforming::new(&spec_tls::CLUSTER, feature_map, optional)
66 }
67
68 #[must_use]
71 pub const fn tables(&self) -> &'a TlsTables<R, C, E> {
72 self.tables
73 }
74}
75
76fn cluster_status(code: StatusCodeEnum) -> StatusIb {
78 StatusIb::cluster_failure(code.value())
79}
80
81impl<const R: usize, const C: usize, const E: usize> ClusterHandler
82 for ClientManagement<'_, R, C, E>
83{
84 fn read(
85 &self,
86 resolved: &Resolved<'_>,
87 ctx: &InteractionContext<'_>,
88 w: &mut TlvWriter<'_>,
89 tag: Tag,
90 ) -> Result<(), Status> {
91 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
92 match resolved.attribute {
93 MAX_PROVISIONED => full(w.unsigned(tag, u64::from(self.tables.max_endpoints()))),
94 PROVISIONED_ENDPOINTS => {
95 let endpoints = self.tables.endpoints();
96 full(w.start_array(tag))?;
97 for endpoint in endpoints.iter().filter(|e| visible(ctx, e.fabric_index)) {
98 full(encode_endpoint(endpoint, w, Tag::Anonymous))?;
99 }
100 full(w.end_container())
101 }
102 _ => Err(Status::UnsupportedAttribute),
103 }
104 }
105
106 fn invoke(
107 &self,
108 resolved: &ResolvedCommand<'_>,
109 fields: Option<&[u8]>,
110 ctx: &InteractionContext<'_>,
111 w: &mut TlvWriter<'_>,
112 tag: Tag,
113 ) -> Result<Option<CommandId>, StatusIb> {
114 let fabric = ctx
116 .fabric_index
117 .filter(|f| f.0 != 0)
118 .ok_or(StatusIb::from(Status::UnsupportedAccess))?;
119 let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
120 match resolved.command.id {
121 PROVISION_ENDPOINT => self.provision(fabric, payload, w, tag),
122 FIND_ENDPOINT => self.find(fabric, payload, w, tag),
123 REMOVE_ENDPOINT => self.remove(fabric, payload),
124 _ => Err(Status::UnsupportedCommand.into()),
125 }
126 }
127}
128
129impl<const R: usize, const C: usize, const E: usize> ClientManagement<'_, R, C, E> {
130 fn provision(
132 &self,
133 fabric: FabricIndex,
134 payload: &[u8],
135 w: &mut TlvWriter<'_>,
136 tag: Tag,
137 ) -> Result<Option<CommandId>, StatusIb> {
138 let decoded: spec_tls::ProvisionEndpointFields<'_> =
139 crate::clusters::decode_fields(payload)?;
140 if !(HOSTNAME_MIN..=HOSTNAME_MAX).contains(&decoded.hostname.len()) || decoded.port == 0 {
143 return Err(Status::ConstraintError.into());
144 }
145 if !self.tables.time_known() {
148 return Err(cluster_status(StatusCodeEnum::InvalidTime));
149 }
150 if !self
153 .tables
154 .roots()
155 .iter()
156 .any(|r| r.caid == decoded.caid && r.fabric_index == fabric)
157 {
158 return Err(cluster_status(StatusCodeEnum::RootCertificateNotFound));
159 }
160 let ccdid = decoded.ccdid.0;
161 if let Some(ccdid) = ccdid
162 && !self
163 .tables
164 .clients()
165 .iter()
166 .any(|c| c.ccdid == ccdid && c.fabric_index == fabric)
167 {
168 return Err(cluster_status(StatusCodeEnum::ClientCertificateNotFound));
169 }
170
171 let endpoint_id = match decoded.endpoint_id.0 {
172 None => {
173 if self.tables.count_endpoints(fabric) >= usize::from(self.tables.max_endpoints()) {
174 return Err(Status::ResourceExhausted.into());
175 }
176 if self.host_taken(fabric, decoded.hostname, decoded.port, None) {
177 return Err(cluster_status(StatusCodeEnum::EndpointAlreadyInstalled));
178 }
179 let taken = |candidate: TlsEndpointId| {
180 self.tables
181 .endpoints()
182 .iter()
183 .any(|e| e.endpoint_id == candidate)
184 };
185 let endpoint_id =
186 TlsTables::<R, C, E>::allocate(&self.tables.next_endpoint_id, taken)
187 .ok_or(StatusIb::from(Status::ResourceExhausted))?;
188 let mut hostname = heapless::Vec::new();
189 hostname
190 .extend_from_slice(decoded.hostname)
191 .map_err(|_| StatusIb::from(Status::ConstraintError))?;
192 self.tables
193 .endpoints
194 .borrow_mut()
195 .push(EndpointEntry {
196 fabric_index: fabric,
197 endpoint_id,
198 hostname,
199 port: decoded.port,
200 caid: decoded.caid,
201 ccdid,
202 reference_count: 0,
204 })
205 .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
206 endpoint_id
207 }
208 Some(endpoint_id) => {
209 if !self
210 .tables
211 .endpoints()
212 .iter()
213 .any(|e| e.endpoint_id == endpoint_id && e.fabric_index == fabric)
214 {
215 return Err(Status::NotFound.into());
216 }
217 if self.host_taken(fabric, decoded.hostname, decoded.port, Some(endpoint_id)) {
221 return Err(cluster_status(StatusCodeEnum::EndpointAlreadyInstalled));
222 }
223 let mut endpoints = self.tables.endpoints.borrow_mut();
224 let Some(entry) = endpoints
225 .iter_mut()
226 .find(|e| e.endpoint_id == endpoint_id && e.fabric_index == fabric)
227 else {
228 return Err(Status::NotFound.into());
229 };
230 entry.hostname.clear();
231 entry
232 .hostname
233 .extend_from_slice(decoded.hostname)
234 .map_err(|_| StatusIb::from(Status::ConstraintError))?;
235 entry.port = decoded.port;
236 entry.caid = decoded.caid;
237 entry.ccdid = ccdid;
238 endpoint_id
239 }
240 };
241 spec_tls::ProvisionEndpointResponseFields { endpoint_id }
242 .to_tlv(w, tag)
243 .map_err(|_| StatusIb::from(Status::Failure))?;
244 Ok(Some(PROVISION_ENDPOINT_RESPONSE))
245 }
246
247 fn find(
249 &self,
250 fabric: FabricIndex,
251 payload: &[u8],
252 w: &mut TlvWriter<'_>,
253 tag: Tag,
254 ) -> Result<Option<CommandId>, StatusIb> {
255 let decoded: spec_tls::FindEndpointFields = crate::clusters::decode_fields(payload)?;
256 if self.tables.endpoints().is_empty() {
257 return Err(Status::NotFound.into());
258 }
259 let endpoints = self.tables.endpoints();
260 let entry = endpoints
261 .iter()
262 .find(|e| e.endpoint_id == decoded.endpoint_id && e.fabric_index == fabric)
263 .ok_or(StatusIb::from(Status::NotFound))?;
264 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
265 full(w.start_structure(tag))?;
266 full(encode_endpoint(entry, w, Tag::Context(0)))?;
267 full(w.end_container())?;
268 Ok(Some(FIND_ENDPOINT_RESPONSE))
269 }
270
271 fn remove(&self, fabric: FabricIndex, payload: &[u8]) -> Result<Option<CommandId>, StatusIb> {
273 let decoded: spec_tls::RemoveEndpointFields = crate::clusters::decode_fields(payload)?;
274 if self.tables.endpoints().is_empty() {
275 return Err(Status::NotFound.into());
276 }
277 let found = self
278 .tables
279 .endpoints()
280 .iter()
281 .find(|e| e.endpoint_id == decoded.endpoint_id && e.fabric_index == fabric)
282 .map(|e| e.reference_count)
283 .ok_or(StatusIb::from(Status::NotFound))?;
284 if found > 0 {
287 return Err(Status::InvalidInState.into());
288 }
289 self.tables
290 .endpoints
291 .borrow_mut()
292 .retain(|e| !(e.endpoint_id == decoded.endpoint_id && e.fabric_index == fabric));
293 Ok(None)
294 }
295
296 fn host_taken(
298 &self,
299 fabric: FabricIndex,
300 hostname: &[u8],
301 port: u16,
302 except: Option<TlsEndpointId>,
303 ) -> bool {
304 self.tables.endpoints().iter().any(|e| {
305 e.fabric_index == fabric
306 && e.port == port
307 && e.hostname == hostname
308 && except != Some(e.endpoint_id)
309 })
310 }
311}
312
313fn encode_endpoint(
315 entry: &EndpointEntry,
316 w: &mut TlvWriter<'_>,
317 tag: Tag,
318) -> crate::error::Result<()> {
319 w.start_structure(tag)?;
320 w.unsigned(Tag::Context(0), u64::from(entry.endpoint_id))?;
321 w.octets(Tag::Context(1), &entry.hostname)?;
322 w.unsigned(Tag::Context(2), u64::from(entry.port))?;
323 w.unsigned(Tag::Context(3), u64::from(entry.caid))?;
324 match entry.ccdid {
325 Some(ccdid) => w.unsigned(Tag::Context(4), u64::from(ccdid))?,
327 None => w.null(Tag::Context(4))?,
328 }
329 w.unsigned(Tag::Context(5), u64::from(entry.reference_count))?;
330 w.unsigned(Tag::Context(254), u64::from(entry.fabric_index.0))?;
331 w.end_container()
332}
333
334impl<const R: usize, const C: usize, const E: usize> Cluster for ClientManagement<'_, R, C, E> {
336 const ID: ClusterId = ID;
337}