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};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConnectProperties {
pub session_expiry_interval: Option<u32>,
pub receive_maximum: Option<u16>,
pub maximum_packet_size: Option<u32>,
pub topic_alias_maximum: Option<u16>,
pub request_response_information: Option<u8>,
pub request_problem_information: Option<u8>,
pub user_properties: Vec<(String, String)>,
pub authentication_method: Option<String>,
pub authentication_data: Option<Bytes>,
}
impl ConnectProperties {
fn encoded_len(&self) -> usize {
let mut len = 0;
if self.session_expiry_interval.is_some() {
len += PROP_ID_LEN + PropertyId::SESSION_EXPIRY_INTERVAL_LEN;
}
if self.receive_maximum.is_some() {
len += PROP_ID_LEN + PropertyId::RECEIVE_MAXIMUM_LEN;
}
if self.maximum_packet_size.is_some() {
len += PROP_ID_LEN + PropertyId::MAXIMUM_PACKET_SIZE_LEN;
}
if self.topic_alias_maximum.is_some() {
len += PROP_ID_LEN + PropertyId::TOPIC_ALIAS_MAXIMUM_LEN;
}
if self.request_response_information.is_some() {
len += PROP_ID_LEN + PropertyId::REQUEST_RESPONSE_INFORMATION_LEN;
}
if self.request_problem_information.is_some() {
len += PROP_ID_LEN + PropertyId::REQUEST_PROBLEM_INFORMATION_LEN;
}
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.authentication_method {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
if let Some(ref d) = self.authentication_data {
len += PROP_ID_LEN + primitives::binary_encoded_len(d.len());
}
len
}
fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
write_properties_len(self.encoded_len(), buf);
if let Some(v) = self.session_expiry_interval {
primitives::write_u8(PropertyId::SessionExpiryInterval as u8, buf);
primitives::write_u32(v, buf);
}
if let Some(v) = self.receive_maximum {
primitives::write_u8(PropertyId::ReceiveMaximum as u8, buf);
primitives::write_u16(v, buf);
}
if let Some(v) = self.maximum_packet_size {
primitives::write_u8(PropertyId::MaximumPacketSize as u8, buf);
primitives::write_u32(v, buf);
}
if let Some(v) = self.topic_alias_maximum {
primitives::write_u8(PropertyId::TopicAliasMaximum as u8, buf);
primitives::write_u16(v, buf);
}
if let Some(v) = self.request_response_information {
primitives::write_u8(PropertyId::RequestResponseInformation as u8, buf);
primitives::write_u8(v, buf);
}
if let Some(v) = self.request_problem_information {
primitives::write_u8(PropertyId::RequestProblemInformation as u8, buf);
primitives::write_u8(v, buf);
}
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.authentication_method {
primitives::write_u8(PropertyId::AuthenticationMethod as u8, buf);
primitives::write_string(s, buf)?;
}
if let Some(ref d) = self.authentication_data {
primitives::write_u8(PropertyId::AuthenticationData as u8, buf);
primitives::write_binary(d, 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::Connect,
id: id_byte,
})?;
match id {
PropertyId::SessionExpiryInterval => {
if props.session_expiry_interval.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.session_expiry_interval = Some(primitives::read_u32(&mut buf)?);
}
PropertyId::ReceiveMaximum => {
if props.receive_maximum.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.receive_maximum = Some(primitives::read_u16(&mut buf)?);
}
PropertyId::MaximumPacketSize => {
if props.maximum_packet_size.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.maximum_packet_size = Some(primitives::read_u32(&mut buf)?);
}
PropertyId::TopicAliasMaximum => {
if props.topic_alias_maximum.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.topic_alias_maximum = Some(primitives::read_u16(&mut buf)?);
}
PropertyId::RequestResponseInformation => {
if props.request_response_information.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.request_response_information = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::RequestProblemInformation => {
if props.request_problem_information.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.request_problem_information = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::UserProperty => {
props.user_properties.push(primitives::read_string_pair(&mut buf)?);
}
PropertyId::AuthenticationMethod => {
if props.authentication_method.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.authentication_method = Some(primitives::read_string(&mut buf)?);
}
PropertyId::AuthenticationData => {
if props.authentication_data.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.authentication_data = Some(primitives::read_binary(&mut buf)?);
}
_ => {
return Err(DecodeError::InvalidProperty {
packet_type: PacketType::Connect,
id: id_byte,
});
}
}
}
Ok(props)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WillProperties {
pub will_delay_interval: Option<u32>,
pub payload_format_indicator: Option<u8>,
pub message_expiry_interval: Option<u32>,
pub content_type: Option<String>,
pub response_topic: Option<String>,
pub correlation_data: Option<Bytes>,
pub user_properties: Vec<(String, String)>,
}
impl WillProperties {
fn encoded_len(&self) -> usize {
let mut len = 0;
if self.will_delay_interval.is_some() {
len += PROP_ID_LEN + PropertyId::WILL_DELAY_INTERVAL_LEN;
}
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 let Some(ref s) = self.content_type {
len += PROP_ID_LEN + primitives::string_encoded_len(s.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 (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(v) = self.will_delay_interval {
primitives::write_u8(PropertyId::WillDelayInterval as u8, buf);
primitives::write_u32(v, 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(ref s) = self.content_type {
primitives::write_u8(PropertyId::ContentType as u8, buf);
primitives::write_string(s, 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 (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) -> 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::Connect,
id: id_byte,
})?;
match id {
PropertyId::WillDelayInterval => {
if props.will_delay_interval.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.will_delay_interval = Some(primitives::read_u32(&mut buf)?);
}
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::ContentType => {
if props.content_type.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.content_type = Some(primitives::read_string(&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::UserProperty => {
props.user_properties.push(primitives::read_string_pair(&mut buf)?);
}
_ => {
return Err(DecodeError::InvalidProperty {
packet_type: PacketType::Connect,
id: id_byte,
});
}
}
}
Ok(props)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Will {
pub properties: WillProperties,
pub topic: String,
pub payload: Bytes,
pub qos: QoS,
pub retain: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
pub clean_start: bool,
pub keep_alive: u16,
pub properties: ConnectProperties,
pub client_id: String,
pub will: Option<Will>,
pub username: Option<String>,
pub password: Option<Bytes>,
}
impl Connect {
const FLAGS: u8 = 0b0000;
pub(super) fn flags(&self) -> u8 {
Self::FLAGS
}
pub(super) fn encoded_body_len(&self) -> usize {
let mut len = 0;
len += 6 + 1 + 1 + 2;
len += properties_encoded_len(self.properties.encoded_len());
len += 2 + self.client_id.len();
if let Some(ref will) = self.will {
len += properties_encoded_len(will.properties.encoded_len());
len += 2 + will.topic.len();
len += 2 + will.payload.len();
}
if let Some(ref u) = self.username {
len += 2 + u.len();
}
if let Some(ref p) = self.password {
len += 2 + p.len();
}
len
}
pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
primitives::write_string("MQTT", buf)?;
primitives::write_u8(0x05, buf);
let mut flags: u8 = 0;
if self.clean_start {
flags |= 0x02;
}
if let Some(ref will) = self.will {
flags |= 0x04;
flags |= (will.qos as u8) << 3;
if will.retain {
flags |= 0x20;
}
}
if self.username.is_some() {
flags |= 0x80;
}
if self.password.is_some() {
flags |= 0x40;
}
primitives::write_u8(flags, buf);
primitives::write_u16(self.keep_alive, buf);
self.properties.encode(buf)?;
primitives::write_string(&self.client_id, buf)?;
if let Some(ref will) = self.will {
will.properties.encode(buf)?;
primitives::write_string(&will.topic, buf)?;
primitives::write_binary(&will.payload, buf)?;
}
if let Some(ref u) = self.username {
primitives::write_string(u, buf)?;
}
if let Some(ref p) = self.password {
primitives::write_binary(p, buf)?;
}
Ok(())
}
pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
if header_flags != Self::FLAGS {
return Err(DecodeError::InvalidFlags {
packet_type: PacketType::Connect,
flags: header_flags,
});
}
let protocol_name = primitives::read_string(&mut buf)?;
if protocol_name != "MQTT" {
return Err(DecodeError::ProtocolError {
reason: "invalid protocol name",
});
}
let level = primitives::read_u8(&mut buf)?;
if level != 0x05 {
return Err(DecodeError::ProtocolError {
reason: "unsupported protocol level for v5",
});
}
let flags_byte = primitives::read_u8(&mut buf)?;
if flags_byte & 0x01 != 0 {
return Err(DecodeError::ProtocolError {
reason: "reserved flag bit must be 0",
});
}
let clean_start = flags_byte & 0x02 != 0;
let has_will = flags_byte & 0x04 != 0;
let will_qos = QoS::try_from((flags_byte >> 3) & 0x03)?;
let will_retain = flags_byte & 0x20 != 0;
let has_password = flags_byte & 0x40 != 0;
let has_username = flags_byte & 0x80 != 0;
let keep_alive = primitives::read_u16(&mut buf)?;
let props_buf = property::read_properties_bytes(&mut buf)?;
let properties = ConnectProperties::decode(props_buf)?;
let client_id = primitives::read_string(&mut buf)?;
let will = if has_will {
let will_props_buf = property::read_properties_bytes(&mut buf)?;
let will_properties = WillProperties::decode(will_props_buf)?;
let topic = primitives::read_string(&mut buf)?;
let payload = primitives::read_binary(&mut buf)?;
Some(Will {
properties: will_properties,
topic,
payload,
qos: will_qos,
retain: will_retain,
})
} else {
None
};
let username = if has_username {
Some(primitives::read_string(&mut buf)?)
} else {
None
};
let password = if has_password {
Some(primitives::read_binary(&mut buf)?)
} else {
None
};
if !buf.is_empty() {
return Err(DecodeError::TrailingBytes { count: buf.len() });
}
Ok(Self {
clean_start,
keep_alive,
properties,
client_id,
will,
username,
password,
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConnAckProperties {
pub session_expiry_interval: Option<u32>,
pub receive_maximum: Option<u16>,
pub maximum_qos: Option<u8>,
pub retain_available: Option<u8>,
pub maximum_packet_size: Option<u32>,
pub assigned_client_identifier: Option<String>,
pub topic_alias_maximum: Option<u16>,
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
pub wildcard_subscription_available: Option<u8>,
pub subscription_identifier_available: Option<u8>,
pub shared_subscription_available: Option<u8>,
pub server_keep_alive: Option<u16>,
pub response_information: Option<String>,
pub server_reference: Option<String>,
pub authentication_method: Option<String>,
pub authentication_data: Option<Bytes>,
}
impl ConnAckProperties {
fn encoded_len(&self) -> usize {
let mut len = 0;
if self.session_expiry_interval.is_some() {
len += PROP_ID_LEN + PropertyId::SESSION_EXPIRY_INTERVAL_LEN;
}
if self.receive_maximum.is_some() {
len += PROP_ID_LEN + PropertyId::RECEIVE_MAXIMUM_LEN;
}
if self.maximum_qos.is_some() {
len += PROP_ID_LEN + PropertyId::MAXIMUM_QOS_LEN;
}
if self.retain_available.is_some() {
len += PROP_ID_LEN + PropertyId::RETAIN_AVAILABLE_LEN;
}
if self.maximum_packet_size.is_some() {
len += PROP_ID_LEN + PropertyId::MAXIMUM_PACKET_SIZE_LEN;
}
if let Some(ref s) = self.assigned_client_identifier {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
if self.topic_alias_maximum.is_some() {
len += PROP_ID_LEN + PropertyId::TOPIC_ALIAS_MAXIMUM_LEN;
}
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());
}
if self.wildcard_subscription_available.is_some() {
len += PROP_ID_LEN + PropertyId::WILDCARD_SUBSCRIPTION_AVAILABLE_LEN;
}
if self.subscription_identifier_available.is_some() {
len += PROP_ID_LEN + PropertyId::SUBSCRIPTION_IDENTIFIER_AVAILABLE_LEN;
}
if self.shared_subscription_available.is_some() {
len += PROP_ID_LEN + PropertyId::SHARED_SUBSCRIPTION_AVAILABLE_LEN;
}
if self.server_keep_alive.is_some() {
len += PROP_ID_LEN + PropertyId::SERVER_KEEP_ALIVE_LEN;
}
if let Some(ref s) = self.response_information {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
if let Some(ref s) = self.server_reference {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
if let Some(ref s) = self.authentication_method {
len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
}
if let Some(ref d) = self.authentication_data {
len += PROP_ID_LEN + primitives::binary_encoded_len(d.len());
}
len
}
fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
write_properties_len(self.encoded_len(), buf);
if let Some(v) = self.session_expiry_interval {
primitives::write_u8(PropertyId::SessionExpiryInterval as u8, buf);
primitives::write_u32(v, buf);
}
if let Some(v) = self.receive_maximum {
primitives::write_u8(PropertyId::ReceiveMaximum as u8, buf);
primitives::write_u16(v, buf);
}
if let Some(v) = self.maximum_qos {
primitives::write_u8(PropertyId::MaximumQoS as u8, buf);
primitives::write_u8(v, buf);
}
if let Some(v) = self.retain_available {
primitives::write_u8(PropertyId::RetainAvailable as u8, buf);
primitives::write_u8(v, buf);
}
if let Some(v) = self.maximum_packet_size {
primitives::write_u8(PropertyId::MaximumPacketSize as u8, buf);
primitives::write_u32(v, buf);
}
if let Some(ref s) = self.assigned_client_identifier {
primitives::write_u8(PropertyId::AssignedClientIdentifier as u8, buf);
primitives::write_string(s, buf)?;
}
if let Some(v) = self.topic_alias_maximum {
primitives::write_u8(PropertyId::TopicAliasMaximum as u8, buf);
primitives::write_u16(v, 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)?;
}
if let Some(v) = self.wildcard_subscription_available {
primitives::write_u8(PropertyId::WildcardSubscriptionAvailable as u8, buf);
primitives::write_u8(v, buf);
}
if let Some(v) = self.subscription_identifier_available {
primitives::write_u8(PropertyId::SubscriptionIdentifierAvailable as u8, buf);
primitives::write_u8(v, buf);
}
if let Some(v) = self.shared_subscription_available {
primitives::write_u8(PropertyId::SharedSubscriptionAvailable as u8, buf);
primitives::write_u8(v, buf);
}
if let Some(v) = self.server_keep_alive {
primitives::write_u8(PropertyId::ServerKeepAlive as u8, buf);
primitives::write_u16(v, buf);
}
if let Some(ref s) = self.response_information {
primitives::write_u8(PropertyId::ResponseInformation as u8, buf);
primitives::write_string(s, buf)?;
}
if let Some(ref s) = self.server_reference {
primitives::write_u8(PropertyId::ServerReference as u8, buf);
primitives::write_string(s, buf)?;
}
if let Some(ref s) = self.authentication_method {
primitives::write_u8(PropertyId::AuthenticationMethod as u8, buf);
primitives::write_string(s, buf)?;
}
if let Some(ref d) = self.authentication_data {
primitives::write_u8(PropertyId::AuthenticationData as u8, buf);
primitives::write_binary(d, 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::ConnAck,
id: id_byte,
})?;
match id {
PropertyId::SessionExpiryInterval => {
if props.session_expiry_interval.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.session_expiry_interval = Some(primitives::read_u32(&mut buf)?);
}
PropertyId::ReceiveMaximum => {
if props.receive_maximum.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.receive_maximum = Some(primitives::read_u16(&mut buf)?);
}
PropertyId::MaximumQoS => {
if props.maximum_qos.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.maximum_qos = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::RetainAvailable => {
if props.retain_available.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.retain_available = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::MaximumPacketSize => {
if props.maximum_packet_size.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.maximum_packet_size = Some(primitives::read_u32(&mut buf)?);
}
PropertyId::AssignedClientIdentifier => {
if props.assigned_client_identifier.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.assigned_client_identifier = Some(primitives::read_string(&mut buf)?);
}
PropertyId::TopicAliasMaximum => {
if props.topic_alias_maximum.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.topic_alias_maximum = Some(primitives::read_u16(&mut buf)?);
}
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)?);
}
PropertyId::WildcardSubscriptionAvailable => {
if props.wildcard_subscription_available.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.wildcard_subscription_available = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::SubscriptionIdentifierAvailable => {
if props.subscription_identifier_available.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.subscription_identifier_available = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::SharedSubscriptionAvailable => {
if props.shared_subscription_available.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.shared_subscription_available = Some(primitives::read_u8(&mut buf)?);
}
PropertyId::ServerKeepAlive => {
if props.server_keep_alive.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.server_keep_alive = Some(primitives::read_u16(&mut buf)?);
}
PropertyId::ResponseInformation => {
if props.response_information.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.response_information = Some(primitives::read_string(&mut buf)?);
}
PropertyId::ServerReference => {
if props.server_reference.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.server_reference = Some(primitives::read_string(&mut buf)?);
}
PropertyId::AuthenticationMethod => {
if props.authentication_method.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.authentication_method = Some(primitives::read_string(&mut buf)?);
}
PropertyId::AuthenticationData => {
if props.authentication_data.is_some() {
return Err(DecodeError::DuplicateProperty { id: id_byte });
}
props.authentication_data = Some(primitives::read_binary(&mut buf)?);
}
_ => {
return Err(DecodeError::InvalidProperty {
packet_type: PacketType::ConnAck,
id: id_byte,
});
}
}
}
Ok(props)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnAck {
pub session_present: bool,
pub reason_code: ReasonCode,
pub properties: ConnAckProperties,
}
impl ConnAck {
const FLAGS: u8 = 0b0000;
pub(super) fn flags(&self) -> u8 {
Self::FLAGS
}
pub(super) fn encoded_body_len(&self) -> usize {
1 + 1 + properties_encoded_len(self.properties.encoded_len())
}
pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
primitives::write_u8(if self.session_present { 0x01 } else { 0x00 }, buf);
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 != Self::FLAGS {
return Err(DecodeError::InvalidFlags {
packet_type: PacketType::ConnAck,
flags: header_flags,
});
}
let ack_flags = primitives::read_u8(&mut buf)?;
if ack_flags & 0xFE != 0 {
return Err(DecodeError::ProtocolError {
reason: "reserved bits in CONNACK flags",
});
}
let session_present = ack_flags & 0x01 != 0;
let reason_byte = primitives::read_u8(&mut buf)?;
let reason_code = ReasonCode::try_from(reason_byte)?;
let props_buf = property::read_properties_bytes(&mut buf)?;
let properties = ConnAckProperties::decode(props_buf)?;
if !buf.is_empty() {
return Err(DecodeError::TrailingBytes { count: buf.len() });
}
Ok(Self {
session_present,
reason_code,
properties,
})
}
}
#[cfg(test)]
mod tests {
use bytes::{Bytes, BytesMut};
use super::*;
use crate::v5::Packet;
use crate::{DecodeError, 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 connect_minimal() {
let pkt = Packet::Connect(Connect {
clean_start: true,
keep_alive: 0,
properties: ConnectProperties::default(),
client_id: String::new(),
will: None,
username: None,
password: None,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connect_full() {
let pkt = Packet::Connect(Connect {
clean_start: false,
keep_alive: 120,
properties: ConnectProperties {
session_expiry_interval: Some(3600),
receive_maximum: Some(100),
maximum_packet_size: Some(1024 * 1024),
topic_alias_maximum: Some(10),
request_response_information: Some(1),
request_problem_information: Some(1),
user_properties: vec![("key".to_owned(), "val".to_owned())],
authentication_method: Some("SCRAM".to_owned()),
authentication_data: Some(Bytes::from_static(b"auth-data")),
},
client_id: "my-client-v5".to_owned(),
will: Some(Will {
properties: WillProperties {
will_delay_interval: Some(30),
payload_format_indicator: Some(1),
message_expiry_interval: Some(60),
content_type: Some("text/plain".to_owned()),
response_topic: Some("resp".to_owned()),
correlation_data: Some(Bytes::from_static(b"\x01\x02")),
user_properties: vec![("wp".to_owned(), "wv".to_owned())],
},
topic: "will/topic".to_owned(),
payload: Bytes::from_static(b"goodbye"),
qos: QoS::ExactlyOnce,
retain: true,
}),
username: Some("admin".to_owned()),
password: Some(Bytes::from_static(b"secret")),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connect_clean_start_false() {
let pkt = Packet::Connect(Connect {
clean_start: false,
keep_alive: 60,
properties: ConnectProperties::default(),
client_id: "c".to_owned(),
will: None,
username: None,
password: None,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connect_with_user_properties() {
let pkt = Packet::Connect(Connect {
clean_start: true,
keep_alive: 30,
properties: ConnectProperties {
user_properties: vec![
("k1".to_owned(), "v1".to_owned()),
("k2".to_owned(), "v2".to_owned()),
("k1".to_owned(), "v3".to_owned()), ],
..Default::default()
},
client_id: "c".to_owned(),
will: None,
username: None,
password: None,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connect_decode_wrong_protocol_level() {
let mut raw = BytesMut::new();
primitives::write_string("MQTT", &mut raw).unwrap();
primitives::write_u8(0x04, &mut raw); primitives::write_u8(0x02, &mut raw); primitives::write_u16(60, &mut raw);
raw.extend_from_slice(&[0x00]);
primitives::write_string("c", &mut raw).unwrap();
let buf = raw.freeze();
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "unsupported protocol level for v5"
})
);
}
#[test]
fn connect_decode_duplicate_property() {
let mut raw = BytesMut::new();
primitives::write_string("MQTT", &mut raw).unwrap();
primitives::write_u8(0x05, &mut raw);
primitives::write_u8(0x02, &mut raw); primitives::write_u16(60, &mut raw);
let mut props_buf = BytesMut::new();
primitives::write_u8(0x11, &mut props_buf);
primitives::write_u32(100, &mut props_buf);
primitives::write_u8(0x11, &mut props_buf);
primitives::write_u32(200, &mut props_buf);
let props_len = props_buf.len() as u32;
let mut varint_dst = [0u8; 4];
let vlen = crate::varint::encode_to(props_len, &mut varint_dst);
raw.extend_from_slice(&varint_dst[..vlen]);
raw.extend_from_slice(&props_buf);
primitives::write_string("c", &mut raw).unwrap();
let buf = raw.freeze();
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::DuplicateProperty { id: 0x11 })
);
}
#[test]
fn connack_minimal() {
let pkt = Packet::ConnAck(ConnAck {
session_present: false,
reason_code: ReasonCode::Success,
properties: ConnAckProperties::default(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connack_session_present() {
let pkt = Packet::ConnAck(ConnAck {
session_present: true,
reason_code: ReasonCode::Success,
properties: ConnAckProperties::default(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connack_with_all_properties() {
let pkt = Packet::ConnAck(ConnAck {
session_present: false,
reason_code: ReasonCode::Success,
properties: ConnAckProperties {
session_expiry_interval: Some(7200),
receive_maximum: Some(50),
maximum_qos: Some(1),
retain_available: Some(1),
maximum_packet_size: Some(1_048_576),
assigned_client_identifier: Some("assigned-id".to_owned()),
topic_alias_maximum: Some(20),
reason_string: Some("all good".to_owned()),
user_properties: vec![("x".to_owned(), "y".to_owned())],
wildcard_subscription_available: Some(1),
subscription_identifier_available: Some(1),
shared_subscription_available: Some(1),
server_keep_alive: Some(300),
response_information: Some("resp-info".to_owned()),
server_reference: Some("other-server".to_owned()),
authentication_method: Some("PLAIN".to_owned()),
authentication_data: Some(Bytes::from_static(b"data")),
},
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connack_error_reason_code() {
let pkt = Packet::ConnAck(ConnAck {
session_present: false,
reason_code: ReasonCode::NotAuthorized,
properties: ConnAckProperties::default(),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connack_invalid_flags() {
let buf = Bytes::from_static(&[0x00, 0x00, 0x00]); assert_eq!(
ConnAck::decode_body(0x01, buf),
Err(DecodeError::InvalidFlags {
packet_type: PacketType::ConnAck,
flags: 0x01,
})
);
}
#[test]
fn connack_reserved_bits_in_ack_flags() {
let buf = Bytes::from_static(&[0x02, 0x00, 0x00]); assert_eq!(
ConnAck::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "reserved bits in CONNACK flags"
})
);
}
}