1use bitflags::bitflags;
19
20use super::ids::{ExchangeId, GroupId, NodeId, ProtocolId, SessionId, VendorId};
21use crate::bytes::Cursor;
22use crate::error::{Error, ErrorCode, Result, bail};
23
24pub const MESSAGE_FORMAT_VERSION: u8 = 0;
29
30bitflags! {
31 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37 pub struct MessageFlags: u8 {
38 const SOURCE_PRESENT = 0b0000_0100;
40 const DSIZ_0 = 0b0000_0001;
42 const DSIZ_1 = 0b0000_0010;
44 const VERSION = 0b1111_0000;
46 }
47}
48
49bitflags! {
50 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52 pub struct SecurityFlags: u8 {
53 const PRIVACY = 0b1000_0000;
55 const CONTROL = 0b0100_0000;
57 const MESSAGE_EXTENSIONS = 0b0010_0000;
59 const SESSION_TYPE_0 = 0b0000_0001;
61 const SESSION_TYPE_1 = 0b0000_0010;
63 }
64}
65
66bitflags! {
67 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69 pub struct ExchangeFlags: u8 {
70 const INITIATOR = 0b0000_0001;
72 const ACKNOWLEDGEMENT = 0b0000_0010;
75 const RELIABILITY = 0b0000_0100;
77 const SECURED_EXTENSIONS = 0b0000_1000;
80 const VENDOR = 0b0001_0000;
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
87pub enum SessionType {
88 #[default]
91 Unicast,
92 Group,
94}
95
96impl SessionType {
97 const fn bits(self) -> u8 {
98 match self {
99 Self::Unicast => 0,
100 Self::Group => 1,
101 }
102 }
103
104 const fn from_bits(bits: u8) -> Result<Self> {
105 match bits & 0b11 {
106 0 => Ok(Self::Unicast),
107 1 => Ok(Self::Group),
108 _ => Err(Error::new(ErrorCode::MessageReserved)),
111 }
112 }
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
118pub enum Destination {
119 #[default]
121 None,
122 Node(NodeId),
124 Group(GroupId),
126}
127
128impl Destination {
129 const fn dsiz(self) -> u8 {
130 match self {
131 Self::None => 0,
132 Self::Node(_) => 1,
133 Self::Group(_) => 2,
134 }
135 }
136
137 const fn encoded_len(self) -> usize {
138 match self {
139 Self::None => 0,
140 Self::Node(_) => 8,
141 Self::Group(_) => 2,
142 }
143 }
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct MessageHeader {
149 pub session_id: SessionId,
151 pub session_type: SessionType,
153 pub privacy: bool,
155 pub control: bool,
157 pub message_counter: u32,
159 pub source: Option<NodeId>,
161 pub destination: Destination,
163}
164
165impl Default for MessageHeader {
166 fn default() -> Self {
167 Self {
168 session_id: SessionId::UNSECURED,
169 session_type: SessionType::Unicast,
170 privacy: false,
171 control: false,
172 message_counter: 0,
173 source: None,
174 destination: Destination::None,
175 }
176 }
177}
178
179impl MessageHeader {
180 #[must_use]
185 pub const fn is_unsecured(&self) -> bool {
186 matches!(self.session_type, SessionType::Unicast) && self.session_id.0 == 0
187 }
188
189 #[must_use]
191 pub const fn encoded_len(&self) -> usize {
192 const BASE: usize = 8;
194 let src = if self.source.is_some() { 8 } else { 0 };
195 BASE.saturating_add(src)
196 .saturating_add(self.destination.encoded_len())
197 }
198
199 pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
201 let mut w = Cursor::writer(out);
202
203 let mut flags = MessageFlags::from_bits_retain(MESSAGE_FORMAT_VERSION << 4);
204 if self.source.is_some() {
205 flags |= MessageFlags::SOURCE_PRESENT;
206 }
207 flags = MessageFlags::from_bits_retain(flags.bits() | self.destination.dsiz());
208 w.u8(flags.bits())?;
209 w.u16(self.session_id.0)?;
210
211 let mut security = SecurityFlags::from_bits_retain(self.session_type.bits());
212 if self.privacy {
213 security |= SecurityFlags::PRIVACY;
214 }
215 if self.control {
216 security |= SecurityFlags::CONTROL;
217 }
218 w.u8(security.bits())?;
219 w.u32(self.message_counter)?;
220
221 if let Some(source) = self.source {
222 w.u64(source.0)?;
223 }
224 match self.destination {
225 Destination::None => {}
226 Destination::Node(n) => w.u64(n.0)?,
227 Destination::Group(g) => w.u16(g.0)?,
228 }
229 Ok(w.position())
230 }
231
232 pub fn decode(buf: &[u8]) -> Result<(Self, &[u8])> {
234 let mut r = Cursor::reader(buf, ErrorCode::MessageTruncated);
235
236 let flags = MessageFlags::from_bits_retain(r.read_u8()?);
237 let version = (flags.bits() & MessageFlags::VERSION.bits()) >> 4;
238 if version != MESSAGE_FORMAT_VERSION {
239 bail!(UnsupportedVersion)
242 }
243
244 let session_id = SessionId(r.read_u16()?);
245 let security = SecurityFlags::from_bits_retain(r.read_u8()?);
246 let session_type = SessionType::from_bits(security.bits())?;
247 let message_counter = r.read_u32()?;
248
249 let source = if flags.contains(MessageFlags::SOURCE_PRESENT) {
250 Some(NodeId(r.read_u64()?))
251 } else {
252 None
253 };
254
255 let dsiz = flags.bits() & 0b11;
256 let destination = match dsiz {
257 0 => Destination::None,
258 1 => Destination::Node(NodeId(r.read_u64()?)),
259 2 => Destination::Group(GroupId(r.read_u16()?)),
260 _ => bail!(MessageReserved),
262 };
263
264 if security.contains(SecurityFlags::MESSAGE_EXTENSIONS) {
268 let len = usize::from(r.read_u16()?);
269 r.skip(len)?;
270 }
271
272 let header = Self {
273 session_id,
274 session_type,
275 privacy: security.contains(SecurityFlags::PRIVACY),
276 control: security.contains(SecurityFlags::CONTROL),
277 message_counter,
278 source,
279 destination,
280 };
281 Ok((header, r.rest()))
282 }
283}
284
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287pub struct ProtocolHeader {
288 pub initiator: bool,
290 pub acknowledged_counter: Option<u32>,
292 pub reliability: bool,
294 pub exchange_id: ExchangeId,
296 pub protocol: ProtocolId,
298 pub opcode: u8,
300}
301
302impl Default for ProtocolHeader {
303 fn default() -> Self {
304 Self {
305 initiator: false,
306 acknowledged_counter: None,
307 reliability: false,
308 exchange_id: ExchangeId(0),
309 protocol: ProtocolId::SECURE_CHANNEL,
310 opcode: 0,
311 }
312 }
313}
314
315impl ProtocolHeader {
316 #[must_use]
318 pub const fn encoded_len(&self) -> usize {
319 const BASE: usize = 6;
321 let vendor = if self.protocol.is_common() { 0 } else { 2 };
322 let ack = if self.acknowledged_counter.is_some() {
323 4
324 } else {
325 0
326 };
327 BASE.saturating_add(vendor).saturating_add(ack)
328 }
329
330 pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
332 let mut w = Cursor::writer(out);
333
334 let mut flags = ExchangeFlags::empty();
335 if self.initiator {
336 flags |= ExchangeFlags::INITIATOR;
337 }
338 if self.acknowledged_counter.is_some() {
339 flags |= ExchangeFlags::ACKNOWLEDGEMENT;
340 }
341 if self.reliability {
342 flags |= ExchangeFlags::RELIABILITY;
343 }
344 if !self.protocol.is_common() {
345 flags |= ExchangeFlags::VENDOR;
346 }
347 w.u8(flags.bits())?;
348 w.u8(self.opcode)?;
349 w.u16(self.exchange_id.0)?;
350 if !self.protocol.is_common() {
351 w.u16(self.protocol.vendor.0)?;
352 }
353 w.u16(self.protocol.id)?;
354 if let Some(ack) = self.acknowledged_counter {
355 w.u32(ack)?;
356 }
357 Ok(w.position())
358 }
359
360 pub fn decode(buf: &[u8]) -> Result<(Self, &[u8])> {
362 let mut r = Cursor::reader(buf, ErrorCode::MessageTruncated);
363
364 let flags = ExchangeFlags::from_bits_retain(r.read_u8()?);
365 let opcode = r.read_u8()?;
366 let exchange_id = ExchangeId(r.read_u16()?);
367 let vendor = if flags.contains(ExchangeFlags::VENDOR) {
368 VendorId(r.read_u16()?)
369 } else {
370 VendorId::COMMON
371 };
372 let protocol = ProtocolId {
373 vendor,
374 id: r.read_u16()?,
375 };
376 let acknowledged_counter = if flags.contains(ExchangeFlags::ACKNOWLEDGEMENT) {
377 Some(r.read_u32()?)
378 } else {
379 None
380 };
381
382 if flags.contains(ExchangeFlags::SECURED_EXTENSIONS) {
385 let len = usize::from(r.read_u16()?);
386 r.skip(len)?;
387 }
388
389 let header = Self {
390 initiator: flags.contains(ExchangeFlags::INITIATOR),
391 acknowledged_counter,
392 reliability: flags.contains(ExchangeFlags::RELIABILITY),
393 exchange_id,
394 protocol,
395 opcode,
396 };
397 Ok((header, r.rest()))
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 fn round_trip(header: &MessageHeader) {
406 let mut buf = [0u8; 64];
407 let n = header.encode(&mut buf).expect("encode");
408 assert_eq!(n, header.encoded_len(), "encoded_len disagrees with encode");
409 let (decoded, rest) = MessageHeader::decode(&buf[..n]).expect("decode");
410 assert_eq!(&decoded, header);
411 assert!(rest.is_empty());
412 }
413
414 #[test]
415 fn message_header_round_trips() {
416 round_trip(&MessageHeader::default());
417 round_trip(&MessageHeader {
418 session_id: SessionId(0x1234),
419 session_type: SessionType::Unicast,
420 message_counter: 0xDEAD_BEEF,
421 source: Some(NodeId(0x0102_0304_0506_0708)),
422 destination: Destination::Node(NodeId(1)),
423 ..MessageHeader::default()
424 });
425 round_trip(&MessageHeader {
426 session_id: SessionId(5),
427 session_type: SessionType::Group,
428 destination: Destination::Group(GroupId(0x4242)),
429 control: true,
430 privacy: true,
431 ..MessageHeader::default()
432 });
433 }
434
435 #[test]
436 fn the_wire_layout_is_little_endian_and_in_order() {
437 let header = MessageHeader {
438 session_id: SessionId(0x1234),
439 message_counter: 0x0A0B_0C0D,
440 source: Some(NodeId(0x1122_3344_5566_7788)),
441 destination: Destination::Group(GroupId(0xABCD)),
442 ..MessageHeader::default()
443 };
444 let mut buf = [0u8; 64];
445 let n = header.encode(&mut buf).expect("encode");
446 assert_eq!(
447 &buf[..n],
448 &[
449 0x06, 0x34, 0x12, 0x00, 0x0D, 0x0C, 0x0B, 0x0A, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xCD, 0xAB,
461 ]
462 );
463 }
464
465 #[test]
466 fn a_reserved_version_is_dropped() {
467 let buf = [0x10, 0, 0, 0, 0, 0, 0, 0];
469 assert_eq!(
470 MessageHeader::decode(&buf).unwrap_err().code(),
471 ErrorCode::UnsupportedVersion
472 );
473 }
474
475 #[test]
476 fn a_reserved_dsiz_is_dropped() {
477 let buf = [0x03, 0, 0, 0, 0, 0, 0, 0];
479 assert_eq!(
480 MessageHeader::decode(&buf).unwrap_err().code(),
481 ErrorCode::MessageReserved
482 );
483 }
484
485 #[test]
486 fn a_reserved_session_type_is_dropped() {
487 let buf = [0x00, 0, 0, 0x02, 0, 0, 0, 0];
489 assert_eq!(
490 MessageHeader::decode(&buf).unwrap_err().code(),
491 ErrorCode::MessageReserved
492 );
493 }
494
495 #[test]
496 fn truncation_at_every_length_is_an_error_not_a_panic() {
497 let header = MessageHeader {
498 source: Some(NodeId(7)),
499 destination: Destination::Node(NodeId(8)),
500 ..MessageHeader::default()
501 };
502 let mut buf = [0u8; 64];
503 let n = header.encode(&mut buf).expect("encode");
504 for cut in 0..n {
505 assert!(
506 MessageHeader::decode(&buf[..cut]).is_err(),
507 "a {cut}-octet header should not decode"
508 );
509 }
510 }
511
512 #[test]
513 fn a_too_small_buffer_is_an_error() {
514 let header = MessageHeader {
515 source: Some(NodeId(7)),
516 ..MessageHeader::default()
517 };
518 let mut buf = [0u8; 4];
519 assert!(header.encode(&mut buf).is_err());
520 }
521
522 #[test]
523 fn message_extensions_are_skipped() {
524 let buf = [
526 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0xAA, 0xBB, 0xCC, 0x99, ];
534 let (header, rest) = MessageHeader::decode(&buf).expect("decode");
535 assert_eq!(header.message_counter, 0);
536 assert_eq!(rest, &[0x99]);
537 }
538
539 #[test]
540 fn a_lying_extension_length_is_an_error() {
541 let buf = [0x00, 0, 0, 0x20, 0, 0, 0, 0, 0xFF, 0xFF, 0xAA];
542 assert_eq!(
543 MessageHeader::decode(&buf).unwrap_err().code(),
544 ErrorCode::MessageTruncated
545 );
546 }
547
548 fn protocol_round_trip(header: &ProtocolHeader) {
549 let mut buf = [0u8; 32];
550 let n = header.encode(&mut buf).expect("encode");
551 assert_eq!(n, header.encoded_len(), "encoded_len disagrees with encode");
552 let (decoded, rest) = ProtocolHeader::decode(&buf[..n]).expect("decode");
553 assert_eq!(&decoded, header);
554 assert!(rest.is_empty());
555 }
556
557 #[test]
558 fn protocol_header_round_trips() {
559 protocol_round_trip(&ProtocolHeader::default());
560 protocol_round_trip(&ProtocolHeader {
561 initiator: true,
562 reliability: true,
563 acknowledged_counter: Some(0x1234_5678),
564 exchange_id: ExchangeId(0xBEEF),
565 protocol: ProtocolId::INTERACTION_MODEL,
566 opcode: 0x02,
567 });
568 protocol_round_trip(&ProtocolHeader {
569 protocol: ProtocolId {
570 vendor: VendorId::TEST_1,
571 id: 0x0042,
572 },
573 ..ProtocolHeader::default()
574 });
575 }
576
577 #[test]
578 fn a_vendor_protocol_carries_its_vendor_id() {
579 let common = ProtocolHeader::default();
580 let vendor = ProtocolHeader {
581 protocol: ProtocolId {
582 vendor: VendorId::TEST_1,
583 id: 1,
584 },
585 ..ProtocolHeader::default()
586 };
587 assert_eq!(
588 vendor.encoded_len(),
589 common.encoded_len() + 2,
590 "the V flag adds exactly the Protocol Vendor ID field"
591 );
592 }
593
594 #[test]
595 fn payload_follows_the_protocol_header() {
596 let header = ProtocolHeader {
597 exchange_id: ExchangeId(1),
598 protocol: ProtocolId::INTERACTION_MODEL,
599 opcode: 5,
600 ..ProtocolHeader::default()
601 };
602 let mut buf = [0u8; 32];
603 let n = header.encode(&mut buf).expect("encode");
604 buf[n] = 0xAB;
605 let (decoded, payload) = ProtocolHeader::decode(&buf[..=n]).expect("decode");
606 assert_eq!(decoded.opcode, 5);
607 assert_eq!(payload, &[0xAB]);
608 }
609
610 #[test]
611 fn protocol_truncation_is_an_error_not_a_panic() {
612 let header = ProtocolHeader {
613 acknowledged_counter: Some(1),
614 protocol: ProtocolId {
615 vendor: VendorId::TEST_1,
616 id: 1,
617 },
618 ..ProtocolHeader::default()
619 };
620 let mut buf = [0u8; 32];
621 let n = header.encode(&mut buf).expect("encode");
622 for cut in 0..n {
623 assert!(ProtocolHeader::decode(&buf[..cut]).is_err(), "cut {cut}");
624 }
625 }
626}