1use std::time::Duration;
2
3#[cfg(feature = "__rustls")]
4use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer};
5use tracing::{debug, error};
6
7use crate::common::NoExtension;
8pub use crate::connection::Connector;
9use crate::connection::EppConnection;
10use crate::error::Error;
11use crate::hello::{Greeting, Hello};
12use crate::request::{Command, CommandWrapper, Extension, Transaction};
13use crate::response::{Response, ResponseStatus};
14use crate::xml;
15
16pub struct EppClient<C: Connector> {
68 connection: EppConnection<C>,
69}
70
71#[cfg(feature = "__rustls")]
72impl EppClient<RustlsConnector> {
73 pub async fn connect(
83 registry: String,
84 server: (String, u16),
85 identity: Option<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>)>,
86 timeout: Duration,
87 ) -> Result<Self, Error> {
88 let builder =
89 RustlsConnector::builder(server).map_err(|err| Error::Other(Box::new(err)))?;
90 let builder = match identity {
91 Some((certs, key)) => builder.client_auth(certs, key),
92 None => builder,
93 };
94
95 let connector = builder.build().map_err(|err| Error::Other(Box::new(err)))?;
96 Self::new(connector, registry, timeout).await
97 }
98}
99
100impl<C: Connector> EppClient<C> {
101 pub async fn new(connector: C, registry: String, timeout: Duration) -> Result<Self, Error> {
103 Ok(Self {
104 connection: EppConnection::new(connector, registry, timeout).await?,
105 })
106 }
107
108 pub fn set_max_read_buf(&mut self, max_read_buf: usize) {
110 self.connection.max_read_buf = max_read_buf;
111 }
112
113 pub async fn hello(&mut self) -> Result<Greeting, Error> {
115 let xml = xml::serialize(Hello)?;
116
117 debug!("{}: hello: {}", self.connection.registry, &xml);
118 let response = self.connection.transact(&xml)?.await?;
119 debug!("{}: greeting: {}", self.connection.registry, &response);
120
121 xml::deserialize::<Greeting>(&response)
122 }
123
124 pub async fn transact<'c, 'e, Cmd, Ext>(
125 &mut self,
126 data: impl Into<RequestData<'c, 'e, Cmd, Ext>>,
127 id: &str,
128 ) -> Result<Response<Cmd::Response, Ext::Response>, Error>
129 where
130 Cmd: Transaction<Ext> + Command + 'c,
131 Ext: Extension + 'e,
132 {
133 let data = data.into();
134 let document = CommandWrapper::new(data.command, data.extension, id);
135 let xml = xml::serialize(&document)?;
136
137 debug!("{}: request: {}", self.connection.registry, &xml);
138 let response = self.connection.transact(&xml)?.await?;
139 debug!("{}: response: {}", self.connection.registry, &response);
140
141 let rsp = match xml::deserialize::<Response<Cmd::Response, Ext::Response>>(&response) {
142 Ok(rsp) => rsp,
143 Err(e) => {
144 error!(%response, "failed to deserialize response for transaction: {e}");
145 return Err(e);
146 }
147 };
148
149 if rsp.result.code.is_success() {
150 return Ok(rsp);
151 }
152
153 let err = crate::error::Error::Command(Box::new(ResponseStatus {
154 result: rsp.result,
155 tr_ids: rsp.tr_ids,
156 }));
157
158 Err(err)
159 }
160
161 pub async fn transact_xml(&mut self, xml: &str) -> Result<String, Error> {
164 self.connection.transact(xml)?.await
165 }
166
167 pub fn xml_greeting(&self) -> String {
169 String::from(&self.connection.greeting)
170 }
171
172 pub fn greeting(&self) -> Result<Greeting, Error> {
174 xml::deserialize::<Greeting>(&self.connection.greeting)
175 }
176
177 pub async fn reconnect(&mut self) -> Result<(), Error> {
178 self.connection.reconnect().await
179 }
180
181 pub async fn shutdown(mut self) -> Result<(), Error> {
182 self.connection.shutdown().await
183 }
184}
185
186#[derive(Debug)]
187pub struct RequestData<'c, 'e, C, E> {
188 pub(crate) command: &'c C,
189 pub(crate) extension: Option<&'e E>,
190}
191
192impl<'c, C: Command> From<&'c C> for RequestData<'c, 'static, C, NoExtension> {
193 fn from(command: &'c C) -> Self {
194 Self {
195 command,
196 extension: None,
197 }
198 }
199}
200
201impl<'c, 'e, C: Command, E: Extension> From<(&'c C, &'e E)> for RequestData<'c, 'e, C, E> {
202 fn from((command, extension): (&'c C, &'e E)) -> Self {
203 Self {
204 command,
205 extension: Some(extension),
206 }
207 }
208}
209
210impl<C, E> Clone for RequestData<'_, '_, C, E> {
212 fn clone(&self) -> Self {
213 *self
214 }
215}
216
217impl<C, E> Copy for RequestData<'_, '_, C, E> {}
219
220#[cfg(feature = "__rustls")]
221pub use rustls_connector::RustlsConnector;
222
223#[cfg(feature = "__rustls")]
224mod rustls_connector {
225 use std::io;
226 use std::sync::Arc;
227 use std::time::Duration;
228
229 use async_trait::async_trait;
230 use rustls_platform_verifier::BuilderVerifierExt;
231 use tokio::net::lookup_host;
232 use tokio::net::TcpStream;
233 use tokio_rustls::client::TlsStream;
234 use tokio_rustls::rustls::pki_types::InvalidDnsNameError;
235 use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
236 use tokio_rustls::rustls::ClientConfig;
237 use tokio_rustls::TlsConnector;
238 use tracing::info;
239
240 use crate::connection::{self, Connector};
241 use crate::error::Error;
242
243 pub struct RustlsConnector {
244 inner: TlsConnector,
245 server_name: ServerName<'static>,
246 server: (String, u16),
247 }
248
249 impl RustlsConnector {
250 pub fn builder(
252 server: (String, u16),
253 ) -> Result<RustlsConnectorBuilder, InvalidDnsNameError> {
254 Ok(RustlsConnectorBuilder {
255 server_name: ServerName::try_from(server.0.as_str())?.to_owned(),
256 server,
257 identity: None,
258 })
259 }
260 }
261
262 #[async_trait]
263 impl Connector for RustlsConnector {
264 type Connection = TlsStream<TcpStream>;
265
266 async fn connect(&self, timeout: Duration) -> Result<Self::Connection, Error> {
267 info!("connecting to server: {}:{}", self.server.0, self.server.1);
268 let addr = match lookup_host(&self.server).await?.next() {
269 Some(addr) => addr,
270 None => {
271 return Err(Error::Io(io::Error::new(
272 io::ErrorKind::InvalidInput,
273 format!("invalid host: {}", self.server.0),
274 )))
275 }
276 };
277
278 let stream = TcpStream::connect(addr).await?;
279 let future = self.inner.connect(self.server_name.clone(), stream);
280 connection::timeout(timeout, future).await
281 }
282 }
283
284 pub struct RustlsConnectorBuilder {
285 server: (String, u16),
286 server_name: ServerName<'static>,
287 identity: Option<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>)>,
288 }
289
290 impl RustlsConnectorBuilder {
291 pub fn client_auth(
295 mut self,
296 certs: Vec<CertificateDer<'static>>,
297 key: PrivateKeyDer<'static>,
298 ) -> Self {
299 self.identity = Some((certs, key));
300 self
301 }
302
303 pub fn build_with_config(self, config: Arc<ClientConfig>) -> RustlsConnector {
307 let Self {
308 server,
309 server_name,
310 identity: _identity,
311 } = self;
312
313 RustlsConnector {
314 inner: TlsConnector::from(config),
315 server_name,
316 server,
317 }
318 }
319
320 pub fn build(self) -> Result<RustlsConnector, tokio_rustls::rustls::Error> {
322 let Self {
323 server,
324 server_name,
325 identity,
326 } = self;
327
328 let builder = ClientConfig::builder().with_platform_verifier()?;
329 let config = match identity {
330 Some((certs, key)) => builder.with_client_auth_cert(certs, key)?,
331 None => builder.with_no_client_auth(),
332 };
333
334 Ok(RustlsConnector {
335 inner: TlsConnector::from(Arc::new(config)),
336 server_name,
337 server,
338 })
339 }
340 }
341}