001/**
002 *
003 * Copyright 2003-2007 Jive Software, 2015 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.packet;
018
019import java.util.Arrays;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Locale;
023import java.util.Map;
024import java.util.logging.Logger;
025
026import org.jivesoftware.smack.util.Objects;
027import org.jivesoftware.smack.util.StringUtils;
028import org.jivesoftware.smack.util.XmlStringBuilder;
029
030/**
031 * Represents an XMPP error sub-packet. Typically, a server responds to a request that has
032 * problems by sending the stanza(/packet) back and including an error packet. Each error has a type,
033 * error condition as well as as an optional text explanation. Typical errors are:<p>
034 *
035 * <table border=1>
036 *      <caption>XMPP Errors</caption>
037 *      <hr><td><b>XMPP Error Condition</b></td><td><b>Type</b></td><td><b>RFC 6120 Section</b></td></hr>
038 *      <tr><td>bad-request</td><td>MODIFY</td><td>8.3.3.1</td></tr>
039 *      <tr><td>conflict</td><td>CANCEL</td><td>8.3.3.2</td></tr>
040 *      <tr><td>feature-not-implemented</td><td>CANCEL</td><td>8.3.3.3</td></tr>
041 *      <tr><td>forbidden</td><td>AUTH</td><td>8.3.3.4</td></tr>
042 *      <tr><td>gone</td><td>MODIFY</td><td>8.3.3.5</td></tr>
043 *      <tr><td>internal-server-error</td><td>WAIT</td><td>8.3.3.6</td></tr>
044 *      <tr><td>item-not-found</td><td>CANCEL</td><td>8.3.3.7</td></tr>
045 *      <tr><td>jid-malformed</td><td>MODIFY</td><td>8.3.3.8</td></tr>
046 *      <tr><td>not-acceptable</td><td> MODIFY</td><td>8.3.3.9</td></tr>
047 *      <tr><td>not-allowed</td><td>CANCEL</td><td>8.3.3.10</td></tr>
048 *      <tr><td>not-authorized</td><td>AUTH</td><td>8.3.3.11</td></tr>
049 *      <tr><td>policy-violation</td><td>AUTH</td><td>8.3.3.12</td></tr>
050 *      <tr><td>recipient-unavailable</td><td>WAIT</td><td>8.3.3.13</td></tr>
051 *      <tr><td>redirect</td><td>MODIFY</td><td>8.3.3.14</td></tr>
052 *      <tr><td>registration-required</td><td>AUTH</td><td>8.3.3.15</td></tr>
053 *      <tr><td>remote-server-not-found</td><td>CANCEL</td><td>8.3.3.16</td></tr>
054 *      <tr><td>remote-server-timeout</td><td>WAIT</td><td>8.3.3.17</td></tr>
055 *      <tr><td>resource-constraint</td><td>WAIT</td><td>8.3.3.18</td></tr>
056 *      <tr><td>service-unavailable</td><td>CANCEL</td><td>8.3.3.19</td></tr>
057 *      <tr><td>subscription-required</td><td>AUTH</td><td>8.3.3.20</td></tr>
058 *      <tr><td>undefined-condition</td><td>WAIT</td><td>8.3.3.21</td></tr>
059 *      <tr><td>unexpected-request</td><td>WAIT</td><td>8.3.3.22</td></tr>
060 * </table>
061 *
062 * @author Matt Tucker
063 * @see <a href="http://xmpp.org/rfcs/rfc6120.html#stanzas-error-syntax">RFC 6120 - 8.3.2 Syntax: The Syntax of XMPP error stanzas</a>
064 */
065// TODO Rename this class to StanzaError (RFC 6120 ยง 8.3) in Smack 4.3, as this is what this class actually is. SMACK-769
066// TODO Use StanzaErrorTextElement here.
067public class XMPPError extends AbstractError {
068
069    public static final String NAMESPACE = "urn:ietf:params:xml:ns:xmpp-stanzas";
070    public static final String ERROR = "error";
071
072    private static final Logger LOGGER = Logger.getLogger(XMPPError.class.getName());
073    private static final Map<Condition, Type> CONDITION_TO_TYPE = new HashMap<Condition, Type>();
074
075    static {
076        CONDITION_TO_TYPE.put(Condition.bad_request, Type.MODIFY);
077        CONDITION_TO_TYPE.put(Condition.conflict, Type.CANCEL);
078        CONDITION_TO_TYPE.put(Condition.feature_not_implemented, Type.CANCEL);
079        CONDITION_TO_TYPE.put(Condition.forbidden, Type.AUTH);
080        CONDITION_TO_TYPE.put(Condition.gone, Type.CANCEL);
081        CONDITION_TO_TYPE.put(Condition.internal_server_error, Type.CANCEL);
082        CONDITION_TO_TYPE.put(Condition.item_not_found, Type.CANCEL);
083        CONDITION_TO_TYPE.put(Condition.jid_malformed, Type.MODIFY);
084        CONDITION_TO_TYPE.put(Condition.not_acceptable, Type.MODIFY);
085        CONDITION_TO_TYPE.put(Condition.not_allowed, Type.CANCEL);
086        CONDITION_TO_TYPE.put(Condition.not_authorized, Type.AUTH);
087        CONDITION_TO_TYPE.put(Condition.policy_violation, Type.MODIFY);
088        CONDITION_TO_TYPE.put(Condition.recipient_unavailable, Type.WAIT);
089        CONDITION_TO_TYPE.put(Condition.redirect, Type.MODIFY);
090        CONDITION_TO_TYPE.put(Condition.registration_required, Type.AUTH);
091        CONDITION_TO_TYPE.put(Condition.remote_server_not_found, Type.CANCEL);
092        CONDITION_TO_TYPE.put(Condition.remote_server_timeout, Type.WAIT);
093        CONDITION_TO_TYPE.put(Condition.resource_constraint, Type.WAIT);
094        CONDITION_TO_TYPE.put(Condition.service_unavailable, Type.WAIT);
095        CONDITION_TO_TYPE.put(Condition.subscription_required, Type.WAIT);
096        CONDITION_TO_TYPE.put(Condition.unexpected_request, Type.MODIFY);
097    }
098
099    private final Condition condition;
100    private final String conditionText;
101    private final String errorGenerator;
102    private final Type type;
103    private final Stanza stanza;
104
105    // TODO: Deprecated constructors
106    // deprecate in 4.3
107
108    /**
109     * Create a new XMPPError.
110     *
111     * @param condition
112     * @deprecated use {@link Builder} instead.
113     */
114    @Deprecated
115    public XMPPError(Condition condition) {
116        this(condition, null, null, null, null, null, null);
117    }
118
119    /**
120     * Create a new XMPPError.
121     *
122     * @param condition
123     * @param applicationSpecificCondition
124     * @deprecated use {@link Builder} instead.
125     */
126    @Deprecated
127    public XMPPError(Condition condition, ExtensionElement applicationSpecificCondition) {
128        this(condition, null, null, null, null, Arrays.asList(applicationSpecificCondition), null);
129    }
130
131    /**
132     * Creates a new error with the specified type, condition and message.
133     * This constructor is used when the condition is not recognized automatically by XMPPError
134     * i.e. there is not a defined instance of ErrorCondition or it does not apply the default 
135     * specification.
136     * 
137     * @param type the error type.
138     * @param condition the error condition.
139     * @param descriptiveTexts 
140     * @param extensions list of stanza(/packet) extensions
141     * @deprecated use {@link Builder} instead.
142     */
143    @Deprecated
144    public XMPPError(Condition condition, String conditionText, String errorGenerator, Type type, Map<String, String> descriptiveTexts,
145            List<ExtensionElement> extensions) {
146        this(condition, conditionText, errorGenerator, type, descriptiveTexts, extensions, null);
147    }
148
149    /**
150     * Creates a new error with the specified type, condition and message.
151     * This constructor is used when the condition is not recognized automatically by XMPPError
152     * i.e. there is not a defined instance of ErrorCondition or it does not apply the default 
153     * specification.
154     * 
155     * @param type the error type.
156     * @param condition the error condition.
157     * @param descriptiveTexts 
158     * @param extensions list of stanza(/packet) extensions
159     * @param stanza the stanza carrying this XMPP error.
160     */
161    public XMPPError(Condition condition, String conditionText, String errorGenerator, Type type, Map<String, String> descriptiveTexts,
162            List<ExtensionElement> extensions, Stanza stanza) {
163        super(descriptiveTexts, NAMESPACE, extensions);
164        this.condition = Objects.requireNonNull(condition, "condition must not be null");
165        this.stanza = stanza;
166        // Some implementations may send the condition as non-empty element containing the empty string, that is
167        // <condition xmlns='foo'></condition>, in this case the parser may calls this constructor with the empty string
168        // as conditionText, therefore reset it to null if it's the empty string
169        if (StringUtils.isNullOrEmpty(conditionText)) {
170            conditionText = null;
171        }
172        if (conditionText != null) {
173            switch (condition) {
174            case gone:
175            case redirect:
176                break;
177            default:
178                throw new IllegalArgumentException(
179                                "Condition text can only be set with condtion types 'gone' and 'redirect', not "
180                                                + condition);
181            }
182        }
183        this.conditionText = conditionText;
184        this.errorGenerator = errorGenerator;
185        if (type == null) {
186            Type determinedType = CONDITION_TO_TYPE.get(condition);
187            if (determinedType == null) {
188                LOGGER.warning("Could not determine type for condition: " + condition);
189                determinedType = Type.CANCEL;
190            }
191            this.type = determinedType;
192        } else {
193            this.type = type;
194        }
195    }
196
197    /**
198     * Returns the error condition.
199     *
200     * @return the error condition.
201     */
202    public Condition getCondition() {
203        return condition;
204    }
205
206    /**
207     * Returns the error type.
208     *
209     * @return the error type.
210     */
211    public Type getType() {
212        return type;
213    }
214
215    public String getErrorGenerator() {
216        return errorGenerator;
217    }
218
219    public String getConditionText() {
220        return conditionText;
221    }
222
223    /**
224     * Get the stanza carrying the XMPP error.
225     *
226     * @return the stanza carrying the XMPP error.
227     * @since 4.2
228     */
229    public Stanza getStanza() {
230        return stanza;
231    }
232
233    @Override
234    public String toString() {
235        StringBuilder sb = new StringBuilder("XMPPError: ");
236        sb.append(condition.toString()).append(" - ").append(type.toString());
237        if (errorGenerator != null) {
238            sb.append(". Generated by ").append(errorGenerator);
239        }
240        return sb.toString();
241    }
242
243    /**
244     * Returns the error as XML.
245     *
246     * @return the error as XML.
247     */
248    public XmlStringBuilder toXML() {
249        XmlStringBuilder xml = new XmlStringBuilder();
250        xml.halfOpenElement(ERROR);
251        xml.attribute("type", type.toString());
252        xml.optAttribute("by", errorGenerator);
253        xml.rightAngleBracket();
254
255        xml.halfOpenElement(condition.toString());
256        xml.xmlnsAttribute(NAMESPACE);
257        if (conditionText != null) {
258            xml.rightAngleBracket();
259            xml.escape(conditionText);
260            xml.closeElement(condition.toString());
261        }
262        else {
263            xml.closeEmptyElement();
264        }
265
266        addDescriptiveTextsAndExtensions(xml);
267
268        xml.closeElement(ERROR);
269        return xml;
270    }
271
272    public static XMPPError.Builder from(Condition condition, String descriptiveText) {
273        Map<String, String> descriptiveTexts = new HashMap<String, String>();
274        descriptiveTexts.put("en", descriptiveText);
275        return getBuilder().setCondition(condition).setDescriptiveTexts(descriptiveTexts);
276    }
277
278    public static Builder getBuilder() {
279        return new Builder();
280    }
281
282    public static Builder getBuilder(Condition condition) {
283        return getBuilder().setCondition(condition);
284    }
285
286    public static Builder getBuilder(XMPPError xmppError) {
287        return getBuilder().copyFrom(xmppError);
288    }
289
290    public static final class Builder extends AbstractError.Builder<Builder> {
291        private Condition condition;
292        private String conditionText;
293        private String errorGenerator;
294        private Type type;
295        private Stanza stanza;
296
297        private Builder() {
298        }
299
300        public Builder setCondition(Condition condition) {
301            this.condition = condition;
302            return this;
303        }
304
305        public Builder setType(Type type) {
306            this.type = type;
307            return this;
308        }
309
310        public Builder setConditionText(String conditionText) {
311            this.conditionText = conditionText;
312            return this;
313        }
314
315        public Builder setErrorGenerator(String errorGenerator) {
316            this.errorGenerator = errorGenerator;
317            return this;
318        }
319
320        public Builder setStanza(Stanza stanza) {
321            this.stanza = stanza;
322            return this;
323        }
324
325        public Builder copyFrom(XMPPError xmppError) {
326            setCondition(xmppError.getCondition());
327            setType(xmppError.getType());
328            setConditionText(xmppError.getConditionText());
329            setErrorGenerator(xmppError.getErrorGenerator());
330            setStanza(xmppError.getStanza());
331            setDescriptiveTexts(xmppError.descriptiveTexts);
332            setTextNamespace(xmppError.textNamespace);
333            setExtensions(xmppError.extensions);
334            return this;
335        }
336
337        public XMPPError build() {
338            return new XMPPError(condition, conditionText, errorGenerator, type, descriptiveTexts,
339            extensions, stanza);
340        }
341
342        @Override
343        protected Builder getThis() {
344            return this;
345        }
346    }
347    /**
348     * A class to represent the type of the Error. The types are:
349     *
350     * <ul>
351     *      <li>XMPPError.Type.WAIT - retry after waiting (the error is temporary)
352     *      <li>XMPPError.Type.CANCEL - do not retry (the error is unrecoverable)
353     *      <li>XMPPError.Type.MODIFY - retry after changing the data sent
354     *      <li>XMPPError.Type.AUTH - retry after providing credentials
355     *      <li>XMPPError.Type.CONTINUE - proceed (the condition was only a warning)
356     * </ul>
357     */
358    public static enum Type {
359        WAIT,
360        CANCEL,
361        MODIFY,
362        AUTH,
363        CONTINUE;
364
365        @Override
366        public String toString() {
367            return name().toLowerCase(Locale.US);
368        }
369
370        public static Type fromString(String string) {
371            string = string.toUpperCase(Locale.US);
372            return Type.valueOf(string);
373        }
374    }
375
376    public enum Condition {
377        bad_request,
378        conflict,
379        feature_not_implemented,
380        forbidden,
381        gone,
382        internal_server_error,
383        item_not_found,
384        jid_malformed,
385        not_acceptable,
386        not_allowed,
387        not_authorized,
388        policy_violation,
389        recipient_unavailable,
390        redirect,
391        registration_required,
392        remote_server_not_found,
393        remote_server_timeout,
394        resource_constraint,
395        service_unavailable,
396        subscription_required,
397        undefined_condition,
398        unexpected_request;
399
400        @Override
401        public String toString() {
402            return this.name().replace('_', '-');
403        }
404
405        public static Condition fromString(String string) {
406            // Backwards compatibility for older implementations still using RFC 3920. RFC 6120
407            // changed 'xml-not-well-formed' to 'not-well-formed'.
408            if ("xml-not-well-formed".equals(string)) {
409                string = "not-well-formed";
410            }
411            string = string.replace('-', '_');
412            Condition condition = null;
413            try {
414                condition = Condition.valueOf(string);
415            } catch (Exception e) {
416                throw new IllegalStateException("Could not transform string '" + string + "' to XMPPErrorCondition", e);
417            }
418            return condition;
419        }
420    }
421
422}