stanza_error.rs

  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 try_from::TryFrom;
  8use std::collections::BTreeMap;
  9
 10use minidom::Element;
 11
 12use error::Error;
 13use jid::Jid;
 14use ns;
 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 TryFrom<Element> for StanzaError {
216    type Err = Error;
217
218    fn try_from(elem: Element) -> Result<StanzaError, Error> {
219        check_self!(elem, "error", DEFAULT_NS);
220
221        let type_ = get_attr!(elem, "type", required);
222        let by = get_attr!(elem, "by", optional);
223        let mut defined_condition = None;
224        let mut texts = BTreeMap::new();
225        let mut other = None;
226
227        for child in elem.children() {
228            if child.is("text", ns::XMPP_STANZAS) {
229                check_no_children!(child, "text");
230                let lang = get_attr!(elem, "xml:lang", default);
231                if texts.insert(lang, child.text()).is_some() {
232                    return Err(Error::ParseError("Text element present twice for the same xml:lang."));
233                }
234            } else if child.has_ns(ns::XMPP_STANZAS) {
235                if defined_condition.is_some() {
236                    return Err(Error::ParseError("Error must not have more than one defined-condition."));
237                }
238                check_no_children!(child, "defined-condition");
239                let condition = DefinedCondition::try_from(child.clone())?;
240                defined_condition = Some(condition);
241            } else {
242                if other.is_some() {
243                    return Err(Error::ParseError("Error must not have more than one other element."));
244                }
245                other = Some(child.clone());
246            }
247        }
248        let defined_condition = defined_condition.ok_or(Error::ParseError("Error must have a defined-condition."))?;
249
250        Ok(StanzaError {
251            type_: type_,
252            by: by,
253            defined_condition: defined_condition,
254            texts: texts,
255            other: other,
256        })
257    }
258}
259
260impl From<StanzaError> for Element {
261    fn from(err: StanzaError) -> Element {
262        let mut root = Element::builder("error")
263                               .ns(ns::DEFAULT_NS)
264                               .attr("type", err.type_)
265                               .attr("by", err.by)
266                               .append(err.defined_condition)
267                               .build();
268        for (lang, text) in err.texts {
269            let elem = Element::builder("text")
270                               .ns(ns::XMPP_STANZAS)
271                               .attr("xml:lang", lang)
272                               .append(text)
273                               .build();
274            root.append_child(elem);
275        }
276        if let Some(other) = err.other {
277            root.append_child(other);
278        }
279        root
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn test_simple() {
289        #[cfg(not(feature = "component"))]
290        let elem: Element = "<error xmlns='jabber:client' type='cancel'><undefined-condition xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error>".parse().unwrap();
291        #[cfg(feature = "component")]
292        let elem: Element = "<error xmlns='jabber:component:accept' type='cancel'><undefined-condition xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error>".parse().unwrap();
293        let error = StanzaError::try_from(elem).unwrap();
294        assert_eq!(error.type_, ErrorType::Cancel);
295        assert_eq!(error.defined_condition, DefinedCondition::UndefinedCondition);
296    }
297
298    #[test]
299    fn test_invalid_type() {
300        #[cfg(not(feature = "component"))]
301        let elem: Element = "<error xmlns='jabber:client'/>".parse().unwrap();
302        #[cfg(feature = "component")]
303        let elem: Element = "<error xmlns='jabber:component:accept'/>".parse().unwrap();
304        let error = StanzaError::try_from(elem).unwrap_err();
305        let message = match error {
306            Error::ParseError(string) => string,
307            _ => panic!(),
308        };
309        assert_eq!(message, "Required attribute 'type' missing.");
310
311        #[cfg(not(feature = "component"))]
312        let elem: Element = "<error xmlns='jabber:client' type='coucou'/>".parse().unwrap();
313        #[cfg(feature = "component")]
314        let elem: Element = "<error xmlns='jabber:component:accept' type='coucou'/>".parse().unwrap();
315        let error = StanzaError::try_from(elem).unwrap_err();
316        let message = match error {
317            Error::ParseError(string) => string,
318            _ => panic!(),
319        };
320        assert_eq!(message, "Unknown value for 'type' attribute.");
321    }
322
323    #[test]
324    fn test_invalid_condition() {
325        #[cfg(not(feature = "component"))]
326        let elem: Element = "<error xmlns='jabber:client' type='cancel'/>".parse().unwrap();
327        #[cfg(feature = "component")]
328        let elem: Element = "<error xmlns='jabber:component:accept' type='cancel'/>".parse().unwrap();
329        let error = StanzaError::try_from(elem).unwrap_err();
330        let message = match error {
331            Error::ParseError(string) => string,
332            _ => panic!(),
333        };
334        assert_eq!(message, "Error must have a defined-condition.");
335    }
336}