use crate::std_shim::{String, ToString, Vec, format, vec};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum QoS {
AtMostOnce,
#[default]
AtLeastOnce,
}
impl QoS {
fn bits(self) -> u8 {
match self {
QoS::AtMostOnce => 0,
QoS::AtLeastOnce => 1,
}
}
fn from_bits(bits: u8) -> Result<Self, CodecError> {
match bits {
0 => Ok(QoS::AtMostOnce),
1 => Ok(QoS::AtLeastOnce),
other => Err(CodecError::Malformed(format!(
"unsupported QoS {other} in a PUBLISH"
))),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CodecError {
#[error("malformed MQTT packet: {0}")]
Malformed(String),
#[error("MQTT packet of {size} bytes exceeds the {limit}-byte limit")]
TooLarge {
size: usize,
limit: usize,
},
#[error("MQTT string field is not UTF-8")]
NotUtf8,
}
pub const MAX_PACKET: usize = 8 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnAck {
pub session_present: bool,
pub code: u8,
}
impl ConnAck {
pub fn is_accepted(&self) -> bool {
self.code == 0
}
pub fn reason(&self) -> &'static str {
match self.code {
0 => "accepted",
1 => "unacceptable protocol version",
2 => "client identifier rejected",
3 => "server unavailable",
4 => "bad username or password",
5 => "not authorized",
_ => "unknown return code",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Publish {
pub topic: String,
pub qos: QoS,
pub retain: bool,
pub dup: bool,
pub packet_id: Option<u16>,
pub payload: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Packet {
ConnAck(ConnAck),
Publish(Publish),
PubAck(u16),
SubAck {
packet_id: u16,
codes: Vec<u8>,
},
PingResp,
}
#[derive(Debug, Clone)]
pub struct Connect {
pub client_id: String,
pub keep_alive_secs: u16,
pub clean_session: bool,
pub username: Option<String>,
pub password: Option<String>,
}
pub fn encode_connect(connect: &Connect) -> Vec<u8> {
let mut body = Vec::new();
put_string(&mut body, "MQTT");
body.push(4); let mut flags = 0u8;
if connect.clean_session {
flags |= 0x02;
}
if connect.username.is_some() {
flags |= 0x80;
}
if connect.password.is_some() {
flags |= 0x40;
}
body.push(flags);
body.extend_from_slice(&connect.keep_alive_secs.to_be_bytes());
put_string(&mut body, &connect.client_id);
if let Some(u) = &connect.username {
put_string(&mut body, u);
}
if let Some(p) = &connect.password {
put_string(&mut body, p);
}
frame(0x10, body)
}
pub fn encode_publish(publish: &Publish) -> Vec<u8> {
let mut header = 0x30 | (publish.qos.bits() << 1);
if publish.retain {
header |= 0x01;
}
if publish.dup {
header |= 0x08;
}
let mut body = Vec::new();
put_string(&mut body, &publish.topic);
if publish.qos != QoS::AtMostOnce {
body.extend_from_slice(&publish.packet_id.unwrap_or(0).to_be_bytes());
}
body.extend_from_slice(&publish.payload);
frame(header, body)
}
pub fn encode_puback(packet_id: u16) -> Vec<u8> {
frame(0x40, packet_id.to_be_bytes().to_vec())
}
pub fn encode_subscribe(packet_id: u16, filters: &[(String, QoS)]) -> Vec<u8> {
let mut body = Vec::new();
body.extend_from_slice(&packet_id.to_be_bytes());
for (filter, qos) in filters {
put_string(&mut body, filter);
body.push(qos.bits());
}
frame(0x82, body)
}
pub fn encode_pingreq() -> Vec<u8> {
vec![0xc0, 0x00]
}
pub fn encode_disconnect() -> Vec<u8> {
vec![0xe0, 0x00]
}
fn frame(header: u8, body: Vec<u8>) -> Vec<u8> {
let mut out = Vec::with_capacity(body.len() + 5);
out.push(header);
put_remaining_length(&mut out, body.len());
out.extend_from_slice(&body);
out
}
fn put_string(out: &mut Vec<u8>, s: &str) {
let bytes = s.as_bytes();
out.extend_from_slice(&(bytes.len() as u16).to_be_bytes());
out.extend_from_slice(bytes);
}
fn put_remaining_length(out: &mut Vec<u8>, mut value: usize) {
loop {
let mut byte = (value % 128) as u8;
value /= 128;
if value > 0 {
byte |= 0x80;
}
out.push(byte);
if value == 0 {
break;
}
}
}
pub fn decode(buf: &[u8]) -> Result<Option<(Option<Packet>, usize)>, CodecError> {
if buf.len() < 2 {
return Ok(None);
}
let header = buf[0];
let Some((remaining, length_bytes)) = take_remaining_length(&buf[1..])? else {
return Ok(None);
};
if remaining > MAX_PACKET {
return Err(CodecError::TooLarge {
size: remaining,
limit: MAX_PACKET,
});
}
let start = 1 + length_bytes;
let total = start + remaining;
if buf.len() < total {
return Ok(None);
}
let body = &buf[start..total];
let packet = decode_body(header, body)?;
Ok(Some((packet, total)))
}
fn decode_body(header: u8, body: &[u8]) -> Result<Option<Packet>, CodecError> {
match header >> 4 {
2 => {
if body.len() < 2 {
return Err(CodecError::Malformed("short CONNACK".to_string()));
}
Ok(Some(Packet::ConnAck(ConnAck {
session_present: body[0] & 0x01 == 1,
code: body[1],
})))
}
3 => {
let qos = QoS::from_bits((header >> 1) & 0x03)?;
let mut cursor = 0usize;
let topic = take_string(body, &mut cursor)?;
let packet_id = if qos == QoS::AtMostOnce {
None
} else {
Some(take_u16(body, &mut cursor)?)
};
Ok(Some(Packet::Publish(Publish {
topic,
qos,
retain: header & 0x01 == 1,
dup: header & 0x08 == 0x08,
packet_id,
payload: body[cursor..].to_vec(),
})))
}
4 => {
let mut cursor = 0usize;
Ok(Some(Packet::PubAck(take_u16(body, &mut cursor)?)))
}
9 => {
let mut cursor = 0usize;
let packet_id = take_u16(body, &mut cursor)?;
Ok(Some(Packet::SubAck {
packet_id,
codes: body[cursor..].to_vec(),
}))
}
13 => Ok(Some(Packet::PingResp)),
_ => Ok(None),
}
}
fn take_remaining_length(buf: &[u8]) -> Result<Option<(usize, usize)>, CodecError> {
let mut value = 0usize;
let mut multiplier = 1usize;
for (index, byte) in buf.iter().take(4).enumerate() {
value += usize::from(byte & 0x7f) * multiplier;
if byte & 0x80 == 0 {
return Ok(Some((value, index + 1)));
}
multiplier *= 128;
}
if buf.len() >= 4 {
return Err(CodecError::Malformed(
"remaining length is longer than four bytes".to_string(),
));
}
Ok(None)
}
fn take_u16(buf: &[u8], cursor: &mut usize) -> Result<u16, CodecError> {
if buf.len() < *cursor + 2 {
return Err(CodecError::Malformed("truncated 16-bit field".to_string()));
}
let value = u16::from_be_bytes([buf[*cursor], buf[*cursor + 1]]);
*cursor += 2;
Ok(value)
}
fn take_string(buf: &[u8], cursor: &mut usize) -> Result<String, CodecError> {
let len = usize::from(take_u16(buf, cursor)?);
if buf.len() < *cursor + len {
return Err(CodecError::Malformed("truncated string field".to_string()));
}
let s = core::str::from_utf8(&buf[*cursor..*cursor + len])
.map_err(|_| CodecError::NotUtf8)?
.to_string();
*cursor += len;
Ok(s)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_connect_carries_the_protocol_name_level_and_credentials() {
let bytes = encode_connect(&Connect {
client_id: "ven-1".into(),
keep_alive_secs: 30,
clean_session: false,
username: Some("ven-1".into()),
password: Some("token".into()),
});
assert_eq!(bytes[0], 0x10);
assert_eq!(&bytes[2..8], b"\x00\x04MQTT");
assert_eq!(bytes[8], 4);
assert_eq!(bytes[9], 0xc0);
assert_eq!(u16::from_be_bytes([bytes[10], bytes[11]]), 30);
}
#[test]
fn clean_session_is_a_single_bit_and_off_by_default_here() {
let dirty = encode_connect(&Connect {
client_id: "a".into(),
keep_alive_secs: 1,
clean_session: false,
username: None,
password: None,
});
let clean = encode_connect(&Connect {
client_id: "a".into(),
keep_alive_secs: 1,
clean_session: true,
username: None,
password: None,
});
assert_eq!(dirty[9], 0x00);
assert_eq!(clean[9], 0x02);
}
#[test]
fn a_qos1_publish_round_trips_through_the_decoder() {
let original = Publish {
topic: "openadr3/events/vens/ven-1/update".into(),
qos: QoS::AtLeastOnce,
retain: false,
dup: false,
packet_id: Some(0x1234),
payload: b"{\"objectType\":\"EVENT\"}".to_vec(),
};
let bytes = encode_publish(&original);
let (packet, used) = decode(&bytes).unwrap().unwrap();
assert_eq!(used, bytes.len());
assert_eq!(packet, Some(Packet::Publish(original)));
}
#[test]
fn a_qos0_publish_carries_no_identifier() {
let original = Publish {
topic: "t".into(),
qos: QoS::AtMostOnce,
retain: true,
dup: false,
packet_id: None,
payload: b"x".to_vec(),
};
let bytes = encode_publish(&original);
assert_eq!(bytes[0] & 0x06, 0); assert_eq!(bytes[0] & 0x01, 1); let (packet, _) = decode(&bytes).unwrap().unwrap();
assert_eq!(packet, Some(Packet::Publish(original)));
}
#[test]
fn a_connack_reports_the_session_flag_separately_from_the_code() {
let (packet, _) = decode(&[0x20, 0x02, 0x01, 0x00]).unwrap().unwrap();
let Some(Packet::ConnAck(ack)) = packet else {
panic!("expected CONNACK")
};
assert!(ack.session_present);
assert!(ack.is_accepted());
let (packet, _) = decode(&[0x20, 0x02, 0x00, 0x05]).unwrap().unwrap();
let Some(Packet::ConnAck(ack)) = packet else {
panic!("expected CONNACK")
};
assert!(!ack.session_present);
assert!(!ack.is_accepted());
assert_eq!(ack.reason(), "not authorized");
}
#[test]
fn a_suback_carries_one_code_per_filter_and_0x80_is_a_refusal() {
let (packet, _) = decode(&[0x90, 0x04, 0x00, 0x07, 0x01, 0x80])
.unwrap()
.unwrap();
assert_eq!(
packet,
Some(Packet::SubAck {
packet_id: 7,
codes: vec![0x01, 0x80],
})
);
}
#[test]
fn a_subscribe_sets_the_reserved_nibble_brokers_check() {
let bytes = encode_subscribe(9, &[("a/b".to_string(), QoS::AtLeastOnce)]);
assert_eq!(bytes[0], 0x82);
}
#[test]
fn a_partial_buffer_asks_for_more_rather_than_erroring() {
let bytes = encode_publish(&Publish {
topic: "some/topic".into(),
qos: QoS::AtLeastOnce,
retain: false,
dup: false,
packet_id: Some(1),
payload: vec![0u8; 64],
});
for cut in 0..bytes.len() {
assert_eq!(decode(&bytes[..cut]).unwrap(), None, "cut at {cut}");
}
assert!(decode(&bytes).unwrap().is_some());
}
#[test]
fn two_packets_in_one_read_are_taken_one_at_a_time() {
let mut buf = encode_puback(1);
buf.extend(encode_pingreq());
buf.extend(encode_puback(2));
let (first, used) = decode(&buf).unwrap().unwrap();
assert_eq!(first, Some(Packet::PubAck(1)));
let (second, used2) = decode(&buf[used..]).unwrap().unwrap();
assert_eq!(second, None);
let (third, _) = decode(&buf[used + used2..]).unwrap().unwrap();
assert_eq!(third, Some(Packet::PubAck(2)));
}
#[test]
fn a_remaining_length_uses_every_byte_it_needs() {
for len in [0usize, 1, 127, 128, 16_383, 16_384, 2_097_151] {
let mut out = Vec::new();
put_remaining_length(&mut out, len);
let (decoded, used) = take_remaining_length(&out).unwrap().unwrap();
assert_eq!(decoded, len);
assert_eq!(used, out.len());
}
}
#[test]
fn a_fifth_continuation_byte_is_malformed_rather_than_a_request_for_more() {
let err = take_remaining_length(&[0xff, 0xff, 0xff, 0xff, 0x7f]).unwrap_err();
assert!(matches!(err, CodecError::Malformed(_)));
}
#[test]
fn a_declared_length_beyond_the_ceiling_is_refused_before_anything_is_allocated() {
let err = decode(&[0x30, 0xff, 0xff, 0xff, 0x7f]).unwrap_err();
assert!(matches!(err, CodecError::TooLarge { .. }));
}
#[test]
fn a_qos2_publish_is_refused_rather_than_misread() {
let err = decode(&[0x34, 0x05, 0x00, 0x01, b'a', 0x00, 0x01]).unwrap_err();
assert!(matches!(err, CodecError::Malformed(_)));
}
#[test]
fn a_topic_that_is_not_utf8_is_named_as_such() {
let err = decode(&[0x30, 0x04, 0x00, 0x02, 0xff, 0xfe]).unwrap_err();
assert_eq!(err, CodecError::NotUtf8);
}
#[test]
fn a_truncated_string_field_does_not_index_past_the_body() {
let err = decode(&[0x30, 0x03, 0x00, 0x02, b'a']).unwrap_err();
assert!(matches!(err, CodecError::Malformed(_)));
}
}