basic error handling for epp command errors

This commit is contained in:
Ritesh Chitlangi 2021-07-22 22:01:46 +08:00
parent d991fdec26
commit fca4e4b231
10 changed files with 377 additions and 275 deletions

View File

@ -1,5 +1,4 @@
use epp_client::{epp::request::generate_client_tr_id, connection::EppClient, connection, epp::xml::EppXml};
use epp_client::epp::request::EppHello;
use epp_client::{epp::request::generate_client_tr_id, connection::client::EppClient, connection, epp::xml::EppXml};
use epp_client::epp::response::EppGreeting;
use epp_client::epp::request::domain::check::EppDomainCheck;
use epp_client::epp::response::domain::check::EppDomainCheckResponse;
@ -40,16 +39,16 @@ async fn create_contact() {
}
async fn hello(client: &mut EppClient) {
let hello = EppHello::new();
let greeting = client.hello().await.unwrap();
client.transact::<_, EppGreeting>(&hello).await.unwrap();
println!("{:?}", greeting);
}
#[tokio::main]
async fn main() {
let mut client = match connection::connect("hexonet").await {
let mut client = match EppClient::new("hexonet").await {
Ok(client) => {
let greeting = client.greeting();
let greeting = client.xml_greeting();
let greeting_object = EppGreeting::deserialize(&greeting).unwrap();
println!("{:?}", greeting_object);
client
@ -57,9 +56,9 @@ async fn main() {
Err(e) => panic!("Error: {}", e)
};
hello(&mut client).await;
// hello(&mut client).await;
// check_domains(&mut client).await;
check_domains(&mut client).await;
// check_contacts(&mut client).await;

View File

@ -1,251 +1,2 @@
use std::sync::Arc;
use std::sync::mpsc;
use std::{str, u32};
use bytes::BytesMut;
use std::convert::TryInto;
use futures::executor::block_on;
use std::{error::Error, fmt::Debug, net::ToSocketAddrs, io as stdio};
use tokio_rustls::{TlsConnector, rustls::ClientConfig, webpki::DNSNameRef, client::TlsStream};
use tokio::{net::TcpStream, io::AsyncWriteExt, io::AsyncReadExt, io::split, io::ReadHalf, io::WriteHalf};
use crate::config::{CONFIG, EppClientConnection};
use crate::error;
use crate::epp::request::{generate_client_tr_id, EppLogin, EppLogout};
use crate::epp::response::EppCommandResponse;
use crate::epp::xml::EppXml;
pub struct ConnectionStream {
reader: ReadHalf<TlsStream<TcpStream>>,
writer: WriteHalf<TlsStream<TcpStream>>,
}
pub struct EppConnection {
registry: String,
stream: ConnectionStream,
pub greeting: String,
}
pub struct EppClient {
credentials: (String, String),
connection: EppConnection,
}
impl EppConnection {
pub async fn new(
registry: String,
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)?.to_string();
Ok(EppConnection {
registry: registry,
stream: stream,
greeting: greeting
})
}
async fn write(&mut self, buf: &Vec<u8>) -> Result<(), Box<dyn Error>> {
let wrote = self.stream.writer.write(buf).await?;
println!("Wrote {} bytes", wrote);
Ok(())
}
pub async fn send_epp_request(&mut self, content: &str) -> Result<(), Box<dyn Error>> {
let len = content.len();
let buf_size = len + 4;
let mut buf: Vec<u8> = vec![0u8; buf_size];
let len = len + 4;
let len_u32: [u8; 4] = u32::to_be_bytes(len.try_into()?);
buf[..4].clone_from_slice(&len_u32);
buf[4..].clone_from_slice(&content.as_bytes());
self.write(&buf).await
}
async fn read(&mut self) -> Result<Vec<u8>, Box<dyn Error>> {
let mut buf = vec![0u8; 4096];
self.stream.reader.read(&mut buf).await?;
Ok(buf)
}
async fn read_epp_response(&mut self) -> Result<Vec<u8>, Box<dyn Error>> {
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 message_size = buf_size - 4;
println!("Message buffer size: {}", message_size);
let mut buf = BytesMut::with_capacity(4096);
let mut read_buf = vec![0u8; 4096];
let mut read_size :usize = 0;
loop {
let read = self.stream.reader.read(&mut read_buf).await?;
println!("Read: {} bytes", read);
buf.extend_from_slice(&read_buf[0..read]);
read_size = read_size + read;
println!("Total read: {} bytes", read_size);
if read == 0 {
panic!("Unexpected eof")
} else if read_size >= message_size {
break;
}
}
let data = buf.to_vec();
Ok(data)
}
pub async fn get_epp_response(&mut self) -> Result<String, Box<dyn Error>> {
let contents = self.read_epp_response().await?;
let response = str::from_utf8(&contents)?.to_string();
Ok(response)
}
pub async fn transact(&mut self, content: &str) -> Result<String, Box<dyn Error>> {
self.send_epp_request(&content).await?;
self.get_epp_response().await
}
async fn close(&mut self) -> Result<(), Box<dyn Error>> {
println!("Closing ...");
self.stream.writer.shutdown().await?;
Ok(())
}
}
impl Drop for EppConnection {
fn drop(&mut self) {
block_on(self.close());
}
}
impl EppClient {
pub async fn new(connection: EppConnection, credentials: (String, String)) -> Result<EppClient, Box<dyn Error>> {
let mut client = EppClient {
connection: connection,
credentials: credentials
};
let client_tr_id = generate_client_tr_id(&client.credentials.0)?;
let login_request = EppLogin::new(&client.credentials.0, &client.credentials.1, client_tr_id.as_str());
client.transact::<EppLogin, EppCommandResponse>(&login_request).await?;
Ok(client)
}
pub async fn transact<T: EppXml + Debug, E: EppXml + Debug>(&mut self, request: &T) -> Result<E::Output, Box<dyn Error>> {
let epp_xml = request.serialize()?;
println!("Request:\r\n{}", epp_xml);
let response = self.connection.transact(&epp_xml).await?;
println!("Response:\r\n{}", response);
// let result_object = EppCommandResponse::deserialize(&response);
let response_obj = E::deserialize(&response)?;
println!("Response:\r\n{:?}", response_obj);
Ok(response_obj)
}
pub async fn transact_xml(&mut self, xml: &str) -> Result<String, Box<dyn Error>> {
self.connection.transact(&xml).await
}
pub fn greeting(&self) -> String {
return String::from(&self.connection.greeting)
}
pub async fn logout(&mut self) {
let client_tr_id = generate_client_tr_id(&self.credentials.0).unwrap();
let epp_logout = EppLogout::new(client_tr_id.as_str());
self.transact::<EppLogout, EppCommandResponse>(&epp_logout).await;
}
}
impl Drop for EppClient {
fn drop(&mut self) {
block_on(self.logout());
}
}
async fn epp_connect(registry_creds: &EppClientConnection) -> Result<ConnectionStream, error::Error> {
let (host, port) = registry_creds.connection_details();
println!("{}: {}", host, port);
let addr = (host.as_str(), port)
.to_socket_addrs()?
.next()
.ok_or_else(|| stdio::ErrorKind::NotFound)?;
let mut config = ClientConfig::new();
config
.root_store
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
let connector = TlsConnector::from(Arc::new(config));
let stream = TcpStream::connect(&addr).await?;
let domain = DNSNameRef::try_from_ascii_str(&host)
.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: reader,
writer: writer,
})
}
pub 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())
};
let (tx, rx) = mpsc::channel();
tokio::spawn(async move {
let stream = epp_connect(&registry_creds).await.unwrap();
let credentials = registry_creds.credentials();
let connection = EppConnection::new(
registry.to_string(),
stream
).await.unwrap();
let client = EppClient::new(connection, credentials).await.unwrap();
tx.send(client).unwrap();
});
let client = rx.recv()?;
Ok(client)
}
pub mod registry;
pub mod client;

View File

@ -0,0 +1,118 @@
use futures::executor::block_on;
use std::{error::Error, fmt::Debug};
use std::sync::mpsc;
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, EppCommandResponseStatus, EppCommandResponse, EppCommandResponseError};
use crate::epp::xml::EppXml;
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())
};
let (tx, rx) = mpsc::channel();
tokio::spawn(async move {
let stream = epp_connect(&registry_creds).await.unwrap();
let credentials = registry_creds.credentials();
let connection = EppConnection::new(
registry.to_string(),
stream
).await.unwrap();
let client = EppClient::build(connection, credentials).await.unwrap();
tx.send(client).unwrap();
});
let client = rx.recv()?;
Ok(client)
}
pub struct EppClient {
credentials: (String, String),
connection: EppConnection,
}
impl EppClient {
pub async fn new(registry: &'static str) -> Result<EppClient, Box<dyn Error>> {
connect(registry).await
}
async fn build(connection: EppConnection, credentials: (String, String)) -> Result<EppClient, Box<dyn Error>> {
let mut client = EppClient {
connection: connection,
credentials: credentials
};
let client_tr_id = generate_client_tr_id(&client.credentials.0)?;
let login_request = EppLogin::new(&client.credentials.0, &client.credentials.1, client_tr_id.as_str());
client.transact::<EppLogin, EppCommandResponse>(&login_request).await?;
Ok(client)
}
pub async fn hello(&mut self) -> Result<EppGreeting, Box<dyn Error>> {
let hello = EppHello::new();
let hello_xml = hello.serialize()?;
let response = self.connection.transact(&hello_xml).await?;
Ok(EppGreeting::deserialize(&response)?)
}
pub async fn transact<T: EppXml + Debug, E: EppXml + Debug>(&mut self, request: &T) -> Result<E::Output, error::Error> {
let epp_xml = request.serialize()?;
println!("Request:\r\n{}", epp_xml);
let response = self.connection.transact(&epp_xml).await?;
println!("Response:\r\n{}", response);
let status = EppCommandResponseStatus::deserialize(&response)?;
if status.data.result.code < 2000 {
let response = E::deserialize(&response)?;
println!("Response:\r\n{:?}", response);
Ok(response)
} else {
let epp_error = EppCommandResponseError::deserialize(&response)?;
let epp_error = error::Error::EppCommandError(error::EppCommandError::new(epp_error));
Err(epp_error)
}
}
pub async fn transact_xml(&mut self, xml: &str) -> Result<String, Box<dyn Error>> {
self.connection.transact(&xml).await
}
pub fn xml_greeting(&self) -> String {
return String::from(&self.connection.greeting)
}
pub fn greeting(&self) -> Result<EppGreeting, Box<dyn Error>> {
Ok(EppGreeting::deserialize(&self.connection.greeting)?)
}
pub async fn logout(&mut self) {
let client_tr_id = generate_client_tr_id(&self.credentials.0).unwrap();
let epp_logout = EppLogout::new(client_tr_id.as_str());
self.transact::<EppLogout, EppCommandResponse>(&epp_logout).await;
}
}
impl Drop for EppClient {
fn drop(&mut self) {
block_on(self.logout());
}
}

View File

@ -0,0 +1,160 @@
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, webpki::DNSNameRef, client::TlsStream};
use tokio::{net::TcpStream, io::AsyncWriteExt, io::AsyncReadExt, io::split, io::ReadHalf, io::WriteHalf};
use crate::config::{EppClientConnection};
use crate::error;
pub struct ConnectionStream {
reader: ReadHalf<TlsStream<TcpStream>>,
writer: WriteHalf<TlsStream<TcpStream>>,
}
pub struct EppConnection {
registry: String,
stream: ConnectionStream,
pub greeting: String,
}
impl EppConnection {
pub async fn new(
registry: String,
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)?.to_string();
Ok(EppConnection {
registry: registry,
stream: stream,
greeting: greeting
})
}
async fn write(&mut self, buf: &Vec<u8>) -> Result<(), Box<dyn Error>> {
let wrote = self.stream.writer.write(buf).await?;
println!("Wrote {} bytes", wrote);
Ok(())
}
pub async fn send_epp_request(&mut self, content: &str) -> Result<(), Box<dyn Error>> {
let len = content.len();
let buf_size = len + 4;
let mut buf: Vec<u8> = vec![0u8; buf_size];
let len = len + 4;
let len_u32: [u8; 4] = u32::to_be_bytes(len.try_into()?);
buf[..4].clone_from_slice(&len_u32);
buf[4..].clone_from_slice(&content.as_bytes());
self.write(&buf).await
}
async fn read(&mut self) -> Result<Vec<u8>, Box<dyn Error>> {
let mut buf = vec![0u8; 4096];
self.stream.reader.read(&mut buf).await?;
Ok(buf)
}
async fn read_epp_response(&mut self) -> Result<Vec<u8>, Box<dyn Error>> {
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 message_size = buf_size - 4;
println!("Message buffer size: {}", message_size);
let mut buf = BytesMut::with_capacity(4096);
let mut read_buf = vec![0u8; 4096];
let mut read_size :usize = 0;
loop {
let read = self.stream.reader.read(&mut read_buf).await?;
println!("Read: {} bytes", read);
buf.extend_from_slice(&read_buf[0..read]);
read_size = read_size + read;
println!("Total read: {} bytes", read_size);
if read == 0 {
panic!("Unexpected eof")
} else if read_size >= message_size {
break;
}
}
let data = buf.to_vec();
Ok(data)
}
pub async fn get_epp_response(&mut self) -> Result<String, Box<dyn Error>> {
let contents = self.read_epp_response().await?;
let response = str::from_utf8(&contents)?.to_string();
Ok(response)
}
pub async fn transact(&mut self, content: &str) -> Result<String, Box<dyn Error>> {
self.send_epp_request(&content).await?;
self.get_epp_response().await
}
async fn close(&mut self) -> Result<(), Box<dyn Error>> {
println!("Closing ...");
self.stream.writer.shutdown().await?;
Ok(())
}
}
impl Drop for EppConnection {
fn drop(&mut self) {
block_on(self.close());
}
}
pub async fn epp_connect(registry_creds: &EppClientConnection) -> Result<ConnectionStream, error::Error> {
let (host, port) = registry_creds.connection_details();
println!("{}: {}", host, port);
let addr = (host.as_str(), port)
.to_socket_addrs()?
.next()
.ok_or_else(|| stdio::ErrorKind::NotFound)?;
let mut config = ClientConfig::new();
config
.root_store
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
let connector = TlsConnector::from(Arc::new(config));
let stream = TcpStream::connect(&addr).await?;
let domain = DNSNameRef::try_from_ascii_str(&host)
.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: reader,
writer: writer,
})
}

View File

@ -1,5 +1,6 @@
pub mod data;
use std::fmt::Display;
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
use crate::epp::xml::{EPP_XMLNS, EPP_XMLNS_XSI, EPP_XSI_SCHEMA_LOCATION};
@ -13,6 +14,12 @@ impl Default for StringValue {
}
}
impl Display for StringValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
pub trait StringValueTrait {
fn to_string_value(&self) -> StringValue;
}
@ -37,6 +44,8 @@ pub struct EppObject<T: ElementName> {
pub xsi_schema_location: String,
#[serde(alias = "greeting", alias = "response")]
pub data: T,
// #[serde(skip)]
// pub xml: Option<String>,
}
impl<T: ElementName + Serialize> Serialize for EppObject<T> {
@ -88,6 +97,7 @@ pub struct Services {
impl<T: ElementName> EppObject<T> {
pub fn build(data: T) -> EppObject<T> {
EppObject {
// xml: None,
data: data,
xmlns: EPP_XMLNS.to_string(),
xmlns_xsi: EPP_XMLNS_XSI.to_string(),

View File

@ -16,9 +16,11 @@ impl<T: Serialize + DeserializeOwned + ElementName + Debug> EppXml for EppObject
}
fn deserialize(epp_xml: &str) -> Result<Self::Output, Box<dyn Error>> {
match from_str(epp_xml) {
Ok(v) => Ok(v),
Err(e) => Err(format!("epp-client Deserialization Error: {}", e).into()),
}
let mut object: Self::Output = match from_str(epp_xml) {
Ok(v) => v,
Err(e) => return Err(format!("epp-client Deserialization Error: {}", e).into()),
};
// object.xml = Some(epp_xml.to_string());
Ok(object)
}
}

View File

@ -15,7 +15,7 @@ pub struct DomainList {
}
#[derive(Serialize, Deserialize, Debug, ElementName)]
#[element_name(name = "check")]
#[element_name(name = "checkr")]
pub struct DomainCheck {
#[serde(rename = "check")]
list: DomainList,

View File

@ -9,6 +9,9 @@ use crate::epp::object::{
};
pub type EppGreeting = EppObject<Greeting>;
pub type EppCommandResponseStatus = EppObject<CommandResponseStatus>;
type CommandResponseError = CommandResponseStatus;
pub type EppCommandResponseError = EppObject<CommandResponseError>;
pub type EppCommandResponse = EppObject<CommandResponse<String>>;
#[derive(Serialize, Debug, PartialEq)]
@ -115,17 +118,41 @@ pub struct Greeting {
dcp: Dcp,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Undef;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct ResultValue {
#[serde(rename = "xmlns:epp")]
xmlns: String,
pub undef: Undef,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct ExtValue {
value: ResultValue,
reason: StringValue,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct EppResult {
pub code: String,
pub code: u16,
#[serde(rename = "msg")]
pub message: StringValue,
#[serde(rename = "extValue")]
pub ext_value: Option<ExtValue>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct ResponseTRID {
#[serde(rename = "clTRID")]
pub client_tr_id: StringValue,
pub client_tr_id: Option<StringValue>,
#[serde(rename = "svTRID")]
pub server_tr_id: StringValue,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct ErrorResponseTRID {
#[serde(rename = "svTRID")]
pub server_tr_id: StringValue,
}
@ -140,3 +167,11 @@ pub struct CommandResponse<T> {
#[serde(rename = "trID")]
pub tr_ids: ResponseTRID,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, ElementName)]
#[element_name(name = "response")]
pub struct CommandResponseStatus {
pub result: EppResult,
#[serde(rename = "trID")]
pub tr_ids: ResponseTRID,
}

View File

@ -1,19 +1,52 @@
use crate::epp::response::EppCommandResponseError;
use std::fmt::Display;
#[derive(Debug)]
pub enum Error {
EppConnectionError(std::io::Error),
EppCommandError(EppCommandError),
Other(String),
}
#[derive(Debug)]
pub struct EppCommandError {
pub epp_error: EppCommandResponseError,
}
impl std::error::Error for Error {}
impl std::error::Error for EppCommandError {}
impl Display for EppCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"epp-client EppCommandError: {}",
self.epp_error.data.result.message
)
}
}
impl EppCommandError {
pub fn new(epp_error: EppCommandResponseError) -> EppCommandError {
EppCommandError {
epp_error: epp_error,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "epp-client Exception: {:?}", self)
}
}
impl From<std::boxed::Box<dyn std::error::Error>> for Error {
fn from(e: std::boxed::Box<dyn std::error::Error>) -> Self {
Self::Other(format!("{}", e).to_string())
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::EppConnectionError(e)
@ -31,9 +64,3 @@ impl From<String> for Error {
Self::Other(e)
}
}
// impl From<std::io::Error> for Box<EppClientError> {
// fn from(e: std::io::Error) -> Self {
// }
// }

View File

@ -6,7 +6,7 @@ pub mod error;
#[cfg(test)]
mod tests {
use super::config;
use super::connection;
use super::connection::client::EppClient;
#[test]
fn config() {
@ -23,9 +23,9 @@ mod tests {
#[test]
fn connect() {
let mut client = match aw!(connection::connect("hexonet")) {
let mut client = match aw!(EppClient::new("hexonet")) {
Ok(client) => {
println!("{}", client.greeting());
println!("{}", client.xml_greeting());
client
},
Err(e) => panic!("Error: {}", e)