use bytes::{Buf, Bytes, BytesMut};
use super::property::{self, PROP_ID_LEN, PropertyId, properties_encoded_len, write_properties_len};
use super::reason_code::ReasonCode;
use crate::{DecodeError, EncodeError, PacketType, QoS, primitives, varint};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PublishProperties {
pub payload_format_indicator: Option<u8>,
pub message_expiry_interval: Option<u32>,
pub topic_alias: Option<u16>,
pub response_topic: Option<String>,
pub correlation_data: Option<Bytes>,
pub subscription_identifiers: Vec<u32>,
pub user_properties: Vec<(String, String)>,
pub content_type: Option<String>,
}
impl PublishProperties {
fn encoded_len(&self) -> usize {
let mut len = 0;
if self.payload_format_indicator.is_some() {
len += PROP_ID_LEN + PropertyId::PAYLOAD_FORMAT_INDICATOR_LEN;
}
if self.message_expiry_interval.is_some() {
len += PROP_ID_LEN + PropertyId::MESSAGE_EXPIRY_INTERVAL_LEN;
}
if self.topic_alias.is_some() {
len += PROP_ID_LEN + PropertyId::TOPIC_ALIAS_LEN;
}
if let Some(ref s) = self.response_topic {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
if let Some(ref d) = self.correlation_data {
len += PROP_ID_LEN + primitives::binary_encoded_len(d.len());
}
for &v in &self.subscription_identifiers {
len += PROP_ID_LEN + varint::len(v);
}
for (k, v) in &self.user_properties {
len += PROP_ID_LEN + primitives::string_pair_encoded_len(k.len(), v.len());
}
if let Some(ref s) = self.content_type {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
len
}
fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
write_properties_len(self.encoded_len(), buf);
if let Some(v) = self.payload_format_indicator {
primitives::write_u8(PropertyId::PayloadFormatIndicator as u8, buf);
primitives::write_u8(v, buf);
}
if let Some(v) = self.message_expiry_interval {
primitives::write_u8(PropertyId::MessageExpiryInterval as u8, buf);
primitives::write_u32(v, buf);
}
if let Some(v) = self.topic_alias {
primitives::write_u8(PropertyId::TopicAlias as u8, buf);
primitives::write_u16(v, buf);
}
if let Some(ref s) = self.response_topic {
primitives::write_u8(PropertyId::ResponseTopic as u8, buf);
primitives::write_string(s, buf)?;
}
if let Some(ref d) = self.correlation_data {
primitives::write_u8(PropertyId::CorrelationData as u8, buf);
primitives::write_binary(d, buf)?;
}
for &v in &self.subscription_identifiers {
primitives::write_u8(PropertyId::SubscriptionIdentifier as u8, buf);
let mut tmp = [0u8; 4];
let n = varint::encode_to(v, &mut tmp);
buf.extend_from_slice(&tmp[..n]);
}
for (k, v) in &self.user_properties {
primitives::write_u8(PropertyId::UserProperty as u8, buf);
primitives::write_string_pair(k, v, buf)?;
}
if let Some(ref s) = self.content_type {
primitives::write_u8(PropertyId::ContentType as u8, buf);
primitives::write_string(s, buf)?;
}
Ok(())
}
fn decode(mut buf: Bytes) -> Result<Self, DecodeError> {
let mut props = Self::default();
while buf.has_remaining() {
let id_byte = primitives::read_u8(&mut buf)?;
let id = PropertyId::try_from(id_byte).map_err(|_| DecodeError::InvalidProperty {
packet_type: PacketType::Publish,
id: id_byte,
})?;
match id {
PropertyId::PayloadFormatIndicator => {
if props.payload_format_indicator.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.payload_format_indicator = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::MessageExpiryInterval => {
if props.message_expiry_interval.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.message_expiry_interval = Some(primitives::read_u32(&mut buf)?);
}
PropertyId::TopicAlias => {
if props.topic_alias.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.topic_alias = Some(primitives::read_u16(&mut buf)?);
}
PropertyId::ResponseTopic => {
if props.response_topic.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.response_topic = Some(primitives::read_string(&mut buf)?);
}
PropertyId::CorrelationData => {
if props.correlation_data.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.correlation_data = Some(primitives::read_binary(&mut buf)?);
}
PropertyId::SubscriptionIdentifier => {
props.subscription_identifiers.push(varint::decode(&mut buf)?);
}
PropertyId::UserProperty => {
props.user_properties.push(primitives::read_string_pair(&mut buf)?);
}
PropertyId::ContentType => {
if props.content_type.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.content_type = Some(primitives::read_string(&mut buf)?);
}
_ => {
return Err(DecodeError::InvalidProperty {
packet_type: PacketType::Publish,
id: id_byte,
});
}
}
}
Ok(props)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Publish {
pub dup: bool,
pub qos: QoS,
pub retain: bool,
pub topic: String,
pub pkid: Option<u16>,
pub properties: PublishProperties,
pub payload: Bytes,
}
impl Publish {
pub(super) fn flags(&self) -> u8 {
let mut f: u8 = 0;
if self.dup {
f |= 0x08;
}
f |= (self.qos as u8) << 1;
if self.retain {
f |= 0x01;
}
f
}
pub(super) fn encoded_body_len(&self) -> usize {
let mut len = 2 + self.topic.len();
if self.qos != QoS::AtMostOnce {
len += 2;
}
len += properties_encoded_len(self.properties.encoded_len());
len += self.payload.len();
len
}
pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
if self.qos == QoS::AtMostOnce && self.pkid.is_some() {
return Err(EncodeError::InvalidState {
reason: "QoS 0 must not carry pkid",
});
}
if self.qos != QoS::AtMostOnce && self.pkid.is_none() {
return Err(EncodeError::InvalidState {
reason: "QoS > 0 must carry pkid",
});
}
primitives::write_string(&self.topic, buf)?;
if let Some(pkid) = self.pkid {
primitives::write_u16(pkid, buf);
}
self.properties.encode(buf)?;
buf.extend_from_slice(&self.payload);
Ok(())
}
pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
let dup = header_flags & 0x08 != 0;
let qos = QoS::try_from((header_flags >> 1) & 0x03)?;
let retain = header_flags & 0x01 != 0;
let topic = primitives::read_string(&mut buf)?;
let pkid = if qos != QoS::AtMostOnce {
Some(primitives::read_u16(&mut buf)?)
} else {
None
};
let props_buf = property::read_properties_bytes(&mut buf)?;
let properties = PublishProperties::decode(props_buf)?;
let payload = buf.split_to(buf.remaining());
Ok(Self {
dup,
qos,
retain,
topic,
pkid,
properties,
payload,
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PubAckProperties {
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
impl PubAckProperties {
fn encoded_len(&self) -> usize {
let mut len = 0;
if let Some(ref s) = self.reason_string {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
for (k, v) in &self.user_properties {
len += PROP_ID_LEN + primitives::string_pair_encoded_len(k.len(), v.len());
}
len
}
fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
write_properties_len(self.encoded_len(), buf);
if let Some(ref s) = self.reason_string {
primitives::write_u8(PropertyId::ReasonString as u8, buf);
primitives::write_string(s, buf)?;
}
for (k, v) in &self.user_properties {
primitives::write_u8(PropertyId::UserProperty as u8, buf);
primitives::write_string_pair(k, v, buf)?;
}
Ok(())
}
fn decode(mut buf: Bytes, packet_type: PacketType) -> Result<Self, DecodeError> {
let mut props = Self::default();
while buf.has_remaining() {
let id_byte = primitives::read_u8(&mut buf)?;
let id = PropertyId::try_from(id_byte).map_err(|_| DecodeError::InvalidProperty {
packet_type,
id: id_byte,
})?;
match id {
PropertyId::ReasonString => {
if props.reason_string.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.reason_string = Some(primitives::read_string(&mut buf)?);
}
PropertyId::UserProperty => {
props.user_properties.push(primitives::read_string_pair(&mut buf)?);
}
_ => {
return Err(DecodeError::InvalidProperty {
packet_type,
id: id_byte,
});
}
}
}
Ok(props)
}
}
macro_rules! pub_ack_packet {
($name:ident, $props_name:ident, $ptype:expr, $flags:expr, $doc:expr) => {
#[doc = $doc]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct $name {
/// Packet identifier
pub pkid: u16,
pub reason_code: ReasonCode,
pub properties: $props_name,
}
impl $name {
pub(super) fn flags(&self) -> u8 {
$flags
}
pub(super) fn encoded_body_len(&self) -> usize {
let props_body_len = self.properties.encoded_len();
if self.reason_code as u8 == 0x00 && props_body_len == 0 {
return 2;
}
2 + 1 + properties_encoded_len(props_body_len)
}
pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
primitives::write_u16(self.pkid, buf);
let props_body_len = self.properties.encoded_len();
if self.reason_code as u8 == 0x00 && props_body_len == 0 {
return Ok(());
}
primitives::write_u8(self.reason_code as u8, buf);
self.properties.encode(buf)?;
Ok(())
}
pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
if header_flags != $flags {
return Err(DecodeError::InvalidFlags {
packet_type: $ptype,
flags: header_flags,
});
}
let pkid = primitives::read_u16(&mut buf)?;
if !buf.has_remaining() {
return Ok(Self {
pkid,
reason_code: ReasonCode::Success,
properties: $props_name::default(),
});
}
let reason_byte = primitives::read_u8(&mut buf)?;
let reason_code = ReasonCode::try_from(reason_byte)?;
let properties = if buf.has_remaining() {
let props_buf = property::read_properties_bytes(&mut buf)?;
$props_name::decode(props_buf, $ptype)?
} else {
$props_name::default()
};
if !buf.is_empty() {
return Err(DecodeError::TrailingBytes { count: buf.len() });
}
Ok(Self {
pkid,
reason_code,
properties,
})
}
}
};
}
pub type PubRecProperties = PubAckProperties;
pub type PubRelProperties = PubAckProperties;
pub type PubCompProperties = PubAckProperties;
pub_ack_packet!(
PubAck,
PubAckProperties,
PacketType::PubAck,
0b0000,
"PUBACK packet [MQTTv5-3.4]"
);
pub_ack_packet!(
PubRec,
PubRecProperties,
PacketType::PubRec,
0b0000,
"PUBREC packet [MQTTv5-3.5]"
);
pub_ack_packet!(
PubRel,
PubRelProperties,
PacketType::PubRel,
0b0010,
"PUBREL packet [MQTTv5-3.6]"
);
pub_ack_packet!(
PubComp,
PubCompProperties,
PacketType::PubComp,
0b0000,
"PUBCOMP packet [MQTTv5-3.7]"
);
#[cfg(test)]
mod tests {
use bytes::{Bytes, BytesMut};
use super::*;
use crate::v5::Packet;
use crate::{DecodeError, EncodeError, PacketType, QoS};
fn roundtrip(packet: Packet) -> Packet {
let mut buf = BytesMut::new();
packet.encode(&mut buf).unwrap();
Packet::decode(&mut buf).unwrap().unwrap()
}
#[test]
fn publish_qos0_minimal() {
let pkt = Packet::Publish(Publish {
dup: false,
qos: QoS::AtMostOnce,
retain: false,
topic: "t".to_owned(),
pkid: None,
properties: PublishProperties::default(),
payload: Bytes::new(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn publish_qos1_with_properties() {
let pkt = Packet::Publish(Publish {
dup: false,
qos: QoS::AtLeastOnce,
retain: true,
topic: "sensor/temp".to_owned(),
pkid: Some(42),
properties: PublishProperties {
payload_format_indicator: Some(1),
message_expiry_interval: Some(3600),
topic_alias: Some(5),
response_topic: Some("reply".to_owned()),
correlation_data: Some(Bytes::from_static(b"\x01\x02")),
subscription_identifiers: vec![1, 2, 3],
user_properties: vec![("k".to_owned(), "v".to_owned())],
content_type: Some("application/json".to_owned()),
},
payload: Bytes::from_static(b"{\"temp\":22.5}"),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn publish_qos2_dup() {
let pkt = Packet::Publish(Publish {
dup: true,
qos: QoS::ExactlyOnce,
retain: false,
topic: "x".to_owned(),
pkid: Some(65535),
properties: PublishProperties::default(),
payload: Bytes::from_static(b"data"),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn publish_encode_qos0_with_pkid_error() {
let pkt = Packet::Publish(Publish {
dup: false,
qos: QoS::AtMostOnce,
retain: false,
topic: "t".to_owned(),
pkid: Some(1),
properties: PublishProperties::default(),
payload: Bytes::new(),
});
let mut buf = BytesMut::new();
assert_eq!(
pkt.encode(&mut buf),
Err(EncodeError::InvalidState {
reason: "QoS 0 must not carry pkid"
})
);
}
#[test]
fn publish_encode_qos1_no_pkid_error() {
let pkt = Packet::Publish(Publish {
dup: false,
qos: QoS::AtLeastOnce,
retain: false,
topic: "t".to_owned(),
pkid: None,
properties: PublishProperties::default(),
payload: Bytes::new(),
});
let mut buf = BytesMut::new();
assert_eq!(
pkt.encode(&mut buf),
Err(EncodeError::InvalidState {
reason: "QoS > 0 must carry pkid"
})
);
}
#[test]
fn publish_subscription_identifiers_repeatable() {
let pkt = Packet::Publish(Publish {
dup: false,
qos: QoS::AtMostOnce,
retain: false,
topic: "t".to_owned(),
pkid: None,
properties: PublishProperties {
subscription_identifiers: vec![10, 20, 30],
..Default::default()
},
payload: Bytes::new(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn puback_abbreviated_success() {
let pkt = Packet::PubAck(PubAck {
pkid: 1,
reason_code: ReasonCode::Success,
properties: PubAckProperties::default(),
});
let mut buf = BytesMut::new();
pkt.encode(&mut buf).unwrap();
assert_eq!(buf.len(), 4);
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn puback_with_reason_and_properties() {
let pkt = Packet::PubAck(PubAck {
pkid: 100,
reason_code: ReasonCode::NoMatchingSubscribers,
properties: PubAckProperties {
reason_string: Some("no subs".to_owned()),
user_properties: vec![("k".to_owned(), "v".to_owned())],
},
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn puback_non_success_no_properties() {
let pkt = Packet::PubAck(PubAck {
pkid: 5,
reason_code: ReasonCode::UnspecifiedError,
properties: PubAckProperties::default(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn pubrec_abbreviated() {
let pkt = Packet::PubRec(PubRec {
pkid: 200,
reason_code: ReasonCode::Success,
properties: PubRecProperties::default(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn pubrec_with_properties() {
let pkt = Packet::PubRec(PubRec {
pkid: 10,
reason_code: ReasonCode::QuotaExceeded,
properties: PubRecProperties {
reason_string: Some("quota".to_owned()),
user_properties: vec![],
},
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn pubrel_abbreviated() {
let pkt = Packet::PubRel(PubRel {
pkid: 300,
reason_code: ReasonCode::Success,
properties: PubRelProperties::default(),
});
let mut buf = BytesMut::new();
pkt.encode(&mut buf).unwrap();
assert_eq!(buf[0], 0x62);
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn pubrel_wrong_flags() {
let buf = Bytes::from_static(&[0x00, 0x01]); assert_eq!(
PubRel::decode_body(0x00, buf),
Err(DecodeError::InvalidFlags {
packet_type: PacketType::PubRel,
flags: 0x00,
})
);
}
#[test]
fn pubcomp_abbreviated() {
let pkt = Packet::PubComp(PubComp {
pkid: 400,
reason_code: ReasonCode::Success,
properties: PubCompProperties::default(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn pubcomp_with_reason() {
let pkt = Packet::PubComp(PubComp {
pkid: 50,
reason_code: ReasonCode::PacketIdentifierNotFound,
properties: PubCompProperties::default(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
}