Skip to main content

instant_epp/domain/
mod.rs

1//! Mapping for EPP domain objects
2//!
3//! As described in [RFC 5731](https://tools.ietf.org/html/rfc5731).
4
5use std::borrow::Cow;
6use std::fmt;
7use std::net::IpAddr;
8use std::str::FromStr;
9
10use instant_xml::ser::Context;
11use instant_xml::OptionAccumulator;
12use instant_xml::{Accumulate, Deserializer, FromXml, Serializer, ToXml};
13
14use crate::Error;
15
16pub mod check;
17pub use check::DomainCheck;
18
19pub mod create;
20pub use create::DomainCreate;
21
22pub mod delete;
23pub use delete::DomainDelete;
24
25pub mod info;
26pub use info::{DomainInfo, InfoData};
27
28pub mod renew;
29pub use renew::DomainRenew;
30
31pub mod transfer;
32pub use transfer::DomainTransfer;
33
34pub mod update;
35pub use update::DomainUpdate;
36
37pub const XMLNS: &str = "urn:ietf:params:xml:ns:domain-1.0";
38
39/// The `<hostAttr>` type for domain transactions
40#[derive(Clone, Debug, Eq, FromXml, PartialEq, ToXml)]
41#[xml(rename = "hostAttr", ns(XMLNS))]
42pub struct HostAttr<'a> {
43    /// The `<hostName>` tag
44    #[xml(rename = "hostName")]
45    pub name: Cow<'a, str>,
46    /// The `<hostAddr>` tags
47    #[xml(
48        rename = "hostAddr",
49        serialize_with = "serialize_host_addrs_option",
50        deserialize_with = "deserialize_host_addrs_option"
51    )]
52    pub addresses: Option<Vec<IpAddr>>,
53}
54
55fn deserialize_host_addrs_option<'xml>(
56    into: &mut OptionAccumulator<Vec<IpAddr>, Vec<IpAddr>>,
57    field: &'static str,
58    deserializer: &mut Deserializer<'_, 'xml>,
59) -> Result<(), instant_xml::Error> {
60    let mut value = <Option<Vec<HostAddr<'static>>> as FromXml<'xml>>::Accumulator::default();
61    <Option<Vec<HostAddr<'static>>>>::deserialize(&mut value, field, deserializer)?;
62    let new = match value.try_done(field)? {
63        Some(new) => new,
64        None => return Ok(()),
65    };
66
67    let into = into.get_mut();
68    for addr in new {
69        match IpAddr::from_str(&addr.address) {
70            Ok(ip) => into.push(ip),
71            Err(_) => {
72                return Err(instant_xml::Error::UnexpectedValue(format!(
73                    "invalid IP address '{}'",
74                    addr.address
75                )))
76            }
77        }
78    }
79
80    Ok(())
81}
82
83/// The `<hostAddr>` types domain or host transactions
84#[derive(Debug, FromXml, ToXml)]
85#[xml(rename = "hostAddr", ns(super::domain::XMLNS))]
86struct HostAddr<'a> {
87    #[xml(attribute, rename = "ip")]
88    ip_version: Option<Cow<'a, str>>,
89    #[xml(direct)]
90    address: Cow<'a, str>,
91}
92
93impl From<&IpAddr> for HostAddr<'static> {
94    fn from(addr: &IpAddr) -> Self {
95        Self {
96            ip_version: Some(match addr {
97                IpAddr::V4(_) => "v4".into(),
98                IpAddr::V6(_) => "v6".into(),
99            }),
100            address: addr.to_string().into(),
101        }
102    }
103}
104
105pub(crate) fn serialize_host_addrs_option<T: AsRef<[IpAddr]>, W: fmt::Write + ?Sized>(
106    addrs: &Option<T>,
107    serializer: &mut Serializer<'_, W>,
108) -> Result<(), instant_xml::Error> {
109    let addrs = match addrs {
110        Some(addrs) => addrs.as_ref(),
111        None => return Ok(()),
112    };
113
114    for addr in addrs {
115        HostAddr::from(addr).serialize(None, serializer)?;
116    }
117
118    Ok(())
119}
120
121#[derive(Clone, Debug, Eq, FromXml, PartialEq, ToXml)]
122#[xml(rename = "hostObj", ns(XMLNS))]
123pub struct HostObj<'a> {
124    #[xml(direct)]
125    pub name: Cow<'a, str>,
126}
127
128#[derive(Clone, Debug, Eq, FromXml, PartialEq, ToXml)]
129#[xml(forward)]
130pub enum HostInfo<'a> {
131    Attr(HostAttr<'a>),
132    Obj(HostObj<'a>),
133}
134
135#[derive(Debug, FromXml, ToXml)]
136#[xml(rename = "ns", ns(XMLNS))]
137pub struct NameServers<'a> {
138    pub ns: Cow<'a, [HostInfo<'a>]>,
139}
140
141/// The `<contact>` type on domain creation and update requests
142#[derive(Debug, FromXml, ToXml)]
143#[xml(rename = "contact", ns(XMLNS))]
144pub struct DomainContact<'a> {
145    /// The contact type attr (usually admin, billing, or tech in most registries)
146    #[xml(attribute, rename = "type")]
147    pub contact_type: Cow<'a, str>,
148    /// The contact id
149    #[xml(direct)]
150    pub id: Cow<'a, str>,
151}
152
153/// The `<period>` type for registration, renewal or transfer on domain transactions
154#[derive(Clone, Copy, Debug)]
155pub enum Period {
156    Years(PeriodLength),
157    Months(PeriodLength),
158}
159
160#[derive(Clone, Copy, Debug)]
161pub struct PeriodLength(u8);
162
163impl PeriodLength {
164    pub fn new(length: u8) -> Result<Self, Error> {
165        match length {
166            1..=99 => Ok(Self(length)),
167            0 | 100.. => Err(Error::Other(
168                "period length must be greater than 0 and less than 100".into(),
169            )),
170        }
171    }
172}
173
174impl ToXml for Period {
175    fn serialize<W: fmt::Write + ?Sized>(
176        &self,
177        _: Option<instant_xml::Id<'_>>,
178        serializer: &mut Serializer<W>,
179    ) -> Result<(), instant_xml::Error> {
180        let (unit, length) = match self {
181            Self::Years(length) => ('y', length.0),
182            Self::Months(length) => ('m', length.0),
183        };
184
185        let period = serializer.write_start("period", XMLNS, None::<Context<0>>)?;
186        serializer.write_attr("unit", XMLNS, &unit)?;
187        serializer.end_start()?;
188        serializer.write_str(&length)?;
189        serializer.write_close(period)
190    }
191}
192
193pub const ONE_YEAR: Period = Period::Years(PeriodLength(1));
194
195pub const TWO_YEARS: Period = Period::Years(PeriodLength(2));
196
197pub const THREE_YEARS: Period = Period::Years(PeriodLength(3));
198
199pub const ONE_MONTH: Period = Period::Months(PeriodLength(1));
200
201pub const SIX_MONTHS: Period = Period::Months(PeriodLength(6));
202
203/// The `<authInfo>` tag for domain and contact transactions
204#[derive(Clone, Debug, FromXml, ToXml)]
205#[xml(rename = "authInfo", ns(XMLNS))]
206pub struct DomainAuthInfo<'a> {
207    /// The `<pw>` tag under `<authInfo>`
208    #[xml(rename = "pw")]
209    pub password: Cow<'a, str>,
210}
211
212impl<'a> DomainAuthInfo<'a> {
213    /// Creates a DomainAuthInfo instance with the given password
214    pub fn new(password: &'a str) -> Self {
215        Self {
216            password: password.into(),
217        }
218    }
219}
220
221/// The `<status>` type on contact transactions
222#[derive(Clone, Copy, Debug, Eq, PartialEq)]
223pub enum Status {
224    ClientDeleteProhibited,
225    ServerDeleteProhibited,
226    ClientHold,
227    ServerHold,
228    ClientRenewProhibited,
229    ServerRenewProhibited,
230    ClientTransferProhibited,
231    ServerTransferProhibited,
232    ClientUpdateProhibited,
233    ServerUpdateProhibited,
234    Inactive,
235    Ok,
236    PendingCreate,
237    PendingDelete,
238    PendingRenew,
239    PendingTransfer,
240    PendingUpdate,
241}
242
243impl Status {
244    pub fn as_str(&self) -> &'static str {
245        use Status::*;
246        match self {
247            ClientDeleteProhibited => "clientDeleteProhibited",
248            ServerDeleteProhibited => "serverDeleteProhibited",
249            ClientHold => "clientHold",
250            ServerHold => "serverHold",
251            ClientRenewProhibited => "clientRenewProhibited",
252            ServerRenewProhibited => "serverRenewProhibited",
253            ClientTransferProhibited => "clientTransferProhibited",
254            ServerTransferProhibited => "serverTransferProhibited",
255            ClientUpdateProhibited => "clientUpdateProhibited",
256            ServerUpdateProhibited => "serverUpdateProhibited",
257            Inactive => "inactive",
258            Ok => "ok",
259            PendingCreate => "pendingCreate",
260            PendingDelete => "pendingDelete",
261            PendingRenew => "pendingRenew",
262            PendingTransfer => "pendingTransfer",
263            PendingUpdate => "pendingUpdate",
264        }
265    }
266}
267
268impl ToXml for Status {
269    fn serialize<W: fmt::Write + ?Sized>(
270        &self,
271        _: Option<instant_xml::Id<'_>>,
272        serializer: &mut Serializer<W>,
273    ) -> Result<(), instant_xml::Error> {
274        serializer.write_start("status", XMLNS, None::<Context<0>>)?;
275        serializer.write_attr("s", XMLNS, &self.as_str())?;
276        serializer.end_empty()
277    }
278}
279
280impl<'xml> FromXml<'xml> for Status {
281    fn matches(id: instant_xml::Id<'_>, _: Option<instant_xml::Id<'_>>) -> bool {
282        id == instant_xml::Id {
283            ns: XMLNS,
284            name: "status",
285        }
286    }
287
288    fn deserialize<'cx>(
289        into: &mut Self::Accumulator,
290        field: &'static str,
291        deserializer: &mut Deserializer<'cx, 'xml>,
292    ) -> Result<(), instant_xml::Error> {
293        use instant_xml::de::Node;
294        use instant_xml::{Error, Id};
295
296        let node = match deserializer.next() {
297            Some(result) => result?,
298            None => return Err(Error::MissingValue(field)),
299        };
300
301        let attr = match node {
302            Node::Attribute(attr) => attr,
303            Node::Open(_) | Node::Text(_) => return Err(Error::MissingValue(field)),
304            node => return Err(Error::UnexpectedNode(format!("{node:?} in Status"))),
305        };
306
307        let id = deserializer.attribute_id(&attr)?;
308        let expected = Id { ns: "", name: "s" };
309        if id != expected {
310            return Err(Error::MissingValue(field));
311        }
312
313        *into = Some(match attr.value.as_ref() {
314            "clientDeleteProhibited" => Self::ClientDeleteProhibited,
315            "serverDeleteProhibited" => Self::ServerDeleteProhibited,
316            "clientHold" => Self::ClientHold,
317            "serverHold" => Self::ServerHold,
318            "clientRenewProhibited" => Self::ClientRenewProhibited,
319            "serverRenewProhibited" => Self::ServerRenewProhibited,
320            "clientTransferProhibited" => Self::ClientTransferProhibited,
321            "serverTransferProhibited" => Self::ServerTransferProhibited,
322            "clientUpdateProhibited" => Self::ClientUpdateProhibited,
323            "serverUpdateProhibited" => Self::ServerUpdateProhibited,
324            "inactive" => Self::Inactive,
325            "ok" => Self::Ok,
326            "pendingCreate" => Self::PendingCreate,
327            "pendingDelete" => Self::PendingDelete,
328            "pendingRenew" => Self::PendingRenew,
329            "pendingTransfer" => Self::PendingTransfer,
330            "pendingUpdate" => Self::PendingUpdate,
331            val => return Err(Error::UnexpectedValue(format!("invalid status {val:?}"))),
332        });
333
334        deserializer.ignore()?;
335        Ok(())
336    }
337
338    type Accumulator = Option<Self>;
339    const KIND: instant_xml::Kind = instant_xml::Kind::Element;
340}