1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
//! A pure rust MQTT client which strives to be robust, efficient and easy to use. //! This library is backed by an async (tokio) eventloop which handles all the //! robustness and and efficiency parts of MQTT but naturally fits into both sync //! and async worlds as we'll see //! //! Let's jump into examples right away //! //! A simple synchronous publish and subscribe //! ---------------------------- //! //! ```no_run //! use rumqttc::{MqttOptions, Client, QoS}; //! use std::time::Duration; //! use std::thread; //! //! let mut mqttoptions = MqttOptions::new("rumqtt-sync", "test.mosquitto.org", 1883); //! mqttoptions.set_keep_alive(5); //! //! let (mut client, mut connection) = Client::new(mqttoptions, 10); //! client.subscribe("hello/rumqtt", QoS::AtMostOnce).unwrap(); //! thread::spawn(move || for i in 0..10 { //! client.publish("hello/rumqtt", QoS::AtLeastOnce, false, vec![i; i as usize]).unwrap(); //! thread::sleep(Duration::from_millis(100)); //! }); //! //! // Iterate to poll the eventloop for connection progress //! for (i, notification) in connection.iter().enumerate() { //! println!("Notification = {:?}", notification); //! } //! ``` //! //! A simple asynchronous publish and subscribe //! ------------------------------ //! //! ```no_run //! use rumqttc::{MqttOptions, AsyncClient, QoS}; //! use tokio::{task, time}; //! use std::time::Duration; //! use std::error::Error; //! //! # #[tokio::main(worker_threads = 1)] //! # async fn main() { //! let mut mqttoptions = MqttOptions::new("rumqtt-async", "test.mosquitto.org", 1883); //! mqttoptions.set_keep_alive(5); //! //! let (mut client, mut eventloop) = AsyncClient::new(mqttoptions, 10); //! client.subscribe("hello/rumqtt", QoS::AtMostOnce).await.unwrap(); //! //! task::spawn(async move { //! for i in 0..10 { //! client.publish("hello/rumqtt", QoS::AtLeastOnce, false, vec![i; i as usize]).await.unwrap(); //! time::sleep(Duration::from_millis(100)).await; //! } //! }); //! //! loop { //! let notification = eventloop.poll().await.unwrap(); //! println!("Received = {:?}", notification); //! } //! # } //! ``` //! //! Quick overview of features //! - Eventloop orchestrates outgoing/incoming packets concurrently and hadles the state //! - Pings the broker when necessary and detects client side half open connections as well //! - Throttling of outgoing packets (todo) //! - Queue size based flow control on outgoing packets //! - Automatic reconnections by just continuing the `eventloop.poll()/connection.iter()` loop` //! - Natural backpressure to client APIs during bad network //! - Immediate cancellation with `client.cancel()` //! //! In short, everything necessary to maintain a robust connection //! //! Since the eventloop is externally polled (with `iter()/poll()` in a loop) //! out side the library and `Eventloop` is accessible, users can //! - Distribute incoming messages based on topics //! - Stop it when required //! - Access internal state for use cases like graceful shutdown or to modify options before reconnection //! //! ## Important notes //! //! - Looping on `connection.iter()`/`eventloop.poll()` is necessary to run the //! event loop and make progress. It yields incoming and outgoing activity //! notifications which allows customization as you see fit. //! //! - Blocking inside the `connection.iter()`/`eventloop.poll()` loop will block //! connection progress. //! //! ## FAQ //! **Connecting to a broker using raw ip doesn't work** //! //! You cannot create a TLS connection to a bare IP address with a self-signed //! certificate. This is a [limitation of rustls](https://github.com/ctz/rustls/issues/184). //! One workaround, which only works under *nix/BSD-like systems, is to add an //! entry to wherever your DNS resolver looks (e.g. `/etc/hosts`) for the bare IP //! address and use that name in your code. #![cfg_attr(docsrs, feature(doc_cfg))] #[macro_use] extern crate log; use std::fmt::{self, Debug, Formatter}; use std::sync::Arc; use std::time::Duration; mod client; mod eventloop; mod framed; mod state; mod tls; mod cond_fut; pub use async_channel::{SendError, Sender, TrySendError}; pub use client::{AsyncClient, Client, ClientError, Connection}; pub use eventloop::{ConnectionError, Event, EventLoop}; pub use mqttbytes::v4::*; pub use mqttbytes::*; pub use state::{MqttState, StateError}; pub use rustls::internal::pemfile::{certs, pkcs8_private_keys, rsa_private_keys}; pub use rustls::ClientConfig; pub type Incoming = Packet; /// Current outgoing activity on the eventloop #[derive(Debug, Eq, PartialEq, Clone)] pub enum Outgoing { /// Publish packet with packet identifier. 0 implies QoS 0 Publish(u16), /// Subscribe packet with packet identifier Subscribe(u16), /// Unsubscribe packet with packet identifier Unsubscribe(u16), /// PubAck packet PubAck(u16), /// PubRec packet PubRec(u16), /// PubRel packet PubRel(u16), /// PubComp packet PubComp(u16), /// Ping request packet PingReq, /// Ping response packet PingResp, /// Disconnect packet Disconnect, } /// Requests by the client to mqtt event loop. Request are /// handled one by one. #[derive(Clone, Debug, PartialEq)] pub enum Request { Publish(Publish), PubAck(PubAck), PubRec(PubRec), PubComp(PubComp), PubRel(PubRel), PingReq, PingResp, Subscribe(Subscribe), SubAck(SubAck), Unsubscribe(Unsubscribe), UnsubAck(UnsubAck), Disconnect, } /// Key type for TLS authentication #[derive(Clone, Debug, Eq, PartialEq)] pub enum Key { RSA(Vec<u8>), ECC(Vec<u8>), } impl From<Publish> for Request { fn from(publish: Publish) -> Request { Request::Publish(publish) } } impl From<Subscribe> for Request { fn from(subscribe: Subscribe) -> Request { Request::Subscribe(subscribe) } } impl From<Unsubscribe> for Request { fn from(unsubscribe: Unsubscribe) -> Request { Request::Unsubscribe(unsubscribe) } } #[derive(Clone)] pub enum Transport { Tcp, Tls(TlsConfiguration), #[cfg(feature = "websocket")] #[cfg_attr(docsrs, doc(cfg(feature = "websocket")))] Ws, #[cfg(feature = "websocket")] #[cfg_attr(docsrs, doc(cfg(feature = "websocket")))] Wss(TlsConfiguration), } impl Default for Transport { fn default() -> Self { Self::tcp() } } impl Transport { /// Use regular tcp as transport (default) pub fn tcp() -> Self { Self::Tcp } /// Use secure tcp with tls as transport pub fn tls( ca: Vec<u8>, client_auth: Option<(Vec<u8>, Key)>, alpn: Option<Vec<Vec<u8>>>, ) -> Self { let config = TlsConfiguration::Simple { ca, alpn, client_auth, }; Self::tls_with_config(config) } pub fn tls_with_config(tls_config: TlsConfiguration) -> Self { Self::Tls(tls_config) } /// Use websockets as transport #[cfg(feature = "websocket")] #[cfg_attr(docsrs, doc(cfg(feature = "websocket")))] pub fn ws() -> Self { Self::Ws } /// Use secure websockets with tls as transport #[cfg(feature = "websocket")] #[cfg_attr(docsrs, doc(cfg(feature = "websocket")))] pub fn wss( ca: Vec<u8>, client_auth: Option<(Vec<u8>, Key)>, alpn: Option<Vec<Vec<u8>>>, ) -> Self { let config = TlsConfiguration::Simple { ca, client_auth, alpn, }; Self::wss_with_config(config) } #[cfg(feature = "websocket")] #[cfg_attr(docsrs, doc(cfg(feature = "websocket")))] pub fn wss_with_config(tls_config: TlsConfiguration) -> Self { Self::Wss(tls_config) } } #[derive(Clone)] pub enum TlsConfiguration { Simple { /// connection method ca: Vec<u8>, /// alpn settings alpn: Option<Vec<Vec<u8>>>, /// tls client_authentication client_auth: Option<(Vec<u8>, Key)>, }, /// Injected rustls ClientConfig for TLS, to allow more customisation. Rustls(Arc<ClientConfig>), } impl From<ClientConfig> for TlsConfiguration { fn from(config: ClientConfig) -> Self { TlsConfiguration::Rustls(Arc::new(config)) } } // TODO: Should all the options be exposed as public? Drawback // would be loosing the ability to panic when the user options // are wrong (e.g empty client id) or aggressive (keep alive time) /// Options to configure the behaviour of mqtt connection #[derive(Clone)] pub struct MqttOptions { /// broker address that you want to connect to broker_addr: String, /// broker port port: u16, // What transport protocol to use transport: Transport, /// keep alive time to send pingreq to broker when the connection is idle keep_alive: Duration, /// clean (or) persistent session clean_session: bool, /// client identifier client_id: String, /// username and password credentials: Option<(String, String)>, /// maximum incoming packet size (verifies remaining length of the packet) max_incoming_packet_size: usize, /// Maximum outgoing packet size (only verifies publish payload size) // TODO Verify this with all packets. This can be packet.write but message left in // the state might be a footgun as user has to explicitly clean it. Probably state // has to be moved to network max_outgoing_packet_size: usize, /// request (publish, subscribe) channel capacity request_channel_capacity: usize, /// Max internal request batching max_request_batch: usize, /// Minimum delay time between consecutive outgoing packets /// while retransmitting pending packets pending_throttle: Duration, /// maximum number of outgoing inflight messages inflight: u16, /// Last will that will be issued on unexpected disconnect last_will: Option<LastWill>, /// Enabling will wait for incoming packets to avoid collisions collision_safety: bool, conn_timeout: u64, } impl MqttOptions { /// New mqtt options pub fn new<S: Into<String>, T: Into<String>>(id: S, host: T, port: u16) -> MqttOptions { let id = id.into(); if id.starts_with(' ') || id.is_empty() { panic!("Invalid client id") } MqttOptions { broker_addr: host.into(), port, transport: Transport::tcp(), keep_alive: Duration::from_secs(60), clean_session: true, client_id: id, credentials: None, max_incoming_packet_size: 10 * 1024, max_outgoing_packet_size: 10 * 1024, request_channel_capacity: 10, max_request_batch: 0, pending_throttle: Duration::from_micros(0), inflight: 100, last_will: None, collision_safety: false, conn_timeout: 5, } } /// Broker address pub fn broker_address(&self) -> (String, u16) { (self.broker_addr.clone(), self.port) } pub fn set_last_will(&mut self, will: LastWill) -> &mut Self { self.last_will = Some(will); self } pub fn last_will(&self) -> Option<LastWill> { self.last_will.clone() } pub fn set_transport(&mut self, transport: Transport) -> &mut Self { self.transport = transport; self } pub fn transport(&self) -> Transport { self.transport.clone() } /// Set number of seconds after which client should ping the broker /// if there is no other data exchange pub fn set_keep_alive(&mut self, secs: u16) -> &mut Self { if secs < 5 { panic!("Keep alives should be >= 5 secs"); } self.keep_alive = Duration::from_secs(u64::from(secs)); self } /// Keep alive time pub fn keep_alive(&self) -> Duration { self.keep_alive } /// Client identifier pub fn client_id(&self) -> String { self.client_id.clone() } /// Set packet size limit for outgoing an incoming packets pub fn set_max_packet_size(&mut self, incoming: usize, outgoing: usize) -> &mut Self { self.max_incoming_packet_size = incoming; self.max_outgoing_packet_size = outgoing; self } /// Maximum packet size pub fn max_packet_size(&self) -> usize { self.max_incoming_packet_size } /// `clean_session = true` removes all the state from queues & instructs the broker /// to clean all the client state when client disconnects. /// /// When set `false`, broker will hold the client state and performs pending /// operations on the client when reconnection with same `client_id` /// happens. Local queue state is also held to retransmit packets after reconnection. pub fn set_clean_session(&mut self, clean_session: bool) -> &mut Self { self.clean_session = clean_session; self } /// Clean session pub fn clean_session(&self) -> bool { self.clean_session } /// Username and password pub fn set_credentials<S: Into<String>>(&mut self, username: S, password: S) -> &mut Self { self.credentials = Some((username.into(), password.into())); self } /// Security options pub fn credentials(&self) -> Option<(String, String)> { self.credentials.clone() } /// Set request channel capacity pub fn set_request_channel_capacity(&mut self, capacity: usize) -> &mut Self { self.request_channel_capacity = capacity; self } /// Request channel capacity pub fn request_channel_capacity(&self) -> usize { self.request_channel_capacity } /// Enables throttling and sets outoing message rate to the specified 'rate' pub fn set_pending_throttle(&mut self, duration: Duration) -> &mut Self { self.pending_throttle = duration; self } /// Outgoing message rate pub fn pending_throttle(&self) -> Duration { self.pending_throttle } /// Set number of concurrent in flight messages pub fn set_inflight(&mut self, inflight: u16) -> &mut Self { if inflight == 0 { panic!("zero in flight is not allowed") } self.inflight = inflight; self } /// Number of concurrent in flight messages pub fn inflight(&self) -> u16 { self.inflight } pub fn set_collision_safety(&mut self, c: bool) -> &mut Self { self.collision_safety = c; self } pub fn collision_safety(&self) -> bool { self.collision_safety } /// set connection timeout in secs pub fn set_connection_timeout(&mut self, timeout: u64) -> &mut Self { self.conn_timeout = timeout; self } /// get timeout in secs pub fn connection_timeout(&self) -> u64 { self.conn_timeout } } // Implement Debug manually because ClientConfig doesn't implement it, so derive(Debug) doesn't // work. impl Debug for MqttOptions { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct("MqttOptions") .field("broker_addr", &self.broker_addr) .field("port", &self.port) .field("keep_alive", &self.keep_alive) .field("clean_session", &self.clean_session) .field("client_id", &self.client_id) .field("credentials", &self.credentials) .field("max_packet_size", &self.max_incoming_packet_size) .field("request_channel_capacity", &self.request_channel_capacity) .field("max_request_batch", &self.max_request_batch) .field("pending_throttle", &self.pending_throttle) .field("inflight", &self.inflight) .field("last_will", &self.last_will) .field("conn_timeout", &self.conn_timeout) .finish() } } #[cfg(test)] mod test { use super::*; #[test] #[should_panic] fn client_id_startswith_space() { let _mqtt_opts = MqttOptions::new(" client_a", "127.0.0.1", 1883).set_clean_session(true); } #[test] #[cfg(feature = "websocket")] fn no_scheme() { let mut _mqtt_opts = MqttOptions::new("client_a", "a3f8czas.iot.eu-west-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MyCreds%2F20201001%2Feu-west-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20201001T130812Z&X-Amz-Expires=7200&X-Amz-Signature=9ae09b49896f44270f2707551581953e6cac71a4ccf34c7c3415555be751b2d1&X-Amz-SignedHeaders=host", 443); _mqtt_opts.set_transport(crate::Transport::wss(Vec::from("Test CA"), None, None)); if let crate::Transport::Wss(TlsConfiguration::Simple { ca, client_auth, alpn, }) = _mqtt_opts.transport { assert_eq!(ca, Vec::from("Test CA")); assert_eq!(client_auth, None); assert_eq!(alpn, None); } else { panic!("Unexpected transport!"); } assert_eq!(_mqtt_opts.broker_addr, "a3f8czas.iot.eu-west-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MyCreds%2F20201001%2Feu-west-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20201001T130812Z&X-Amz-Expires=7200&X-Amz-Signature=9ae09b49896f44270f2707551581953e6cac71a4ccf34c7c3415555be751b2d1&X-Amz-SignedHeaders=host"); } #[test] #[should_panic] fn no_client_id() { let _mqtt_opts = MqttOptions::new("", "127.0.0.1", 1883).set_clean_session(true); } }