Skip to main content

instant_epp/
client.rs

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
16/// An `EppClient` provides an interface to sending EPP requests to a registry
17///
18/// Once initialized, the EppClient instance can serialize EPP requests to XML and send them
19/// to the registry and deserialize the XML responses from the registry to local types.
20///
21/// # Examples
22///
23/// ```no_run
24/// # use std::collections::HashMap;
25/// # use std::net::ToSocketAddrs;
26/// # use std::time::Duration;
27/// #
28/// use instant_epp::EppClient;
29/// use instant_epp::domain::DomainCheck;
30/// use instant_epp::common::NoExtension;
31///
32/// # #[cfg(feature = "rustls")]
33/// # #[tokio::main]
34/// # async fn main() {
35/// // Create an instance of EppClient
36/// let timeout = Duration::from_secs(5);
37/// let mut client = match EppClient::connect("registry_name".to_string(), ("example.com".to_owned(), 7000), None, timeout).await {
38///     Ok(client) => client,
39///     Err(e) => panic!("Failed to create EppClient: {}",  e)
40/// };
41///
42/// // Make a EPP Hello call to the registry
43/// let greeting = client.hello().await.unwrap();
44/// println!("{:?}", greeting);
45///
46/// // Execute an EPP Command against the registry with distinct request and response objects
47/// let domain_check = DomainCheck { domains: &["eppdev.com", "eppdev.net"] };
48/// let response = client.transact(&domain_check, "transaction-id").await.unwrap();
49/// response
50///     .res_data()
51///     .unwrap()
52///     .list
53///     .iter()
54///     .for_each(|chk| println!("Domain: {}, Available: {}", chk.inner.id, chk.inner.available));
55/// # }
56/// #
57/// # #[cfg(not(feature = "rustls"))]
58/// # fn main() {}
59/// ```
60///
61/// The output would look like this:
62///
63/// ```text
64/// Domain: eppdev.com, Available: 1
65/// Domain: eppdev.net, Available: 1
66/// ```
67pub struct EppClient<C: Connector> {
68    connection: EppConnection<C>,
69}
70
71#[cfg(feature = "__rustls")]
72impl EppClient<RustlsConnector> {
73    /// Connect to the specified `addr` and `hostname` over TLS
74    ///
75    /// The `registry` is used as a name in internal logging; `host` provides the host name
76    /// and port to connect to), `hostname` is sent as the TLS server name indication and
77    /// `identity` provides optional TLS client authentication (using) rustls as the TLS
78    /// implementation. The `timeout` limits the time spent on any underlying network operations.
79    ///
80    /// Alternatively, use `EppClient::new()` with any established `AsyncRead + AsyncWrite + Unpin`
81    /// implementation.
82    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    /// Create an `EppClient` from an already established connection
102    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    /// Set the maximum read buffer size for the underlying connection
109    pub fn set_max_read_buf(&mut self, max_read_buf: usize) {
110        self.connection.max_read_buf = max_read_buf;
111    }
112
113    /// Executes an EPP Hello call and returns the response as a `Greeting`
114    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    /// Accepts raw EPP XML and returns the raw EPP XML response to it.
162    /// Not recommended for direct use but sometimes can be useful for debugging
163    pub async fn transact_xml(&mut self, xml: &str) -> Result<String, Error> {
164        self.connection.transact(xml)?.await
165    }
166
167    /// Returns the greeting received on establishment of the connection in raw xml form
168    pub fn xml_greeting(&self) -> String {
169        String::from(&self.connection.greeting)
170    }
171
172    /// Returns the greeting received on establishment of the connection as an `Greeting`
173    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
210// Manual impl because this does not depend on whether `C` and `E` are `Clone`
211impl<C, E> Clone for RequestData<'_, '_, C, E> {
212    fn clone(&self) -> Self {
213        *self
214    }
215}
216
217// Manual impl because this does not depend on whether `C` and `E` are `Copy`
218impl<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        /// Create a builder with the given `server` (consisting of a hostname and port)
251        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        /// Enable client authentication
292        ///
293        /// Only used when `build()` is called.
294        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        /// Use the given `config` for the TLS connector
304        ///
305        /// Any client authentication set with `client_auth` will be ignored.
306        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        /// Build a new [`ClientConfig`]
321        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}