1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::util::error::Error;
8use crate::message::MessagePayload;
9use crate::ns;
10use crate::presence::PresencePayload;
11use jid::Jid;
12use minidom::Element;
13use std::collections::BTreeMap;
14use try_from::TryFrom;
15
16generate_attribute!(
17 /// The type of the error.
18 ErrorType, "type", {
19 /// Retry after providing credentials.
20 Auth => "auth",
21
22 /// Do not retry (the error cannot be remedied).
23 Cancel => "cancel",
24
25 /// Proceed (the condition was only a warning).
26 Continue => "continue",
27
28 /// Retry after changing the data sent.
29 Modify => "modify",
30
31 /// Retry after waiting (the error is temporary).
32 Wait => "wait",
33 }
34);
35
36generate_element_enum!(
37 /// List of valid error conditions.
38 DefinedCondition, "condition", XMPP_STANZAS, {
39 /// The sender has sent a stanza containing XML that does not conform
40 /// to the appropriate schema or that cannot be processed (e.g., an IQ
41 /// stanza that includes an unrecognized value of the 'type' attribute,
42 /// or an element that is qualified by a recognized namespace but that
43 /// violates the defined syntax for the element); the associated error
44 /// type SHOULD be "modify".
45 BadRequest => "bad-request",
46
47 /// Access cannot be granted because an existing resource exists with
48 /// the same name or address; the associated error type SHOULD be
49 /// "cancel".
50 Conflict => "conflict",
51
52 /// The feature represented in the XML stanza is not implemented by the
53 /// intended recipient or an intermediate server and therefore the
54 /// stanza cannot be processed (e.g., the entity understands the
55 /// namespace but does not recognize the element name); the associated
56 /// error type SHOULD be "cancel" or "modify".
57 FeatureNotImplemented => "feature-not-implemented",
58
59 /// The requesting entity does not possess the necessary permissions to
60 /// perform an action that only certain authorized roles or individuals
61 /// are allowed to complete (i.e., it typically relates to
62 /// authorization rather than authentication); the associated error
63 /// type SHOULD be "auth".
64 Forbidden => "forbidden",
65
66 /// The recipient or server can no longer be contacted at this address,
67 /// typically on a permanent basis (as opposed to the <redirect/> error
68 /// condition, which is used for temporary addressing failures); the
69 /// associated error type SHOULD be "cancel" and the error stanza
70 /// SHOULD include a new address (if available) as the XML character
71 /// data of the <gone/> element (which MUST be a Uniform Resource
72 /// Identifier [URI] or Internationalized Resource Identifier [IRI] at
73 /// which the entity can be contacted, typically an XMPP IRI as
74 /// specified in [XMPP‑URI]).
75 Gone => "gone",
76
77 /// The server has experienced a misconfiguration or other internal
78 /// error that prevents it from processing the stanza; the associated
79 /// error type SHOULD be "cancel".
80 InternalServerError => "internal-server-error",
81
82 /// The addressed JID or item requested cannot be found; the associated
83 /// error type SHOULD be "cancel".
84 ItemNotFound => "item-not-found",
85
86 /// The sending entity has provided (e.g., during resource binding) or
87 /// communicated (e.g., in the 'to' address of a stanza) an XMPP
88 /// address or aspect thereof that violates the rules defined in
89 /// [XMPP‑ADDR]; the associated error type SHOULD be "modify".
90 JidMalformed => "jid-malformed",
91
92 /// The recipient or server understands the request but cannot process
93 /// it because the request does not meet criteria defined by the
94 /// recipient or server (e.g., a request to subscribe to information
95 /// that does not simultaneously include configuration parameters
96 /// needed by the recipient); the associated error type SHOULD be
97 /// "modify".
98 NotAcceptable => "not-acceptable",
99
100 /// The recipient or server does not allow any entity to perform the
101 /// action (e.g., sending to entities at a blacklisted domain); the
102 /// associated error type SHOULD be "cancel".
103 NotAllowed => "not-allowed",
104
105 /// The sender needs to provide credentials before being allowed to
106 /// perform the action, or has provided improper credentials (the name
107 /// "not-authorized", which was borrowed from the "401 Unauthorized"
108 /// error of [HTTP], might lead the reader to think that this condition
109 /// relates to authorization, but instead it is typically used in
110 /// relation to authentication); the associated error type SHOULD be
111 /// "auth".
112 NotAuthorized => "not-authorized",
113
114 /// The entity has violated some local service policy (e.g., a message
115 /// contains words that are prohibited by the service) and the server
116 /// MAY choose to specify the policy in the <text/> element or in an
117 /// application-specific condition element; the associated error type
118 /// SHOULD be "modify" or "wait" depending on the policy being
119 /// violated.
120 PolicyViolation => "policy-violation",
121
122 /// The intended recipient is temporarily unavailable, undergoing
123 /// maintenance, etc.; the associated error type SHOULD be "wait".
124 RecipientUnavailable => "recipient-unavailable",
125
126 /// The recipient or server is redirecting requests for this
127 /// information to another entity, typically in a temporary fashion (as
128 /// opposed to the <gone/> error condition, which is used for permanent
129 /// addressing failures); the associated error type SHOULD be "modify"
130 /// and the error stanza SHOULD contain the alternate address in the
131 /// XML character data of the <redirect/> element (which MUST be a URI
132 /// or IRI with which the sender can communicate, typically an XMPP IRI
133 /// as specified in [XMPP‑URI]).
134 Redirect => "redirect",
135
136 /// The requesting entity is not authorized to access the requested
137 /// service because prior registration is necessary (examples of prior
138 /// registration include members-only rooms in XMPP multi-user chat
139 /// [XEP‑0045] and gateways to non-XMPP instant messaging services,
140 /// which traditionally required registration in order to use the
141 /// gateway [XEP‑0100]); the associated error type SHOULD be "auth".
142 RegistrationRequired => "registration-required",
143
144 /// A remote server or service specified as part or all of the JID of
145 /// the intended recipient does not exist or cannot be resolved (e.g.,
146 /// there is no _xmpp-server._tcp DNS SRV record, the A or AAAA
147 /// fallback resolution fails, or A/AAAA lookups succeed but there is
148 /// no response on the IANA-registered port 5269); the associated error
149 /// type SHOULD be "cancel".
150 RemoteServerNotFound => "remote-server-not-found",
151
152 /// A remote server or service specified as part or all of the JID of
153 /// the intended recipient (or needed to fulfill a request) was
154 /// resolved but communications could not be established within a
155 /// reasonable amount of time (e.g., an XML stream cannot be
156 /// established at the resolved IP address and port, or an XML stream
157 /// can be established but stream negotiation fails because of problems
158 /// with TLS, SASL, Server Dialback, etc.); the associated error type
159 /// SHOULD be "wait" (unless the error is of a more permanent nature,
160 /// e.g., the remote server is found but it cannot be authenticated or
161 /// it violates security policies).
162 RemoteServerTimeout => "remote-server-timeout",
163
164 /// The server or recipient is busy or lacks the system resources
165 /// necessary to service the request; the associated error type SHOULD
166 /// be "wait".
167 ResourceConstraint => "resource-constraint",
168
169 /// The server or recipient does not currently provide the requested
170 /// service; the associated error type SHOULD be "cancel".
171 ServiceUnavailable => "service-unavailable",
172
173 /// The requesting entity is not authorized to access the requested
174 /// service because a prior subscription is necessary (examples of
175 /// prior subscription include authorization to receive presence
176 /// information as defined in [XMPP‑IM] and opt-in data feeds for XMPP
177 /// publish-subscribe as defined in [XEP‑0060]); the associated error
178 /// type SHOULD be "auth".
179 SubscriptionRequired => "subscription-required",
180
181 /// The error condition is not one of those defined by the other
182 /// conditions in this list; any error type can be associated with this
183 /// condition, and it SHOULD NOT be used except in conjunction with an
184 /// application-specific condition.
185 UndefinedCondition => "undefined-condition",
186
187 /// The recipient or server understood the request but was not
188 /// expecting it at this time (e.g., the request was out of order); the
189 /// associated error type SHOULD be "wait" or "modify".
190 UnexpectedRequest => "unexpected-request",
191 }
192);
193
194type Lang = String;
195
196/// The representation of a stanza error.
197#[derive(Debug, Clone)]
198pub struct StanzaError {
199 /// The type of this error.
200 pub type_: ErrorType,
201
202 /// The JID of the entity who set this error.
203 pub by: Option<Jid>,
204
205 /// One of the defined conditions for this error to happen.
206 pub defined_condition: DefinedCondition,
207
208 /// Human-readable description of this error.
209 pub texts: BTreeMap<Lang, String>,
210
211 /// A protocol-specific extension for this error.
212 pub other: Option<Element>,
213}
214
215impl MessagePayload for StanzaError {}
216impl PresencePayload for StanzaError {}
217
218impl TryFrom<Element> for StanzaError {
219 type Err = Error;
220
221 fn try_from(elem: Element) -> Result<StanzaError, Error> {
222 check_self!(elem, "error", DEFAULT_NS);
223
224 let type_ = get_attr!(elem, "type", Required);
225 let by = get_attr!(elem, "by", Option);
226 let mut defined_condition = None;
227 let mut texts = BTreeMap::new();
228 let mut other = None;
229
230 for child in elem.children() {
231 if child.is("text", ns::XMPP_STANZAS) {
232 check_no_children!(child, "text");
233 let lang = get_attr!(elem, "xml:lang", Default);
234 if texts.insert(lang, child.text()).is_some() {
235 return Err(Error::ParseError(
236 "Text element present twice for the same xml:lang.",
237 ));
238 }
239 } else if child.has_ns(ns::XMPP_STANZAS) {
240 if defined_condition.is_some() {
241 return Err(Error::ParseError(
242 "Error must not have more than one defined-condition.",
243 ));
244 }
245 check_no_children!(child, "defined-condition");
246 let condition = DefinedCondition::try_from(child.clone())?;
247 defined_condition = Some(condition);
248 } else {
249 if other.is_some() {
250 return Err(Error::ParseError(
251 "Error must not have more than one other element.",
252 ));
253 }
254 other = Some(child.clone());
255 }
256 }
257 let defined_condition =
258 defined_condition.ok_or(Error::ParseError("Error must have a defined-condition."))?;
259
260 Ok(StanzaError {
261 type_,
262 by,
263 defined_condition,
264 texts,
265 other,
266 })
267 }
268}
269
270impl From<StanzaError> for Element {
271 fn from(err: StanzaError) -> Element {
272 let mut root = Element::builder("error")
273 .ns(ns::DEFAULT_NS)
274 .attr("type", err.type_)
275 .attr("by", err.by)
276 .append(err.defined_condition)
277 .build();
278 for (lang, text) in err.texts {
279 let elem = Element::builder("text")
280 .ns(ns::XMPP_STANZAS)
281 .attr("xml:lang", lang)
282 .append(text)
283 .build();
284 root.append_child(elem);
285 }
286 if let Some(other) = err.other {
287 root.append_child(other);
288 }
289 root
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[cfg(target_pointer_width = "32")]
298 #[test]
299 fn test_size() {
300 assert_size!(ErrorType, 1);
301 assert_size!(DefinedCondition, 1);
302 assert_size!(StanzaError, 104);
303 }
304
305 #[cfg(target_pointer_width = "64")]
306 #[test]
307 fn test_size() {
308 assert_size!(ErrorType, 1);
309 assert_size!(DefinedCondition, 1);
310 assert_size!(StanzaError, 208);
311 }
312
313 #[test]
314 fn test_simple() {
315 #[cfg(not(feature = "component"))]
316 let elem: Element = "<error xmlns='jabber:client' type='cancel'><undefined-condition xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error>".parse().unwrap();
317 #[cfg(feature = "component")]
318 let elem: Element = "<error xmlns='jabber:component:accept' type='cancel'><undefined-condition xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error>".parse().unwrap();
319 let error = StanzaError::try_from(elem).unwrap();
320 assert_eq!(error.type_, ErrorType::Cancel);
321 assert_eq!(
322 error.defined_condition,
323 DefinedCondition::UndefinedCondition
324 );
325 }
326
327 #[test]
328 fn test_invalid_type() {
329 #[cfg(not(feature = "component"))]
330 let elem: Element = "<error xmlns='jabber:client'/>".parse().unwrap();
331 #[cfg(feature = "component")]
332 let elem: Element = "<error xmlns='jabber:component:accept'/>".parse().unwrap();
333 let error = StanzaError::try_from(elem).unwrap_err();
334 let message = match error {
335 Error::ParseError(string) => string,
336 _ => panic!(),
337 };
338 assert_eq!(message, "Required attribute 'type' missing.");
339
340 #[cfg(not(feature = "component"))]
341 let elem: Element = "<error xmlns='jabber:client' type='coucou'/>"
342 .parse()
343 .unwrap();
344 #[cfg(feature = "component")]
345 let elem: Element = "<error xmlns='jabber:component:accept' type='coucou'/>"
346 .parse()
347 .unwrap();
348 let error = StanzaError::try_from(elem).unwrap_err();
349 let message = match error {
350 Error::ParseError(string) => string,
351 _ => panic!(),
352 };
353 assert_eq!(message, "Unknown value for 'type' attribute.");
354 }
355
356 #[test]
357 fn test_invalid_condition() {
358 #[cfg(not(feature = "component"))]
359 let elem: Element = "<error xmlns='jabber:client' type='cancel'/>"
360 .parse()
361 .unwrap();
362 #[cfg(feature = "component")]
363 let elem: Element = "<error xmlns='jabber:component:accept' type='cancel'/>"
364 .parse()
365 .unwrap();
366 let error = StanzaError::try_from(elem).unwrap_err();
367 let message = match error {
368 Error::ParseError(string) => string,
369 _ => panic!(),
370 };
371 assert_eq!(message, "Error must have a defined-condition.");
372 }
373}