mod codec;
mod conn;
pub use codec::{CodecError, ConnAck, MAX_PACKET, QoS};
pub use conn::{Connection, ConnectionConfig, Incoming};
use crate::std_shim::{String, ToString, format};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum MqttError {
#[error("invalid broker URL: {0}")]
Url(String),
#[error("the broker refused the connection: {1} (code {0})")]
Refused(u8, &'static str),
#[error("the broker connection dropped: {0}")]
Disconnected(String),
#[error("the broker spoke badly: {0}")]
Protocol(#[from] CodecError),
#[error("the broker did not answer within {0:?}")]
Timeout(core::time::Duration),
}
impl MqttError {
pub fn is_retriable(&self) -> bool {
!matches!(self, MqttError::Url(_))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrokerAddress {
host: String,
port: u16,
tls: bool,
}
impl core::fmt::Display for BrokerAddress {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let scheme = if self.tls { "mqtts" } else { "mqtt" };
write!(f, "{scheme}://{}:{}", self.host, self.port)
}
}
impl BrokerAddress {
pub fn parse(url: &str) -> Result<Self, MqttError> {
let parsed = url::Url::parse(url).map_err(|e| MqttError::Url(e.to_string()))?;
let host = parsed
.host_str()
.ok_or_else(|| MqttError::Url("broker URL has no host".to_string()))?
.to_string();
let (default_port, tls) = match parsed.scheme() {
"mqtt" | "tcp" => (1883, false),
"mqtts" | "ssl" => (8883, true),
other => {
return Err(MqttError::Url(format!(
"unsupported broker scheme {other:?}; use mqtt:// or mqtts://"
)));
}
};
Ok(Self {
host,
port: parsed.port().unwrap_or(default_port),
tls,
})
}
pub fn host(&self) -> &str {
&self.host
}
pub fn port(&self) -> u16 {
self.port
}
pub fn is_tls(&self) -> bool {
self.tls
}
pub(crate) async fn connect(&self) -> Result<conn::Stream, MqttError> {
let tcp = tokio::net::TcpStream::connect((self.host.as_str(), self.port))
.await
.map_err(|e| MqttError::Disconnected(format!("{self}: {e}")))?;
let _ = tcp.set_nodelay(true);
if !self.tls {
return Ok(Box::new(tcp));
}
crate::crypto::install_crypto_provider();
let roots = rustls::RootCertStore {
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
};
let config = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
let server_name =
rustls::pki_types::ServerName::try_from(self.host.clone()).map_err(|e| {
MqttError::Url(format!("{} is not a valid TLS server name: {e}", self.host))
})?;
let stream = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config))
.connect(server_name, tcp)
.await
.map_err(|e| MqttError::Disconnected(format!("TLS handshake with {self}: {e}")))?;
Ok(Box::new(stream))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schemes_carry_their_default_ports() {
let plain = BrokerAddress::parse("mqtt://broker.example.com").unwrap();
assert_eq!(
(plain.host(), plain.port(), plain.is_tls()),
("broker.example.com", 1883, false)
);
let tls = BrokerAddress::parse("mqtts://broker.example.com").unwrap();
assert_eq!(
(tls.host(), tls.port(), tls.is_tls()),
("broker.example.com", 8883, true)
);
}
#[test]
fn an_explicit_port_wins_over_the_scheme_default() {
let a = BrokerAddress::parse("mqtts://broker.example.com:1884").unwrap();
assert_eq!(a.port(), 1884);
assert!(a.is_tls());
}
#[test]
fn tcp_and_ssl_are_the_same_two_transports_under_other_names() {
assert!(!BrokerAddress::parse("tcp://h").unwrap().is_tls());
assert!(BrokerAddress::parse("ssl://h").unwrap().is_tls());
}
#[test]
fn an_unknown_scheme_is_refused_by_name_rather_than_defaulted() {
for url in ["ws://h", "wss://h", "http://h", "mqt://h"] {
let err = BrokerAddress::parse(url).unwrap_err();
assert!(matches!(err, MqttError::Url(_)), "{url}");
assert!(err.to_string().contains("use mqtt:// or mqtts://"), "{url}");
}
}
#[test]
fn a_url_with_no_host_is_refused() {
assert!(BrokerAddress::parse("mqtt://").is_err());
}
#[test]
fn an_ipv6_literal_keeps_its_brackets_off_the_host() {
let a = BrokerAddress::parse("mqtt://[::1]:1883").unwrap();
assert_eq!(a.port(), 1883);
assert!(a.host().contains("::1"));
}
#[test]
fn a_url_that_does_not_parse_is_not_retried_and_everything_else_is() {
assert!(!MqttError::Url("x".into()).is_retriable());
assert!(MqttError::Disconnected("x".into()).is_retriable());
assert!(MqttError::Refused(5, "not authorized").is_retriable());
}
}