cargo fmt

This commit is contained in:
Nicholas Rempel 2021-11-02 14:34:13 -07:00 committed by masalachai
parent 4d4da1c52a
commit 42892e12a0
6 changed files with 85 additions and 56 deletions

View File

@ -137,23 +137,27 @@ impl EppClientConnection {
}
/// Parses the client certificate chain
fn client_certificate(&self) -> Option<Vec<Certificate>> {
self.tls_files.as_ref().map(|tls| rustls_pemfile::certs(&mut io::BufReader::new(
fs::File::open(tls.cert_chain.to_string()).unwrap(),
))
.unwrap()
.iter()
.map(|v| Certificate(v.clone()))
.collect())
self.tls_files.as_ref().map(|tls| {
rustls_pemfile::certs(&mut io::BufReader::new(
fs::File::open(tls.cert_chain.to_string()).unwrap(),
))
.unwrap()
.iter()
.map(|v| Certificate(v.clone()))
.collect()
})
}
/// Parses the client RSA private key
fn key(&self) -> Option<PrivateKey> {
self.tls_files.as_ref().map(|tls| rustls::PrivateKey(
self.tls_files.as_ref().map(|tls| {
rustls::PrivateKey(
rustls_pemfile::rsa_private_keys(&mut io::BufReader::new(
fs::File::open(tls.key.to_string()).unwrap(),
))
.unwrap()[0]
.clone(),
))
)
})
}
}

View File

@ -1,5 +1,5 @@
//! Manages registry connections and reading/writing to them
//! and connects the EppClient instances to them
pub mod registry;
pub mod client;
pub mod registry;

View File

@ -28,23 +28,25 @@
//! ```
use futures::executor::block_on;
use std::{error::Error, fmt::Debug};
use std::time::SystemTime;
use std::sync::mpsc;
use std::time::SystemTime;
use std::{error::Error, fmt::Debug};
// use std::sync::Arc;
use crate::config::CONFIG;
use crate::connection::registry::{epp_connect, EppConnection};
use crate::error;
use crate::epp::request::{generate_client_tr_id, EppHello, EppLogin, EppLogout};
use crate::epp::response::{EppGreeting, EppCommandResponse, EppLoginResponse, EppLogoutResponse, EppCommandResponseError};
use crate::epp::response::{
EppCommandResponse, EppCommandResponseError, EppGreeting, EppLoginResponse, EppLogoutResponse,
};
use crate::epp::xml::EppXml;
use crate::error;
/// Connects to the registry and returns an logged-in instance of EppClient for further transactions
async fn connect(registry: &'static str) -> Result<EppClient, Box<dyn Error>> {
let registry_creds = match CONFIG.registry(registry) {
Some(creds) => creds,
None => return Err(format!("missing credentials for {}", registry).into())
None => return Err(format!("missing credentials for {}", registry).into()),
};
let (tx, rx) = mpsc::channel();
@ -54,17 +56,16 @@ async fn connect(registry: &'static str) -> Result<EppClient, Box<dyn Error>> {
let credentials = registry_creds.credentials();
let ext_uris = registry_creds.ext_uris();
let ext_uris = ext_uris.map(|uris| uris
.iter()
.map(|u| u.to_string())
.collect::<Vec<String>>());
let ext_uris =
ext_uris.map(|uris| uris.iter().map(|u| u.to_string()).collect::<Vec<String>>());
let connection = EppConnection::new(
registry.to_string(),
stream
).await.unwrap();
let connection = EppConnection::new(registry.to_string(), stream)
.await
.unwrap();
let client = EppClient::build(connection, credentials, ext_uris).await.unwrap();
let client = EppClient::build(connection, credentials, ext_uris)
.await
.unwrap();
tx.send(client).unwrap();
});
@ -89,7 +90,7 @@ pub struct EppClient {
pub fn default_client_tr_id_fn(client: &EppClient) -> String {
let timestamp = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(time) => time,
Err(e) => panic!("Error in client TRID gen function: {}", e)
Err(e) => panic!("Error in client TRID gen function: {}", e),
};
format!("{}:{}", &client.username(), timestamp.as_secs())
}
@ -112,7 +113,11 @@ impl EppClient {
}
/// Makes a login request to the registry and initializes an EppClient instance with it
async fn build(connection: EppConnection, credentials: (String, String), ext_uris: Option<Vec<String>>) -> Result<EppClient, Box<dyn Error>> {
async fn build(
connection: EppConnection,
credentials: (String, String),
ext_uris: Option<Vec<String>>,
) -> Result<EppClient, Box<dyn Error>> {
let mut client = EppClient {
connection,
credentials,
@ -121,9 +126,16 @@ impl EppClient {
};
let client_tr_id = generate_client_tr_id(&client.credentials.0)?;
let login_request = EppLogin::new(&client.credentials.0, &client.credentials.1, &client.ext_uris, client_tr_id.as_str());
let login_request = EppLogin::new(
&client.credentials.0,
&client.credentials.1,
&client.ext_uris,
client_tr_id.as_str(),
);
client.transact::<_, EppLoginResponse>(&login_request).await?;
client
.transact::<_, EppLoginResponse>(&login_request)
.await?;
Ok(client)
}
@ -140,7 +152,10 @@ impl EppClient {
/// Accepts an EPP request object to convert to a request to send to the registry. The response from the
/// registry is deserialized to response type E and returned.
pub async fn transact<T: EppXml + Debug, E: EppXml + Debug>(&mut self, request: &T) -> Result<E::Output, error::Error> {
pub async fn transact<T: EppXml + Debug, E: EppXml + Debug>(
&mut self,
request: &T,
) -> Result<E::Output, error::Error> {
let epp_xml = request.serialize()?;
let response = self.connection.transact(&epp_xml).await?;

View File

@ -1,16 +1,18 @@
//! Manages registry connections and reading/writing to them
use std::sync::Arc;
use std::{str, u32};
use bytes::BytesMut;
use std::convert::TryInto;
use futures::executor::block_on;
use std::{error::Error, net::ToSocketAddrs, io as stdio};
use tokio_rustls::{TlsConnector, rustls::ClientConfig, client::TlsStream};
use tokio::{net::TcpStream, io::AsyncWriteExt, io::AsyncReadExt, io::split, io::ReadHalf, io::WriteHalf};
use rustls::{RootCertStore, OwnedTrustAnchor};
use rustls::{OwnedTrustAnchor, RootCertStore};
use std::convert::TryInto;
use std::sync::Arc;
use std::{error::Error, io as stdio, net::ToSocketAddrs};
use std::{str, u32};
use tokio::{
io::split, io::AsyncReadExt, io::AsyncWriteExt, io::ReadHalf, io::WriteHalf, net::TcpStream,
};
use tokio_rustls::{client::TlsStream, rustls::ClientConfig, TlsConnector};
use crate::config::{EppClientConnection};
use crate::config::EppClientConnection;
use crate::error;
/// Socket stream for the connection to the registry
@ -30,7 +32,8 @@ impl EppConnection {
/// Create an EppConnection instance with the stream to the registry
pub async fn new(
registry: String,
mut stream: ConnectionStream) -> Result<EppConnection, Box<dyn Error>> {
mut stream: ConnectionStream,
) -> Result<EppConnection, Box<dyn Error>> {
let mut buf = vec![0u8; 4096];
stream.reader.read(&mut buf).await?;
let greeting = str::from_utf8(&buf[4..])?.to_string();
@ -40,7 +43,7 @@ impl EppConnection {
Ok(EppConnection {
registry,
stream,
greeting
greeting,
})
}
@ -74,7 +77,7 @@ impl EppConnection {
let mut buf = [0u8; 4];
self.stream.reader.read_exact(&mut buf).await?;
let buf_size :usize = u32::from_be_bytes(buf).try_into()?;
let buf_size: usize = u32::from_be_bytes(buf).try_into()?;
let message_size = buf_size - 4;
debug!("{}: Response buffer size: {}", self.registry, message_size);
@ -82,7 +85,7 @@ impl EppConnection {
let mut buf = BytesMut::with_capacity(4096);
let mut read_buf = vec![0u8; 4096];
let mut read_size :usize = 0;
let mut read_size: usize = 0;
loop {
let read = self.stream.reader.read(&mut read_buf).await?;
@ -142,14 +145,17 @@ impl Drop for EppConnection {
/// Establishes a TLS connection to a registry and returns a ConnectionStream instance containing the
/// socket stream to read/write to the connection
pub async fn epp_connect(registry_creds: &EppClientConnection) -> Result<ConnectionStream, error::Error> {
pub async fn epp_connect(
registry_creds: &EppClientConnection,
) -> Result<ConnectionStream, error::Error> {
let (host, port) = registry_creds.connection_details();
info!("Connecting: EPP Server: {} Port: {}", host, port);
let addr = (host.as_str(), port)
.to_socket_addrs()?
.next().ok_or(stdio::ErrorKind::NotFound)?;
.next()
.ok_or(stdio::ErrorKind::NotFound)?;
let mut roots = RootCertStore::empty();
roots.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
@ -168,22 +174,23 @@ pub async fn epp_connect(registry_creds: &EppClientConnection) -> Result<Connect
Some((cert_chain, key)) => match builder.with_single_cert(cert_chain, key) {
Ok(config) => config,
Err(e) => return Err(format!("Failed to set client TLS credentials: {}", e).into()),
}
},
None => builder.with_no_client_auth(),
};
let connector = TlsConnector::from(Arc::new(config));
let stream = TcpStream::connect(&addr).await?;
let domain = host.as_str().try_into()
.map_err(|_| stdio::Error::new(stdio::ErrorKind::InvalidInput, format!("Invalid domain: {}", host)))?;
let domain = host.as_str().try_into().map_err(|_| {
stdio::Error::new(
stdio::ErrorKind::InvalidInput,
format!("Invalid domain: {}", host),
)
})?;
let stream = connector.connect(domain, stream).await?;
let (reader, writer) = split(stream);
Ok(ConnectionStream {
reader,
writer,
})
Ok(ConnectionStream { reader, writer })
}

View File

@ -122,9 +122,11 @@ impl EppLogin {
ext_uris: &Option<Vec<String>>,
client_tr_id: &str,
) -> EppLogin {
let ext_uris = ext_uris.as_ref().map(|uris| uris.iter()
.map(|u| u.to_string_value())
.collect::<Vec<StringValue>>());
let ext_uris = ext_uris.as_ref().map(|uris| {
uris.iter()
.map(|u| u.to_string_value())
.collect::<Vec<StringValue>>()
});
let login = Login {
username: username.to_string_value(),

View File

@ -24,9 +24,10 @@ impl<T: Serialize + DeserializeOwned + ElementName + Debug> EppXml for EppObject
let object: Self::Output = match from_str(epp_xml) {
Ok(v) => v,
Err(e) => {
return Err(error::Error::EppDeserializationError(
format!("epp-client Deserialization Error: {}", e),
))
return Err(error::Error::EppDeserializationError(format!(
"epp-client Deserialization Error: {}",
e
)))
}
};
// object.xml = Some(epp_xml.to_string());