Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rumqttc: Enable native tls TlsConnector support. #870

Merged
merged 24 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rumqttc/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* use `Framed` to encode/decode MQTT packets.
* use `Login` to store credentials
* Made `DisconnectProperties` struct public.
* Accept `native_tls::TlsConnectorBuilder` as input of `Transport::tls_with_config`.

### Deprecated

Expand Down
5 changes: 5 additions & 0 deletions rumqttc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ name = "tls"
path = "examples/tls.rs"
required-features = ["use-rustls"]

[[example]]
name = "tls_native"
path = "examples/tls_native.rs"
required-features = ["use-native-tls"]

[[example]]
name = "tls2"
path = "examples/tls2.rs"
Expand Down
2 changes: 1 addition & 1 deletion rumqttc/examples/tls.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Example of how to configure rumqttd to connect to a server using TLS and authentication.
//! Example of how to configure rumqttc to connect to a server using TLS and authentication.
use std::error::Error;

use rumqttc::{AsyncClient, Event, Incoming, MqttOptions, Transport};
Expand Down
40 changes: 40 additions & 0 deletions rumqttc/examples/tls_native.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//! Example of how to configure rumqttc to connect to a server using TLS and authentication.
use std::error::Error;

use rumqttc::{AsyncClient, Event, Incoming, MqttOptions, Transport};
use tokio_native_tls::native_tls;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
color_backtrace::install();

let mut mqttoptions = MqttOptions::new("test-1", "test.mosquitto.org", 8883);
mqttoptions.set_keep_alive(std::time::Duration::from_secs(5));

// Use native-tls to load root certificates from the operating system.
let mut builder = native_tls::TlsConnector::builder();
let pem = include_bytes!("native-tls-cert.pem");
let cert = native_tls::Certificate::from_pem(pem).unwrap();
de-sh marked this conversation as resolved.
Show resolved Hide resolved
builder.add_root_certificate(cert);

mqttoptions.set_transport(Transport::tls_with_config(builder.into()));

let (_client, mut eventloop) = AsyncClient::new(mqttoptions, 10);

loop {
match eventloop.poll().await {
Ok(Event::Incoming(Incoming::Publish(p))) => {
println!("Topic: {}, Payload: {:?}", p.topic, p.payload);
}
Ok(Event::Incoming(i)) => {
println!("Incoming = {i:?}");
}
Ok(Event::Outgoing(o)) => println!("Outgoing = {o:?}"),
Err(e) => {
println!("Error = {e:?}");
return Ok(());
}
}
}
}
19 changes: 17 additions & 2 deletions rumqttc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ extern crate log;

use std::fmt::{self, Debug, Formatter};

#[cfg(any(feature = "use-rustls", feature = "websocket"))]
#[cfg(any(feature = "use-rustls",feature = "use-native-tls", feature = "websocket"))]
use std::sync::Arc;

use std::time::Duration;
Expand Down Expand Up @@ -149,6 +149,10 @@ pub use tls::Error as TlsError;
pub use tokio_rustls;
#[cfg(feature = "use-rustls")]
use tokio_rustls::rustls::{ClientConfig, RootCertStore};
#[cfg(feature = "use-native-tls")]
pub use tokio_native_tls;
#[cfg(feature = "use-native-tls")]
use tokio_native_tls::native_tls::TlsConnectorBuilder;

#[cfg(feature = "proxy")]
pub use proxy::{Proxy, ProxyAuth, ProxyType};
Expand Down Expand Up @@ -315,7 +319,7 @@ impl Transport {
}

/// TLS configuration method
#[derive(Clone, Debug)]
#[derive(Clone)]
xiaocq2001 marked this conversation as resolved.
Show resolved Hide resolved
#[cfg(any(feature = "use-rustls", feature = "use-native-tls"))]
pub enum TlsConfiguration {
#[cfg(feature = "use-rustls")]
Expand All @@ -339,7 +343,11 @@ pub enum TlsConfiguration {
/// Injected rustls ClientConfig for TLS, to allow more customisation.
Rustls(Arc<ClientConfig>),
#[cfg(feature = "use-native-tls")]
/// Use default native-tls configuration
Native,
#[cfg(feature = "use-native-tls")]
/// Injected native-tls TlsConnectorBuilder for TLS, to allow more customisation.
NativeBuilder(Arc<TlsConnectorBuilder>),
}

#[cfg(feature = "use-rustls")]
Expand All @@ -364,6 +372,13 @@ impl From<ClientConfig> for TlsConfiguration {
}
}

#[cfg(feature = "use-native-tls")]
impl From<TlsConnectorBuilder> for TlsConfiguration {
fn from(builder: TlsConnectorBuilder) -> Self {
TlsConfiguration::NativeBuilder(Arc::new(builder))
}
}

/// Provides a way to configure low level network connection configurations
#[derive(Clone, Default)]
pub struct NetworkOptions {
Expand Down
3 changes: 2 additions & 1 deletion rumqttc/src/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ pub async fn native_tls_connector(
connector_builder.build()?
}
TlsConfiguration::Native => native_tls::TlsConnector::new()?,
TlsConfiguration::NativeBuilder(builder) => builder.build()?,
#[allow(unreachable_patterns)]
_ => unreachable!("This cannot be called for other TLS backends than Native TLS"),
};
Expand All @@ -176,7 +177,7 @@ pub async fn tls_connect(
Box::new(connector.connect(domain, tcp).await?)
}
#[cfg(feature = "use-native-tls")]
TlsConfiguration::Native | TlsConfiguration::SimpleNative { .. } => {
TlsConfiguration::Native | TlsConfiguration::NativeBuilder(_) | TlsConfiguration::SimpleNative { .. } => {
let connector = native_tls_connector(tls_config).await?;
Box::new(connector.connect(addr, tcp).await?)
}
Expand Down