use bytes::{Bytes, BytesMut};
use crate::{DecodeError, EncodeError, PacketType, QoS, primitives};
const PROTOCOL_NAME: &str = "MQTT";
const PROTOCOL_LEVEL: u8 = 4;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Will {
pub topic: String,
pub message: Bytes,
pub qos: QoS,
pub retain: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
pub clean_session: bool,
pub keep_alive: u16,
pub client_id: String,
pub will: Option<Will>,
pub username: Option<String>,
pub password: Option<Bytes>,
}
impl Connect {
const FLAGS: u8 = 0b0000;
const VARIABLE_HEADER_LEN: usize = primitives::string_encoded_len(PROTOCOL_NAME.len()) + 1 + 1 + 2;
pub(super) fn flags(&self) -> u8 {
Self::FLAGS
}
pub(super) fn encoded_body_len(&self) -> usize {
let mut len = Self::VARIABLE_HEADER_LEN;
len += primitives::string_encoded_len(self.client_id.len());
if let Some(will) = &self.will {
len += primitives::string_encoded_len(will.topic.len());
len += primitives::binary_encoded_len(will.message.len());
}
if let Some(username) = &self.username {
len += primitives::string_encoded_len(username.len());
}
if let Some(password) = &self.password {
len += primitives::binary_encoded_len(password.len());
}
len
}
pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
self.validate()?;
primitives::write_string(PROTOCOL_NAME, buf)?;
primitives::write_u8(PROTOCOL_LEVEL, buf);
primitives::write_u8(self.connect_flags(), buf);
primitives::write_u16(self.keep_alive, buf);
primitives::write_string(&self.client_id, buf)?;
if let Some(will) = &self.will {
primitives::write_string(&will.topic, buf)?;
primitives::write_binary(&will.message, buf)?;
}
if let Some(username) = &self.username {
primitives::write_string(username, buf)?;
}
if let Some(password) = &self.password {
primitives::write_binary(password, 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 != PROTOCOL_NAME {
return Err(DecodeError::ProtocolError {
reason: "protocol name must be \"MQTT\"",
});
}
let level = primitives::read_u8(&mut buf)?;
if level != PROTOCOL_LEVEL {
return Err(DecodeError::ProtocolError {
reason: "protocol level must be 4 for MQTT 3.1.1",
});
}
let flags = primitives::read_u8(&mut buf)?;
if flags & 0x01 != 0 {
return Err(DecodeError::ProtocolError {
reason: "connect flags reserved bit must be 0",
});
}
let clean_session = (flags >> 1) & 0x01 == 1;
let will_flag = (flags >> 2) & 0x01 == 1;
let will_qos_raw = (flags >> 3) & 0x03;
let will_retain = (flags >> 5) & 0x01 == 1;
let password_flag = (flags >> 6) & 0x01 == 1;
let username_flag = (flags >> 7) & 0x01 == 1;
if !will_flag {
if will_qos_raw != 0 {
return Err(DecodeError::ProtocolError {
reason: "will_qos must be 0 when will_flag is 0",
});
}
if will_retain {
return Err(DecodeError::ProtocolError {
reason: "will_retain must be 0 when will_flag is 0",
});
}
}
let will_qos = QoS::try_from(will_qos_raw)?;
if !username_flag && password_flag {
return Err(DecodeError::ProtocolError {
reason: "password_flag=1 requires username_flag=1",
});
}
let keep_alive = primitives::read_u16(&mut buf)?;
let client_id = primitives::read_string(&mut buf)?;
let will = if will_flag {
let topic = primitives::read_string(&mut buf)?;
let message = primitives::read_binary(&mut buf)?;
Some(Will {
topic,
message,
qos: will_qos,
retain: will_retain,
})
} else {
None
};
let username = if username_flag {
Some(primitives::read_string(&mut buf)?)
} else {
None
};
let password = if password_flag {
Some(primitives::read_binary(&mut buf)?)
} else {
None
};
if !buf.is_empty() {
return Err(DecodeError::TrailingBytes { count: buf.len() });
}
Ok(Connect {
clean_session,
keep_alive,
client_id,
will,
username,
password,
})
}
fn connect_flags(&self) -> u8 {
let mut flags = 0u8;
if self.clean_session {
flags |= 1 << 1;
}
if let Some(will) = &self.will {
flags |= 1 << 2;
flags |= (will.qos as u8) << 3;
if will.retain {
flags |= 1 << 5;
}
}
if self.password.is_some() {
flags |= 1 << 6;
}
if self.username.is_some() {
flags |= 1 << 7;
}
flags
}
fn validate(&self) -> Result<(), EncodeError> {
if self.username.is_none() && self.password.is_some() {
return Err(EncodeError::InvalidState {
reason: "password requires username",
});
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectReturnCode {
Accepted = 0x00,
UnacceptableProtocol = 0x01,
IdentifierRejected = 0x02,
ServerUnavailable = 0x03,
BadCredentials = 0x04,
NotAuthorized = 0x05,
}
impl TryFrom<u8> for ConnectReturnCode {
type Error = DecodeError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x00 => Ok(Self::Accepted),
0x01 => Ok(Self::UnacceptableProtocol),
0x02 => Ok(Self::IdentifierRejected),
0x03 => Ok(Self::ServerUnavailable),
0x04 => Ok(Self::BadCredentials),
0x05 => Ok(Self::NotAuthorized),
_ => Err(DecodeError::ProtocolError {
reason: "invalid connect return code",
}),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnAck {
pub session_present: bool,
pub return_code: ConnectReturnCode,
}
impl ConnAck {
const FLAGS: u8 = 0b0000;
const BODY_LEN: usize = 2;
pub(super) fn flags(&self) -> u8 {
Self::FLAGS
}
pub(super) fn encoded_body_len(&self) -> usize {
Self::BODY_LEN
}
pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
primitives::write_u8(u8::from(self.session_present), buf);
primitives::write_u8(self.return_code as u8, 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: "CONNACK acknowledge flags bits 7-1 must be 0",
});
}
let return_code = ConnectReturnCode::try_from(primitives::read_u8(&mut buf)?)?;
if !buf.is_empty() {
return Err(DecodeError::TrailingBytes { count: buf.len() });
}
Ok(ConnAck {
session_present: ack_flags & 0x01 == 1,
return_code,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Disconnect;
impl Disconnect {
const FLAGS: u8 = 0b0000;
pub(super) fn flags(&self) -> u8 {
Self::FLAGS
}
pub(super) fn encoded_body_len(&self) -> usize {
0
}
pub(super) fn encode_body(&self, _buf: &mut BytesMut) -> Result<(), EncodeError> {
Ok(())
}
pub(super) fn decode_body(header_flags: u8, buf: Bytes) -> Result<Self, DecodeError> {
if header_flags != Self::FLAGS {
return Err(DecodeError::InvalidFlags {
packet_type: PacketType::Disconnect,
flags: header_flags,
});
}
if !buf.is_empty() {
return Err(DecodeError::TrailingBytes { count: buf.len() });
}
Ok(Self)
}
}
#[cfg(test)]
mod tests {
use bytes::{Bytes, BytesMut};
use super::*;
use crate::v3::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 connect_minimal() {
let pkt = Packet::Connect(Connect {
clean_session: true,
keep_alive: 0,
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_session: false,
keep_alive: 60,
client_id: "my-client".to_owned(),
will: Some(Will {
topic: "will/topic".to_owned(),
message: Bytes::from_static(b"bye"),
qos: QoS::ExactlyOnce,
retain: true,
}),
username: Some("user".to_owned()),
password: Some(Bytes::from_static(b"pass")),
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connect_will_qos0_no_retain() {
let pkt = Packet::Connect(Connect {
clean_session: true,
keep_alive: 30,
client_id: "c".to_owned(),
will: Some(Will {
topic: "t".to_owned(),
message: Bytes::from_static(b"m"),
qos: QoS::AtMostOnce,
retain: false,
}),
username: None,
password: None,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connect_username_only() {
let pkt = Packet::Connect(Connect {
clean_session: true,
keep_alive: 10,
client_id: "c".to_owned(),
will: None,
username: Some("admin".to_owned()),
password: None,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connect_encode_password_without_username() {
let pkt = Packet::Connect(Connect {
clean_session: true,
keep_alive: 10,
client_id: "c".to_owned(),
will: None,
username: None,
password: Some(Bytes::from_static(b"secret")),
});
let mut buf = BytesMut::new();
assert_eq!(
pkt.encode(&mut buf),
Err(EncodeError::InvalidState {
reason: "password requires username"
})
);
}
#[test]
fn connect_decode_wrong_protocol_name() {
let buf = build_connect_bytes(|b| {
primitives::write_string("MQIsdp", b).unwrap();
primitives::write_u8(PROTOCOL_LEVEL, b);
primitives::write_u8(0x02, b); primitives::write_u16(60, b);
primitives::write_string("c", b).unwrap();
});
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "protocol name must be \"MQTT\""
})
);
}
#[test]
fn connect_decode_wrong_protocol_level() {
let buf = build_connect_bytes(|b| {
primitives::write_string("MQTT", b).unwrap();
primitives::write_u8(5, b); primitives::write_u8(0x02, b);
primitives::write_u16(60, b);
primitives::write_string("c", b).unwrap();
});
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "protocol level must be 4 for MQTT 3.1.1"
})
);
}
#[test]
fn connect_decode_reserved_bit_set() {
let buf = build_connect_bytes(|b| {
primitives::write_string("MQTT", b).unwrap();
primitives::write_u8(PROTOCOL_LEVEL, b);
primitives::write_u8(0x03, b); primitives::write_u16(60, b);
primitives::write_string("c", b).unwrap();
});
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "connect flags reserved bit must be 0"
})
);
}
#[test]
fn connect_decode_will_qos_nonzero_without_will_flag() {
let buf = build_connect_bytes(|b| {
primitives::write_string("MQTT", b).unwrap();
primitives::write_u8(PROTOCOL_LEVEL, b);
primitives::write_u8(0x0A, b); primitives::write_u16(60, b);
primitives::write_string("c", b).unwrap();
});
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "will_qos must be 0 when will_flag is 0"
})
);
}
#[test]
fn connect_decode_will_retain_without_will_flag() {
let buf = build_connect_bytes(|b| {
primitives::write_string("MQTT", b).unwrap();
primitives::write_u8(PROTOCOL_LEVEL, b);
primitives::write_u8(0x22, b); primitives::write_u16(60, b);
primitives::write_string("c", b).unwrap();
});
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "will_retain must be 0 when will_flag is 0"
})
);
}
#[test]
fn connect_decode_password_without_username() {
let buf = build_connect_bytes(|b| {
primitives::write_string("MQTT", b).unwrap();
primitives::write_u8(PROTOCOL_LEVEL, b);
primitives::write_u8(0x42, b); primitives::write_u16(60, b);
primitives::write_string("c", b).unwrap();
primitives::write_binary(b"pass", b).unwrap();
});
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "password_flag=1 requires username_flag=1"
})
);
}
#[test]
fn connect_decode_trailing_bytes() {
let buf = build_connect_bytes(|b| {
primitives::write_string("MQTT", b).unwrap();
primitives::write_u8(PROTOCOL_LEVEL, b);
primitives::write_u8(0x02, b); primitives::write_u16(60, b);
primitives::write_string("c", b).unwrap();
b.extend_from_slice(&[0xFF]); });
assert_eq!(
Connect::decode_body(0x00, buf),
Err(DecodeError::TrailingBytes { count: 1 })
);
}
#[test]
fn connect_decode_invalid_header_flags() {
let buf = Bytes::from_static(&[]);
assert_eq!(
Connect::decode_body(0x01, buf),
Err(DecodeError::InvalidFlags {
packet_type: PacketType::Connect,
flags: 0x01,
})
);
}
#[test]
fn connack_accepted_no_session() {
let pkt = Packet::ConnAck(ConnAck {
session_present: false,
return_code: ConnectReturnCode::Accepted,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connack_accepted_session_present() {
let pkt = Packet::ConnAck(ConnAck {
session_present: true,
return_code: ConnectReturnCode::Accepted,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn connack_all_return_codes() {
let codes = [
ConnectReturnCode::Accepted,
ConnectReturnCode::UnacceptableProtocol,
ConnectReturnCode::IdentifierRejected,
ConnectReturnCode::ServerUnavailable,
ConnectReturnCode::BadCredentials,
ConnectReturnCode::NotAuthorized,
];
for code in codes {
let pkt = Packet::ConnAck(ConnAck {
session_present: false,
return_code: code,
});
assert_eq!(roundtrip(pkt.clone()), pkt);
}
}
#[test]
fn connack_invalid_return_code() {
let buf = Bytes::from_static(&[0x00, 0x06]); assert_eq!(
ConnAck::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "invalid connect return code"
})
);
}
#[test]
fn connack_invalid_flags() {
let buf = Bytes::from_static(&[0x00, 0x00]);
assert_eq!(
ConnAck::decode_body(0x01, buf),
Err(DecodeError::InvalidFlags {
packet_type: PacketType::ConnAck,
flags: 0x01,
})
);
}
#[test]
fn connack_trailing_bytes() {
let buf = Bytes::from_static(&[0x00, 0x00, 0xFF]); assert_eq!(
ConnAck::decode_body(0x00, buf),
Err(DecodeError::TrailingBytes { count: 1 })
);
}
#[test]
fn connack_ack_flags_high_bits_set() {
let buf = Bytes::from_static(&[0x02, 0x00]); assert_eq!(
ConnAck::decode_body(0x00, buf),
Err(DecodeError::ProtocolError {
reason: "CONNACK acknowledge flags bits 7-1 must be 0"
})
);
}
#[test]
fn disconnect_roundtrip() {
let pkt = Packet::Disconnect(Disconnect);
assert_eq!(roundtrip(pkt.clone()), pkt);
}
#[test]
fn disconnect_encode_bytes() {
let mut buf = BytesMut::new();
Packet::Disconnect(Disconnect).encode(&mut buf).unwrap();
assert_eq!(&buf[..], &[0xE0, 0x00]);
}
#[test]
fn disconnect_invalid_flags() {
assert_eq!(
Disconnect::decode_body(0x01, Bytes::new()),
Err(DecodeError::InvalidFlags {
packet_type: PacketType::Disconnect,
flags: 0x01,
})
);
}
#[test]
fn disconnect_trailing_bytes() {
let buf = Bytes::from_static(&[0xFF]);
assert_eq!(
Disconnect::decode_body(0x00, buf),
Err(DecodeError::TrailingBytes { count: 1 })
);
}
fn build_connect_bytes(f: impl FnOnce(&mut BytesMut)) -> Bytes {
let mut buf = BytesMut::new();
f(&mut buf);
buf.freeze()
}
}