1use std::fmt::Debug;
4
5use chrono::{DateTime, Utc};
6use instant_xml::{Accumulate, AnyAttribute, AnyElement, FromXml, Kind};
7
8use crate::common::EPP_XMLNS;
9
10#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct ResultValue {
26 pub attributes: Vec<AnyAttribute<'static>>,
28 pub inner: AnyElement<'static>,
30}
31
32impl<'xml> FromXml<'xml> for ResultValue {
33 fn matches(id: instant_xml::Id<'_>, field: Option<instant_xml::Id<'_>>) -> bool {
34 match field {
35 Some(field) => id == field,
36 None => {
37 id == instant_xml::Id {
38 ns: EPP_XMLNS,
39 name: "value",
40 }
41 }
42 }
43 }
44
45 fn deserialize<'cx>(
46 into: &mut Self::Accumulator,
47 _field: &'static str,
48 deserializer: &mut instant_xml::Deserializer<'cx, 'xml>,
49 ) -> Result<(), instant_xml::Error> {
50 use instant_xml::de::Node;
51
52 let mut attributes = Vec::new();
53 let mut inner = None;
54 loop {
55 match deserializer.next() {
56 Some(Ok(Node::Attribute(attr))) => {
57 let id = deserializer.attribute_id(&attr)?;
61
62 attributes.push(AnyAttribute {
63 ns: id.ns.to_owned().into(),
64 name: id.name.to_owned().into(),
65 value: attr.value.into_owned().into(),
66 });
67 }
68 Some(Ok(Node::Open(element))) => {
69 let mut nested = deserializer.nested(element);
70 <AnyElement as FromXml>::deserialize(
71 &mut inner,
72 "ResultValue::inner",
73 &mut nested,
74 )?;
75 }
76 Some(Ok(Node::Close { .. })) => break,
77 Some(Ok(_)) => continue,
78 Some(Err(e)) => return Err(e),
79 None => break,
80 }
81 }
82
83 *into = Some(Self {
84 attributes,
85 inner: Accumulate::<AnyElement>::try_done(inner, "ResultValue::inner")?.into_owned(),
86 });
87 Ok(())
88 }
89
90 type Accumulator = Option<Self>;
91 const KIND: Kind = Kind::Element;
92}
93
94#[derive(Debug, Eq, FromXml, PartialEq)]
96#[xml(rename = "extValue", ns(EPP_XMLNS))]
97pub struct ExtValue {
98 pub value: ResultValue,
100 pub reason: Reason,
102}
103
104#[derive(Debug, Eq, FromXml, PartialEq)]
109#[xml(rename = "reason", ns(EPP_XMLNS))]
110pub struct Reason {
111 #[xml(attribute)]
113 pub lang: Option<String>,
114 #[xml(direct)]
116 pub text: String,
117}
118
119#[derive(Debug, Eq, FromXml, PartialEq)]
124#[xml(rename = "result", ns(EPP_XMLNS))]
125pub struct EppResult {
126 #[xml(attribute)]
128 pub code: ResultCode,
129 #[xml(rename = "msg")]
131 pub message: String,
132 #[xml(rename = "value")]
134 pub values: Vec<ResultValue>,
135 #[xml(rename = "extValue")]
137 pub ext_values: Vec<ExtValue>,
138}
139
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
142pub enum ResultCode {
143 CommandCompletedSuccessfully = 1000,
144 CommandCompletedSuccessfullyActionPending = 1001,
145 CommandCompletedSuccessfullyNoMessages = 1300,
146 CommandCompletedSuccessfullyAckToDequeue = 1301,
147 CommandCompletedSuccessfullyEndingSession = 1500,
148 UnknownCommand = 2000,
149 CommandSyntaxError = 2001,
150 CommandUseError = 2002,
151 RequiredParameterMissing = 2003,
152 ParameterValueRangeError = 2004,
153 ParameterValueSyntaxError = 2005,
154 UnimplementedProtocolVersion = 2100,
155 UnimplementedCommand = 2101,
156 UnimplementedOption = 2102,
157 UnimplementedExtension = 2103,
158 BillingFailure = 2104,
159 ObjectIsNotEligibleForRenewal = 2105,
160 ObjectIsNotEligibleForTransfer = 2106,
161 AuthenticationError = 2200,
162 AuthorizationError = 2201,
163 InvalidAuthorizationInformation = 2202,
164 ObjectPendingTransfer = 2300,
165 ObjectNotPendingTransfer = 2301,
166 ObjectExists = 2302,
167 ObjectDoesNotExist = 2303,
168 ObjectStatusProhibitsOperation = 2304,
169 ObjectAssociationProhibitsOperation = 2305,
170 ParameterValuePolicyError = 2306,
171 UnimplementedObjectService = 2307,
172 DataManagementPolicyViolation = 2308,
173 CommandFailed = 2400,
174 CommandFailedServerClosingConnection = 2500,
175 AuthenticationErrorServerClosingConnection = 2501,
176 SessionLimitExceededServerClosingConnection = 2502,
177}
178
179impl ResultCode {
180 pub fn from_u16(code: u16) -> Option<Self> {
181 match code {
182 1000 => Some(Self::CommandCompletedSuccessfully),
183 1001 => Some(Self::CommandCompletedSuccessfullyActionPending),
184 1300 => Some(Self::CommandCompletedSuccessfullyNoMessages),
185 1301 => Some(Self::CommandCompletedSuccessfullyAckToDequeue),
186 1500 => Some(Self::CommandCompletedSuccessfullyEndingSession),
187 2000 => Some(Self::UnknownCommand),
188 2001 => Some(Self::CommandSyntaxError),
189 2002 => Some(Self::CommandUseError),
190 2003 => Some(Self::RequiredParameterMissing),
191 2004 => Some(Self::ParameterValueRangeError),
192 2005 => Some(Self::ParameterValueSyntaxError),
193 2100 => Some(Self::UnimplementedProtocolVersion),
194 2101 => Some(Self::UnimplementedCommand),
195 2102 => Some(Self::UnimplementedOption),
196 2103 => Some(Self::UnimplementedExtension),
197 2104 => Some(Self::BillingFailure),
198 2105 => Some(Self::ObjectIsNotEligibleForRenewal),
199 2106 => Some(Self::ObjectIsNotEligibleForTransfer),
200 2200 => Some(Self::AuthenticationError),
201 2201 => Some(Self::AuthorizationError),
202 2202 => Some(Self::InvalidAuthorizationInformation),
203 2300 => Some(Self::ObjectPendingTransfer),
204 2301 => Some(Self::ObjectNotPendingTransfer),
205 2302 => Some(Self::ObjectExists),
206 2303 => Some(Self::ObjectDoesNotExist),
207 2304 => Some(Self::ObjectStatusProhibitsOperation),
208 2305 => Some(Self::ObjectAssociationProhibitsOperation),
209 2306 => Some(Self::ParameterValuePolicyError),
210 2307 => Some(Self::UnimplementedObjectService),
211 2308 => Some(Self::DataManagementPolicyViolation),
212 2400 => Some(Self::CommandFailed),
213 2500 => Some(Self::CommandFailedServerClosingConnection),
214 2501 => Some(Self::AuthenticationErrorServerClosingConnection),
215 2502 => Some(Self::SessionLimitExceededServerClosingConnection),
216 _ => None,
217 }
218 }
219
220 pub fn is_success(&self) -> bool {
221 use ResultCode::*;
222 matches!(
223 self,
224 CommandCompletedSuccessfully
225 | CommandCompletedSuccessfullyActionPending
226 | CommandCompletedSuccessfullyNoMessages
227 | CommandCompletedSuccessfullyAckToDequeue
228 | CommandCompletedSuccessfullyEndingSession
229 )
230 }
231
232 pub fn is_persistent(&self) -> bool {
237 use ResultCode::*;
238 match self {
239 UnknownCommand
241 | CommandSyntaxError
242 | RequiredParameterMissing
243 | ParameterValueRangeError
244 | ParameterValueSyntaxError
245 | UnimplementedProtocolVersion
246 | UnimplementedCommand
247 | UnimplementedOption
248 | UnimplementedExtension => true,
249 CommandFailedServerClosingConnection
251 | AuthenticationErrorServerClosingConnection
252 | SessionLimitExceededServerClosingConnection => true,
253 _ => false,
254 }
255 }
256}
257
258impl<'xml> FromXml<'xml> for ResultCode {
259 fn matches(id: instant_xml::Id<'_>, field: Option<instant_xml::Id<'_>>) -> bool {
260 match field {
261 Some(field) => id == field,
262 None => false,
263 }
264 }
265
266 fn deserialize<'cx>(
267 into: &mut Self::Accumulator,
268 field: &'static str,
269 deserializer: &mut instant_xml::Deserializer<'cx, 'xml>,
270 ) -> Result<(), instant_xml::Error> {
271 let mut value = None;
272 u16::deserialize(&mut value, field, deserializer)?;
273 if let Some(value) = value {
274 *into = match Self::from_u16(value) {
275 Some(value) => Some(value),
276 None => {
277 return Err(instant_xml::Error::UnexpectedValue(format!(
278 "unexpected result code '{value}'"
279 )))
280 }
281 };
282 }
283
284 Ok(())
285 }
286
287 type Accumulator = Option<Self>;
288 const KIND: instant_xml::Kind = Kind::Scalar;
289}
290
291#[derive(Debug, Eq, FromXml, PartialEq)]
293#[xml(rename = "trID", ns(EPP_XMLNS))]
294pub struct ResponseTRID {
295 #[xml(rename = "clTRID")]
297 pub client_tr_id: Option<String>,
298 #[xml(rename = "svTRID")]
300 pub server_tr_id: String,
301}
302
303#[derive(Debug, Eq, FromXml, PartialEq)]
305#[xml(rename = "msgQ", ns(EPP_XMLNS))]
306pub struct MessageQueue {
307 #[xml(attribute)]
309 pub count: u32,
310 #[xml(attribute)]
312 pub id: String,
313 #[xml(rename = "qDate")]
315 pub date: Option<DateTime<Utc>>,
316 #[xml(rename = "msg")]
318 pub message: Option<Message>,
319}
320
321#[derive(Debug, Eq, FromXml, PartialEq)]
322#[xml(rename = "msg", ns(EPP_XMLNS))]
323pub struct Message {
324 #[xml(attribute)]
325 pub lang: Option<String>,
326 #[xml(direct)]
327 pub text: String,
328}
329
330#[derive(Debug, FromXml, PartialEq)]
331#[xml(rename = "response", ns(EPP_XMLNS))]
334pub struct Response<D, E> {
335 pub result: EppResult,
337 #[xml(rename = "msgQ")]
339 pub message_queue: Option<MessageQueue>,
340 pub res_data: Option<ResponseData<D>>,
342 pub extension: Option<Extension<E>>,
344 pub tr_ids: ResponseTRID,
346}
347
348#[derive(Debug, Eq, FromXml, PartialEq)]
349#[xml(rename = "resData", ns(EPP_XMLNS))]
350pub struct ResponseData<D> {
351 data: D,
352}
353
354impl<D> ResponseData<D> {
355 pub fn into_inner(self) -> D {
356 self.data
357 }
358}
359
360#[derive(Debug, FromXml, PartialEq)]
361#[xml(rename = "response", ns(EPP_XMLNS))]
364pub struct ResponseStatus {
365 pub result: EppResult,
367 #[xml(rename = "trID")]
368 pub tr_ids: ResponseTRID,
370}
371
372impl<T, E> Response<T, E> {
373 pub fn res_data(&self) -> Option<&T> {
375 match &self.res_data {
376 Some(res_data) => Some(&res_data.data),
377 None => None,
378 }
379 }
380
381 pub fn extension(&self) -> Option<&E> {
382 match &self.extension {
383 Some(extension) => Some(&extension.data),
384 None => None,
385 }
386 }
387
388 pub fn message_queue(&self) -> Option<&MessageQueue> {
390 match &self.message_queue {
391 Some(queue) => Some(queue),
392 None => None,
393 }
394 }
395}
396
397#[derive(Debug, Eq, FromXml, PartialEq)]
398#[xml(rename = "extension", ns(EPP_XMLNS))]
399pub struct Extension<E> {
400 pub data: E,
401}
402
403#[cfg(test)]
404mod tests {
405 use super::{ResponseStatus, ResultCode};
406 use crate::tests::{get_xml, CLTRID, SVTRID};
407 use crate::xml;
408
409 #[test]
410 fn error() {
411 let xml = get_xml("response/error.xml").unwrap();
412 let object = xml::deserialize::<ResponseStatus>(xml.as_str()).unwrap();
413
414 assert_eq!(object.result.code, ResultCode::ObjectDoesNotExist);
415 assert_eq!(object.result.message, "Object does not exist");
416 assert_eq!(object.result.ext_values.len(), 1);
417 assert_eq!(
418 object.result.ext_values[0].reason.text,
419 "545 Object not found"
420 );
421 assert_eq!(object.result.ext_values[0].reason.lang, None);
422 assert_eq!(object.tr_ids.client_tr_id.unwrap(), CLTRID);
423 assert_eq!(object.tr_ids.server_tr_id, SVTRID);
424 }
425
426 #[test]
427 fn error_ext() {
428 let xml = get_xml("response/error_ext.xml").unwrap();
429 let object = xml::deserialize::<ResponseStatus>(xml.as_str()).unwrap();
430
431 assert_eq!(object.result.code, ResultCode::ParameterValuePolicyError);
432 assert_eq!(object.result.message, "Parameter value policy error");
433 assert_eq!(object.result.ext_values.len(), 1);
434 assert_eq!(
435 object.result.ext_values[0].reason.text,
436 "Maximum of 20 domains exceeded."
437 );
438 assert_eq!(object.result.ext_values[0].reason.lang, None);
439
440 assert_eq!(object.result.ext_values[0].value.inner.name, "name");
441 assert_eq!(
442 object.result.ext_values[0].value.inner.ns,
443 "urn:ietf:params:xml:ns:domain-1.0"
444 );
445 assert_eq!(object.tr_ids.client_tr_id.unwrap(), CLTRID);
446 assert_eq!(object.tr_ids.server_tr_id, SVTRID);
447 }
448
449 #[test]
450 fn error_value_attrs() {
451 let xml = get_xml("response/error_value_attrs.xml").unwrap();
452 let object = xml::deserialize::<ResponseStatus>(xml.as_str()).unwrap();
453
454 assert_eq!(object.result.code, ResultCode::ParameterValuePolicyError);
455
456 let ext_value = &object.result.ext_values[0];
457
458 assert_eq!(ext_value.value.attributes.len(), 1);
460 assert_eq!(
461 ext_value.value.attributes[0].ns,
462 "urn:ietf:params:xml:ns:suggestion-1.0"
463 );
464 assert_eq!(ext_value.value.attributes[0].name, "suggestedValue");
465 assert_eq!(ext_value.value.attributes[0].value, "pqr-123");
466
467 assert_eq!(ext_value.value.inner.name, "name");
469 assert_eq!(
470 ext_value.value.inner.ns,
471 "urn:ietf:params:xml:ns:domain-1.0"
472 );
473 assert_eq!(ext_value.value.inner.text.as_deref(), Some("example.com"));
474
475 assert_eq!(ext_value.reason.lang.as_deref(), Some("de"));
477 assert_eq!(ext_value.reason.text, "Domainname ist nicht verfügbar.");
478
479 assert_eq!(object.tr_ids.client_tr_id.unwrap(), CLTRID);
480 assert_eq!(object.tr_ids.server_tr_id, SVTRID);
481 }
482
483 #[test]
484 fn poll_unhandled_namespace() {
485 let xml = get_xml("response/poll_unhandled_namespace.xml").unwrap();
486 let object = xml::deserialize::<super::Response<(), ()>>(xml.as_str()).unwrap();
487
488 assert_eq!(
489 object.result.code,
490 ResultCode::CommandCompletedSuccessfullyAckToDequeue
491 );
492 assert_eq!(
493 object.result.message,
494 "Command completed successfully; ack to dequeue"
495 );
496 assert_eq!(object.result.ext_values.len(), 2);
497
498 let ev0 = &object.result.ext_values[0];
500 assert_eq!(ev0.value.inner.name, "infData");
501 assert_eq!(ev0.value.inner.ns, "urn:ietf:params:xml:ns:domain-1.0");
502 assert_eq!(ev0.value.inner.children.len(), 10);
503 assert_eq!(ev0.value.inner.children[0].name, "name");
505 assert_eq!(
506 ev0.value.inner.children[0].text.as_deref(),
507 Some("domain.example")
508 );
509 let status = &ev0.value.inner.children[2];
511 assert_eq!(status.name, "status");
512 assert_eq!(status.attributes.len(), 1);
513 assert_eq!(status.attributes[0].name, "s");
514 assert_eq!(status.attributes[0].value, "ok");
515 let contact = &ev0.value.inner.children[4];
517 assert_eq!(contact.name, "contact");
518 assert_eq!(contact.attributes[0].name, "type");
519 assert_eq!(contact.attributes[0].value, "admin");
520 assert_eq!(contact.text.as_deref(), Some("sh8013"));
521
522 assert_eq!(
523 ev0.reason.text.trim(),
524 "urn:ietf:params:xml:ns:domain-1.0 not in login services"
525 );
526
527 let ev1 = &object.result.ext_values[1];
529 assert_eq!(ev1.value.inner.name, "changeData");
530 assert_eq!(ev1.value.inner.ns, "urn:ietf:params:xml:ns:changePoll-1.0");
531 assert_eq!(ev1.value.inner.attributes.len(), 1);
533 assert_eq!(ev1.value.inner.attributes[0].name, "state");
534 assert_eq!(ev1.value.inner.attributes[0].value, "after");
535 assert_eq!(ev1.value.inner.children.len(), 6);
536 let case_id = &ev1.value.inner.children[4];
538 assert_eq!(case_id.name, "caseId");
539 assert_eq!(case_id.attributes[0].name, "type");
540 assert_eq!(case_id.attributes[0].value, "urs");
541
542 assert_eq!(
543 ev1.reason.text.trim(),
544 "urn:ietf:params:xml:ns:changePoll-1.0 not in login services"
545 );
546
547 let mq = object.message_queue.unwrap();
549 assert_eq!(mq.count, 201);
550 assert_eq!(mq.id, "1");
551
552 assert_eq!(object.tr_ids.client_tr_id.unwrap(), "ABC-12345");
553 assert_eq!(object.tr_ids.server_tr_id, "54322-XYZ");
554 }
555
556 #[test]
557 fn domain_info_unhandled_namespace() {
558 let xml = get_xml("response/domain/info_unhandled_namespace.xml").unwrap();
559 let object =
560 xml::deserialize::<super::Response<crate::domain::info::InfoData, ()>>(xml.as_str())
561 .unwrap();
562
563 assert_eq!(object.result.code, ResultCode::CommandCompletedSuccessfully);
564
565 assert_eq!(object.result.ext_values.len(), 1);
567 let ev = &object.result.ext_values[0];
568 assert_eq!(ev.value.inner.name, "infData");
569 assert_eq!(ev.value.inner.ns, "urn:ietf:params:xml:ns:rgp-1.0");
570 assert_eq!(ev.value.inner.children.len(), 1);
571 let rgp_status = &ev.value.inner.children[0];
572 assert_eq!(rgp_status.name, "rgpStatus");
573 assert_eq!(rgp_status.attributes.len(), 1);
574 assert_eq!(rgp_status.attributes[0].name, "s");
575 assert_eq!(rgp_status.attributes[0].value, "redemptionPeriod");
576 assert_eq!(
577 ev.reason.text,
578 "urn:ietf:params:xml:ns:rgp-1.0 not in login services"
579 );
580
581 let result = object.res_data().unwrap();
583 assert_eq!(result.name, "example.com");
584 assert_eq!(result.roid, "EXAMPLE1-REP");
585
586 assert_eq!(object.tr_ids.client_tr_id.unwrap(), "ABC-12345");
587 assert_eq!(object.tr_ids.server_tr_id, "54322-XYZ");
588 }
589}