001/**
002 *
003 * Copyright 2009 Jive Software, 2018-2020 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;
018
019import java.io.IOException;
020import java.io.Reader;
021import java.io.Writer;
022import java.util.Collection;
023import java.util.HashMap;
024import java.util.Iterator;
025import java.util.LinkedHashMap;
026import java.util.LinkedList;
027import java.util.List;
028import java.util.Map;
029import java.util.Queue;
030import java.util.Set;
031import java.util.concurrent.ConcurrentLinkedQueue;
032import java.util.concurrent.CopyOnWriteArraySet;
033import java.util.concurrent.Executor;
034import java.util.concurrent.ExecutorService;
035import java.util.concurrent.Executors;
036import java.util.concurrent.ThreadFactory;
037import java.util.concurrent.TimeUnit;
038import java.util.concurrent.atomic.AtomicInteger;
039import java.util.concurrent.locks.Lock;
040import java.util.concurrent.locks.ReentrantLock;
041import java.util.logging.Level;
042import java.util.logging.Logger;
043
044import javax.net.ssl.SSLSession;
045import javax.xml.namespace.QName;
046
047import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
048import org.jivesoftware.smack.SmackConfiguration.UnknownIqRequestReplyMode;
049import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
050import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
051import org.jivesoftware.smack.SmackException.NoResponseException;
052import org.jivesoftware.smack.SmackException.NotConnectedException;
053import org.jivesoftware.smack.SmackException.NotLoggedInException;
054import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
055import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;
056import org.jivesoftware.smack.SmackException.SecurityRequiredException;
057import org.jivesoftware.smack.SmackException.SmackSaslException;
058import org.jivesoftware.smack.SmackException.SmackWrappedException;
059import org.jivesoftware.smack.SmackFuture.InternalSmackFuture;
060import org.jivesoftware.smack.XMPPException.FailedNonzaException;
061import org.jivesoftware.smack.XMPPException.StreamErrorException;
062import org.jivesoftware.smack.XMPPException.XMPPErrorException;
063import org.jivesoftware.smack.compress.packet.Compress;
064import org.jivesoftware.smack.compression.XMPPInputOutputStream;
065import org.jivesoftware.smack.datatypes.UInt16;
066import org.jivesoftware.smack.debugger.SmackDebugger;
067import org.jivesoftware.smack.debugger.SmackDebuggerFactory;
068import org.jivesoftware.smack.filter.IQReplyFilter;
069import org.jivesoftware.smack.filter.StanzaFilter;
070import org.jivesoftware.smack.filter.StanzaIdFilter;
071import org.jivesoftware.smack.internal.SmackTlsContext;
072import org.jivesoftware.smack.iqrequest.IQRequestHandler;
073import org.jivesoftware.smack.packet.Bind;
074import org.jivesoftware.smack.packet.ErrorIQ;
075import org.jivesoftware.smack.packet.ExtensionElement;
076import org.jivesoftware.smack.packet.FullyQualifiedElement;
077import org.jivesoftware.smack.packet.IQ;
078import org.jivesoftware.smack.packet.Mechanisms;
079import org.jivesoftware.smack.packet.Message;
080import org.jivesoftware.smack.packet.MessageBuilder;
081import org.jivesoftware.smack.packet.MessageOrPresence;
082import org.jivesoftware.smack.packet.MessageOrPresenceBuilder;
083import org.jivesoftware.smack.packet.Nonza;
084import org.jivesoftware.smack.packet.Presence;
085import org.jivesoftware.smack.packet.PresenceBuilder;
086import org.jivesoftware.smack.packet.Session;
087import org.jivesoftware.smack.packet.Stanza;
088import org.jivesoftware.smack.packet.StanzaError;
089import org.jivesoftware.smack.packet.StanzaFactory;
090import org.jivesoftware.smack.packet.StartTls;
091import org.jivesoftware.smack.packet.StreamError;
092import org.jivesoftware.smack.packet.StreamOpen;
093import org.jivesoftware.smack.packet.TopLevelStreamElement;
094import org.jivesoftware.smack.packet.XmlEnvironment;
095import org.jivesoftware.smack.packet.id.StanzaIdSource;
096import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
097import org.jivesoftware.smack.parsing.SmackParsingException;
098import org.jivesoftware.smack.provider.ExtensionElementProvider;
099import org.jivesoftware.smack.provider.NonzaProvider;
100import org.jivesoftware.smack.provider.ProviderManager;
101import org.jivesoftware.smack.sasl.SASLErrorException;
102import org.jivesoftware.smack.sasl.SASLMechanism;
103import org.jivesoftware.smack.sasl.core.SASLAnonymous;
104import org.jivesoftware.smack.sasl.packet.SaslNonza;
105import org.jivesoftware.smack.util.Async;
106import org.jivesoftware.smack.util.CollectionUtil;
107import org.jivesoftware.smack.util.Consumer;
108import org.jivesoftware.smack.util.MultiMap;
109import org.jivesoftware.smack.util.Objects;
110import org.jivesoftware.smack.util.PacketParserUtils;
111import org.jivesoftware.smack.util.ParserUtils;
112import org.jivesoftware.smack.util.Predicate;
113import org.jivesoftware.smack.util.StringUtils;
114import org.jivesoftware.smack.util.Supplier;
115import org.jivesoftware.smack.xml.XmlPullParser;
116import org.jivesoftware.smack.xml.XmlPullParserException;
117
118import org.jxmpp.jid.DomainBareJid;
119import org.jxmpp.jid.EntityBareJid;
120import org.jxmpp.jid.EntityFullJid;
121import org.jxmpp.jid.Jid;
122import org.jxmpp.jid.impl.JidCreate;
123import org.jxmpp.jid.parts.Resourcepart;
124import org.jxmpp.stringprep.XmppStringprepException;
125import org.jxmpp.util.XmppStringUtils;
126
127/**
128 * This abstract class is commonly used as super class for XMPP connection mechanisms like TCP and BOSH. Hence it
129 * provides the methods for connection state management, like {@link #connect()}, {@link #login()} and
130 * {@link #disconnect()} (which are deliberately not provided by the {@link XMPPConnection} interface).
131 * <p>
132 * <b>Note:</b> The default entry point to Smack's documentation is {@link XMPPConnection}. If you are getting started
133 * with Smack, then head over to {@link XMPPConnection} and the come back here.
134 * </p>
135 * <h2>Parsing Exceptions</h2>
136 * <p>
137 * In case a Smack parser (Provider) throws those exceptions are handled over to the {@link ParsingExceptionCallback}. A
138 * common cause for a provider throwing is illegal input, for example a non-numeric String where only Integers are
139 * allowed. Smack's <em>default behavior</em> follows the <b>"fail-hard per default"</b> principle leading to a
140 * termination of the connection on parsing exceptions. This default was chosen to make users eventually aware that they
141 * should configure their own callback and handle those exceptions to prevent the disconnect. Handle a parsing exception
142 * could be as simple as using a non-throwing no-op callback, which would cause the faulty stream element to be taken
143 * out of the stream, i.e., Smack behaves like that element was never received.
144 * </p>
145 * <p>
146 * If the parsing exception is because Smack received illegal input, then please consider informing the authors of the
147 * originating entity about that. If it was thrown because of an bug in a Smack parser, then please consider filling a
148 * bug with Smack.
149 * </p>
150 * <h3>Managing the parsing exception callback</h3>
151 * <p>
152 * The "fail-hard per default" behavior is achieved by using the
153 * {@link org.jivesoftware.smack.parsing.ExceptionThrowingCallbackWithHint} as default parsing exception callback. You
154 * can change the behavior using {@link #setParsingExceptionCallback(ParsingExceptionCallback)} to set a new callback.
155 * Use {@link org.jivesoftware.smack.SmackConfiguration#setDefaultParsingExceptionCallback(ParsingExceptionCallback)} to
156 * set the default callback.
157 * </p>
158 */
159public abstract class AbstractXMPPConnection implements XMPPConnection {
160    private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());
161
162    protected static final SmackReactor SMACK_REACTOR;
163
164    static {
165        SMACK_REACTOR = SmackReactor.getInstance();
166    }
167
168    /**
169     * Counter to uniquely identify connections that are created.
170     */
171    private static final AtomicInteger connectionCounter = new AtomicInteger(0);
172
173    static {
174        Smack.ensureInitialized();
175    }
176
177    protected enum SyncPointState {
178        initial,
179        request_sent,
180        successful,
181    }
182
183    /**
184     * A collection of ConnectionListeners which listen for connection closing
185     * and reconnection events.
186     */
187    protected final Set<ConnectionListener> connectionListeners =
188            new CopyOnWriteArraySet<>();
189
190    /**
191     * A collection of StanzaCollectors which collects packets for a specified filter
192     * and perform blocking and polling operations on the result queue.
193     * <p>
194     * We use a ConcurrentLinkedQueue here, because its Iterator is weakly
195     * consistent and we want {@link #invokeStanzaCollectorsAndNotifyRecvListeners(Stanza)} for-each
196     * loop to be lock free. As drawback, removing a StanzaCollector is O(n).
197     * The alternative would be a synchronized HashSet, but this would mean a
198     * synchronized block around every usage of <code>collectors</code>.
199     * </p>
200     */
201    private final Collection<StanzaCollector> collectors = new ConcurrentLinkedQueue<>();
202
203    private final Map<StanzaListener, ListenerWrapper> recvListeners = new LinkedHashMap<>();
204
205    /**
206     * List of PacketListeners that will be notified synchronously when a new stanza was received.
207     */
208    private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();
209
210    /**
211     * List of PacketListeners that will be notified asynchronously when a new stanza was received.
212     */
213    private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();
214
215    /**
216     * List of PacketListeners that will be notified when a new stanza was sent.
217     */
218    private final Map<StanzaListener, ListenerWrapper> sendListeners =
219            new HashMap<>();
220
221    /**
222     * List of PacketListeners that will be notified when a new stanza is about to be
223     * sent to the server. These interceptors may modify the stanza before it is being
224     * actually sent to the server.
225     */
226    private final Map<StanzaListener, InterceptorWrapper> interceptors =
227            new HashMap<>();
228
229    private final Map<Consumer<MessageBuilder>, GenericInterceptorWrapper<MessageBuilder, Message>> messageInterceptors = new HashMap<>();
230
231    private final Map<Consumer<PresenceBuilder>, GenericInterceptorWrapper<PresenceBuilder, Presence>> presenceInterceptors = new HashMap<>();
232
233    private XmlEnvironment incomingStreamXmlEnvironment;
234
235    protected XmlEnvironment outgoingStreamXmlEnvironment;
236
237    final MultiMap<QName, NonzaCallback> nonzaCallbacksMap = new MultiMap<>();
238
239    protected final Lock connectionLock = new ReentrantLock();
240
241    protected final Map<QName, FullyQualifiedElement> streamFeatures = new HashMap<>();
242
243    /**
244     * The full JID of the authenticated user, as returned by the resource binding response of the server.
245     * <p>
246     * It is important that we don't infer the user from the login() arguments and the configurations service name, as,
247     * for example, when SASL External is used, the username is not given to login but taken from the 'external'
248     * certificate.
249     * </p>
250     */
251    protected EntityFullJid user;
252
253    protected boolean connected = false;
254
255    /**
256     * The stream ID, see RFC 6120 § 4.7.3
257     */
258    protected String streamId;
259
260    /**
261     * The timeout to wait for a reply in milliseconds.
262     */
263    private long replyTimeout = SmackConfiguration.getDefaultReplyTimeout();
264
265    /**
266     * The SmackDebugger allows to log and debug XML traffic.
267     */
268    protected final SmackDebugger debugger;
269
270    /**
271     * The Reader which is used for the debugger.
272     */
273    protected Reader reader;
274
275    /**
276     * The Writer which is used for the debugger.
277     */
278    protected Writer writer;
279
280    protected SmackException currentSmackException;
281    protected XMPPException currentXmppException;
282
283    protected boolean tlsHandled;
284
285    /**
286     * Set to <code>true</code> if the last features stanza from the server has been parsed. A XMPP connection
287     * handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
288     * stanza is send by the server. This is set to true once the last feature stanza has been
289     * parsed.
290     */
291    protected boolean lastFeaturesReceived;
292
293    /**
294     * Set to <code>true</code> if the SASL feature has been received.
295     */
296    protected boolean saslFeatureReceived;
297
298    /**
299     * A synchronization point which is successful if this connection has received the closing
300     * stream element from the remote end-point, i.e. the server.
301     */
302    protected boolean closingStreamReceived;
303
304    /**
305     * The SASLAuthentication manager that is responsible for authenticating with the server.
306     */
307    private final SASLAuthentication saslAuthentication;
308
309    /**
310     * A number to uniquely identify connections that are created. This is distinct from the
311     * connection ID, which is a value sent by the server once a connection is made.
312     */
313    protected final int connectionCounterValue = connectionCounter.getAndIncrement();
314
315    /**
316     * Holds the initial configuration used while creating the connection.
317     */
318    protected final ConnectionConfiguration config;
319
320    /**
321     * Defines how the from attribute of outgoing stanzas should be handled.
322     */
323    private FromMode fromMode = FromMode.OMITTED;
324
325    protected XMPPInputOutputStream compressionHandler;
326
327    private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();
328
329    /**
330     * A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
331     * them 'daemon'.
332     */
333    private static final ExecutorService CACHED_EXECUTOR_SERVICE = Executors.newCachedThreadPool(new ThreadFactory() {
334        @Override
335        public Thread newThread(Runnable runnable) {
336            Thread thread = new Thread(runnable);
337            thread.setName("Smack Cached Executor");
338            thread.setDaemon(true);
339            thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
340                @Override
341                public void uncaughtException(Thread t, Throwable e) {
342                    LOGGER.log(Level.WARNING, t + " encountered uncaught exception", e);
343                }
344            });
345            return thread;
346        }
347    });
348
349    protected static final AsyncButOrdered<AbstractXMPPConnection> ASYNC_BUT_ORDERED = new AsyncButOrdered<>();
350
351    protected final AsyncButOrdered<StanzaListener> inOrderListeners = new AsyncButOrdered<>();
352
353    /**
354     * The used host to establish the connection to
355     */
356    protected String host;
357
358    /**
359     * The used port to establish the connection to
360     */
361    protected UInt16 port;
362
363    /**
364     * Flag that indicates if the user is currently authenticated with the server.
365     */
366    protected boolean authenticated = false;
367
368    // TODO: Migrate to ZonedDateTime once Smack's minimum required Android SDK level is 26 (8.0, Oreo) or higher.
369    protected long authenticatedConnectionInitiallyEstablishedTimestamp;
370
371    /**
372     * Flag that indicates if the user was authenticated with the server when the connection
373     * to the server was closed (abruptly or not).
374     */
375    protected boolean wasAuthenticated = false;
376
377    private final Map<QName, IQRequestHandler> setIqRequestHandler = new HashMap<>();
378    private final Map<QName, IQRequestHandler> getIqRequestHandler = new HashMap<>();
379
380    private final StanzaFactory stanzaFactory;
381
382    /**
383     * Create a new XMPPConnection to an XMPP server.
384     *
385     * @param configuration The configuration which is used to establish the connection.
386     */
387    protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
388        saslAuthentication = new SASLAuthentication(this, configuration);
389        config = configuration;
390
391        // Install the SASL Nonza callbacks.
392        buildNonzaCallback()
393            .listenFor(SaslNonza.Challenge.class, c -> {
394                try {
395                    saslAuthentication.challengeReceived(c);
396                } catch (SmackException | InterruptedException e) {
397                    saslAuthentication.authenticationFailed(e);
398                }
399            })
400            .listenFor(SaslNonza.Success.class, s -> {
401                try {
402                    saslAuthentication.authenticated(s);
403                } catch (SmackSaslException | NotConnectedException | InterruptedException e) {
404                    saslAuthentication.authenticationFailed(e);
405                }
406            })
407            .listenFor(SaslNonza.SASLFailure.class, f -> saslAuthentication.authenticationFailed(f))
408            .install();
409
410        SmackDebuggerFactory debuggerFactory = configuration.getDebuggerFactory();
411        if (debuggerFactory != null) {
412            debugger = debuggerFactory.create(this);
413        } else {
414            debugger = null;
415        }
416        // Notify listeners that a new connection has been established
417        for (ConnectionCreationListener listener : XMPPConnectionRegistry.getConnectionCreationListeners()) {
418            listener.connectionCreated(this);
419        }
420
421        StanzaIdSource stanzaIdSource = configuration.constructStanzaIdSource();
422        stanzaFactory = new StanzaFactory(stanzaIdSource);
423    }
424
425    /**
426     * Get the connection configuration used by this connection.
427     *
428     * @return the connection configuration.
429     */
430    public ConnectionConfiguration getConfiguration() {
431        return config;
432    }
433
434    @Override
435    public DomainBareJid getXMPPServiceDomain() {
436        if (xmppServiceDomain != null) {
437            return xmppServiceDomain;
438        }
439        return config.getXMPPServiceDomain();
440    }
441
442    @Override
443    public String getHost() {
444        return host;
445    }
446
447    @Override
448    public int getPort() {
449        final UInt16 port = this.port;
450        if (port == null) {
451            return -1;
452        }
453
454        return port.intValue();
455    }
456
457    @Override
458    public abstract boolean isSecureConnection();
459
460    protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException;
461
462    @Override
463    public boolean trySendStanza(Stanza stanza) throws NotConnectedException {
464        // Default implementation which falls back to sendStanza() as mentioned in the methods javadoc. May be
465        // overwritten by subclasses.
466        try {
467            sendStanza(stanza);
468        } catch (InterruptedException e) {
469            LOGGER.log(Level.FINER,
470                            "Thread blocked in fallback implementation of trySendStanza(Stanza) was interrupted", e);
471            return false;
472        }
473        return true;
474    }
475
476    @Override
477    public boolean trySendStanza(Stanza stanza, long timeout, TimeUnit unit)
478                    throws NotConnectedException, InterruptedException {
479        // Default implementation which falls back to sendStanza() as mentioned in the methods javadoc. May be
480        // overwritten by subclasses.
481        sendStanza(stanza);
482        return true;
483    }
484
485    @Override
486    public abstract void sendNonza(Nonza element) throws NotConnectedException, InterruptedException;
487
488    @Override
489    public abstract boolean isUsingCompression();
490
491    protected void initState() {
492        currentSmackException = null;
493        currentXmppException = null;
494        saslFeatureReceived = lastFeaturesReceived = tlsHandled = false;
495        // TODO: We do not init closingStreamReceived here, as the integration tests use it to check if we waited for
496        // it.
497    }
498
499    /**
500     * Establishes a connection to the XMPP server. It basically
501     * creates and maintains a connection to the server.
502     * <p>
503     * Listeners will be preserved from a previous connection.
504     * </p>
505     *
506     * @throws XMPPException if an error occurs on the XMPP protocol level.
507     * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
508     * @throws IOException if an I/O error occurred.
509     * @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
510     * @throws InterruptedException if the calling thread was interrupted.
511     */
512    public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException, InterruptedException {
513        // Check if not already connected
514        throwAlreadyConnectedExceptionIfAppropriate();
515
516        // Notify connection listeners that we are trying to connect
517        callConnectionConnectingListener();
518
519        // Reset the connection state
520        initState();
521        closingStreamReceived = false;
522        streamId = null;
523
524        try {
525            // Perform the actual connection to the XMPP service
526            connectInternal();
527
528            // If TLS is required but the server doesn't offer it, disconnect
529            // from the server and throw an error. First check if we've already negotiated TLS
530            // and are secure, however (features get parsed a second time after TLS is established).
531            if (!isSecureConnection() && getConfiguration().getSecurityMode() == SecurityMode.required) {
532                throw new SecurityRequiredByClientException();
533            }
534        } catch (SmackException | IOException | XMPPException | InterruptedException e) {
535            instantShutdown();
536            throw e;
537        }
538
539        // If connectInternal() did not throw, then this connection must now be marked as connected.
540        assert connected;
541
542        callConnectionConnectedListener();
543
544        return this;
545    }
546
547    /**
548     * Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
549     * way of XMPP connection establishment. Implementations are required to perform an automatic
550     * login if the previous connection state was logged (authenticated).
551     *
552     * @throws SmackException if Smack detected an exceptional situation.
553     * @throws IOException if an I/O error occurred.
554     * @throws XMPPException if an XMPP protocol error was received.
555     * @throws InterruptedException if the calling thread was interrupted.
556     */
557    protected abstract void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException;
558
559    private String usedUsername, usedPassword;
560
561    /**
562     * The resourcepart used for this connection. May not be the resulting resourcepart if it's null or overridden by the XMPP service.
563     */
564    private Resourcepart usedResource;
565
566    /**
567     * Logs in to the server using the strongest SASL mechanism supported by
568     * the server. If more than the connection's default stanza timeout elapses in each step of the
569     * authentication process without a response from the server, a
570     * {@link SmackException.NoResponseException} will be thrown.
571     * <p>
572     * Before logging in (i.e. authenticate) to the server the connection must be connected
573     * by calling {@link #connect}.
574     * </p>
575     * <p>
576     * It is possible to log in without sending an initial available presence by using
577     * {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
578     * Finally, if you want to not pass a password and instead use a more advanced mechanism
579     * while using SASL then you may be interested in using
580     * {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
581     * For more advanced login settings see {@link ConnectionConfiguration}.
582     * </p>
583     *
584     * @throws XMPPException if an error occurs on the XMPP protocol level.
585     * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
586     * @throws IOException if an I/O error occurs during login.
587     * @throws InterruptedException if the calling thread was interrupted.
588     */
589    public synchronized void login() throws XMPPException, SmackException, IOException, InterruptedException {
590        // The previously used username, password and resource take over precedence over the
591        // ones from the connection configuration
592        CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
593        String password = usedPassword != null ? usedPassword : config.getPassword();
594        Resourcepart resource = usedResource != null ? usedResource : config.getResource();
595        login(username, password, resource);
596    }
597
598    /**
599     * Same as {@link #login(CharSequence, String, Resourcepart)}, but takes the resource from the connection
600     * configuration.
601     *
602     * @param username TODO javadoc me please
603     * @param password TODO javadoc me please
604     * @throws XMPPException if an XMPP protocol error was received.
605     * @throws SmackException if Smack detected an exceptional situation.
606     * @throws IOException if an I/O error occurred.
607     * @throws InterruptedException if the calling thread was interrupted.
608     * @see #login
609     */
610    public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
611                    IOException, InterruptedException {
612        login(username, password, config.getResource());
613    }
614
615    /**
616     * Login with the given username (authorization identity). You may omit the password if a callback handler is used.
617     * If resource is null, then the server will generate one.
618     *
619     * @param username TODO javadoc me please
620     * @param password TODO javadoc me please
621     * @param resource TODO javadoc me please
622     * @throws XMPPException if an XMPP protocol error was received.
623     * @throws SmackException if Smack detected an exceptional situation.
624     * @throws IOException if an I/O error occurred.
625     * @throws InterruptedException if the calling thread was interrupted.
626     * @see #login
627     */
628    public synchronized void login(CharSequence username, String password, Resourcepart resource) throws XMPPException,
629                    SmackException, IOException, InterruptedException {
630        if (!config.allowNullOrEmptyUsername) {
631            StringUtils.requireNotNullNorEmpty(username, "Username must not be null nor empty");
632        }
633        throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?");
634        throwAlreadyLoggedInExceptionIfAppropriate();
635        usedUsername = username != null ? username.toString() : null;
636        usedPassword = password;
637        usedResource = resource;
638        loginInternal(usedUsername, usedPassword, usedResource);
639    }
640
641    protected abstract void loginInternal(String username, String password, Resourcepart resource)
642                    throws XMPPException, SmackException, IOException, InterruptedException;
643
644    @Override
645    public final boolean isConnected() {
646        return connected;
647    }
648
649    @Override
650    public final boolean isAuthenticated() {
651        return authenticated;
652    }
653
654    @Override
655    public final EntityFullJid getUser() {
656        return user;
657    }
658
659    @Override
660    public String getStreamId() {
661        if (!isConnected()) {
662            return null;
663        }
664        return streamId;
665    }
666
667    protected final void throwCurrentConnectionException() throws SmackException, XMPPException {
668        if (currentSmackException != null) {
669            throw currentSmackException;
670        } else if (currentXmppException != null) {
671            throw currentXmppException;
672        }
673
674        throw new AssertionError("No current connection exception set, although throwCurrentException() was called");
675    }
676
677    protected final boolean hasCurrentConnectionException() {
678        return currentSmackException != null || currentXmppException != null;
679    }
680
681    protected final void setCurrentConnectionExceptionAndNotify(Exception exception) {
682        if (exception instanceof SmackException) {
683            currentSmackException = (SmackException) exception;
684        } else if (exception instanceof XMPPException) {
685            currentXmppException = (XMPPException) exception;
686        } else {
687            currentSmackException = new SmackException.SmackWrappedException(exception);
688        }
689
690        notifyWaitingThreads();
691    }
692
693    /**
694     * We use an extra object for {@link #notifyWaitingThreads()} and {@link #waitForConditionOrConnectionException(Supplier)}, because all state
695     * changing methods of the connection are synchronized using the connection instance as monitor. If we now would
696     * also use the connection instance for the internal process to wait for a condition, the {@link Object#wait()}
697     * would leave the monitor when it waites, which would allow for another potential call to a state changing function
698     * to proceed.
699     */
700    private final Object internalMonitor = new Object();
701
702    protected final void notifyWaitingThreads() {
703        synchronized (internalMonitor) {
704            internalMonitor.notifyAll();
705        }
706    }
707
708    protected final boolean waitFor(Supplier<Boolean> condition) throws InterruptedException {
709        final long deadline = System.currentTimeMillis() + getReplyTimeout();
710        synchronized (internalMonitor) {
711            while (!condition.get().booleanValue()) {
712                final long now = System.currentTimeMillis();
713                if (now >= deadline) {
714                    return false;
715                }
716                internalMonitor.wait(deadline - now);
717            }
718        }
719        return true;
720    }
721
722    protected final boolean waitForConditionOrConnectionException(Supplier<Boolean> condition) throws InterruptedException {
723        return waitFor(() -> condition.get().booleanValue() || hasCurrentConnectionException());
724    }
725
726    protected final void waitForConditionOrConnectionException(Supplier<Boolean> condition, String waitFor) throws InterruptedException, NoResponseException {
727        boolean success = waitForConditionOrConnectionException(condition);
728        if (!success) {
729            throw NoResponseException.newWith(this, waitFor);
730        }
731    }
732
733    protected final void waitForConditionOrThrowConnectionException(Supplier<Boolean> condition, String waitFor) throws InterruptedException, SmackException, XMPPException {
734        waitForConditionOrConnectionException(condition, waitFor);
735        if (hasCurrentConnectionException()) {
736            throwCurrentConnectionException();
737        }
738    }
739
740    protected Resourcepart bindResourceAndEstablishSession(Resourcepart resource)
741                    throws SmackException, InterruptedException, XMPPException {
742        // Wait until either:
743        // - the servers last features stanza has been parsed
744        // - the timeout occurs
745        LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
746        waitForConditionOrThrowConnectionException(() -> lastFeaturesReceived, "last stream features received from server");
747
748        if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
749            // Server never offered resource binding, which is REQUIRED in XMPP client and
750            // server implementations as per RFC6120 7.2
751            throw new ResourceBindingNotOfferedException();
752        }
753
754        // Resource binding, see RFC6120 7.
755        // Note that we can not use IQReplyFilter here, since the users full JID is not yet
756        // available. It will become available right after the resource has been successfully bound.
757        Bind bindResource = Bind.newSet(resource);
758        StanzaCollector packetCollector = createStanzaCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
759        Bind response = packetCollector.nextResultOrThrow();
760        // Set the connections user to the result of resource binding. It is important that we don't infer the user
761        // from the login() arguments and the configurations service name, as, for example, when SASL External is used,
762        // the username is not given to login but taken from the 'external' certificate.
763        user = response.getJid();
764        xmppServiceDomain = user.asDomainBareJid();
765
766        Session.Feature sessionFeature = getFeature(Session.Feature.class);
767        // Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
768        // For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
769        if (sessionFeature != null && !sessionFeature.isOptional()) {
770            Session session = new Session();
771            packetCollector = createStanzaCollectorAndSend(new StanzaIdFilter(session), session);
772            packetCollector.nextResultOrThrow();
773        }
774
775        return response.getJid().getResourcepart();
776    }
777
778    protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException, InterruptedException {
779        if (!resumed) {
780            authenticatedConnectionInitiallyEstablishedTimestamp = System.currentTimeMillis();
781        }
782        // Indicate that we're now authenticated.
783        this.authenticated = true;
784
785        // If debugging is enabled, change the the debug window title to include the
786        // name we are now logged-in as.
787        // If DEBUG was set to true AFTER the connection was created the debugger
788        // will be null
789        if (debugger != null) {
790            debugger.userHasLogged(user);
791        }
792        callConnectionAuthenticatedListener(resumed);
793
794        // Set presence to online. It is important that this is done after
795        // callConnectionAuthenticatedListener(), as this call will also
796        // eventually load the roster. And we should load the roster before we
797        // send the initial presence.
798        if (config.isSendPresence() && !resumed) {
799            Presence availablePresence = getStanzaFactory()
800                            .buildPresenceStanza()
801                            .ofType(Presence.Type.available)
802                            .build();
803            sendStanza(availablePresence);
804        }
805    }
806
807    @Override
808    public final boolean isAnonymous() {
809        return isAuthenticated() && SASLAnonymous.NAME.equals(getUsedSaslMechansism());
810    }
811
812    /**
813     * Get the name of the SASL mechanism that was used to authenticate this connection. This returns the name of
814     * mechanism which was used the last time this connection was authenticated, and will return <code>null</code> if
815     * this connection was not authenticated before.
816     *
817     * @return the name of the used SASL mechanism.
818     * @since 4.2
819     */
820    public final String getUsedSaslMechansism() {
821        return saslAuthentication.getNameOfLastUsedSaslMechansism();
822    }
823
824    private DomainBareJid xmppServiceDomain;
825
826    protected Lock getConnectionLock() {
827        return connectionLock;
828    }
829
830    protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
831        throwNotConnectedExceptionIfAppropriate(null);
832    }
833
834    protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException {
835        if (!isConnected()) {
836            throw new NotConnectedException(optionalHint);
837        }
838    }
839
840    protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
841        if (isConnected()) {
842            throw new AlreadyConnectedException();
843        }
844    }
845
846    protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
847        if (isAuthenticated()) {
848            throw new AlreadyLoggedInException();
849        }
850    }
851
852    @Override
853    public final StanzaFactory getStanzaFactory() {
854        return stanzaFactory;
855    }
856
857    @Override
858    public final void sendStanza(Stanza stanza) throws NotConnectedException, InterruptedException {
859        Objects.requireNonNull(stanza, "Stanza must not be null");
860        assert stanza instanceof Message || stanza instanceof Presence || stanza instanceof IQ;
861
862        throwNotConnectedExceptionIfAppropriate();
863        switch (fromMode) {
864        case OMITTED:
865            stanza.setFrom((Jid) null);
866            break;
867        case USER:
868            stanza.setFrom(getUser());
869            break;
870        case UNCHANGED:
871        default:
872            break;
873        }
874        // Invoke interceptors for the new stanza that is about to be sent. Interceptors may modify
875        // the content of the stanza.
876        Stanza stanzaAfterInterceptors = firePacketInterceptors(stanza);
877        sendStanzaInternal(stanzaAfterInterceptors);
878    }
879
880    /**
881     * Authenticate a connection.
882     *
883     * @param username the username that is authenticating with the server.
884     * @param password the password to send to the server.
885     * @param authzid the authorization identifier (typically null).
886     * @param sslSession the optional SSL/TLS session (if one was established)
887     * @return the used SASLMechanism.
888     * @throws XMPPErrorException if there was an XMPP error returned.
889     * @throws SASLErrorException if a SASL protocol error was returned.
890     * @throws IOException if an I/O error occurred.
891     * @throws InterruptedException if the calling thread was interrupted.
892     * @throws SmackSaslException if a SASL specific error occurred.
893     * @throws NotConnectedException if the XMPP connection is not connected.
894     * @throws NoResponseException if there was no response from the remote entity.
895     * @throws SmackWrappedException in case of an exception.
896     * @see SASLAuthentication#authenticate(String, String, EntityBareJid, SSLSession)
897     */
898    protected final SASLMechanism authenticate(String username, String password, EntityBareJid authzid,
899                    SSLSession sslSession) throws XMPPErrorException, SASLErrorException, SmackSaslException,
900                    NotConnectedException, NoResponseException, IOException, InterruptedException, SmackWrappedException {
901        SASLMechanism saslMechanism = saslAuthentication.authenticate(username, password, authzid, sslSession);
902        afterSaslAuthenticationSuccess();
903        return saslMechanism;
904    }
905
906    /**
907     * Hook for subclasses right after successful SASL authentication. RFC 6120 § 6.4.6. specifies a that the initiating
908     * entity, needs to initiate a new stream in this case. But some transports, like BOSH, requires a special handling.
909     * <p>
910     * Note that we can not reset XMPPTCPConnection's parser here, because this method is invoked by the thread calling
911     * {@link #login()}, but the parser reset has to be done within the reader thread.
912     * </p>
913     *
914     * @throws NotConnectedException if the XMPP connection is not connected.
915     * @throws InterruptedException if the calling thread was interrupted.
916     * @throws SmackWrappedException in case of an exception.
917     */
918    protected void afterSaslAuthenticationSuccess()
919                    throws NotConnectedException, InterruptedException, SmackWrappedException {
920        sendStreamOpen();
921    }
922
923    protected final boolean isSaslAuthenticated() {
924        return saslAuthentication.authenticationSuccessful();
925    }
926
927    /**
928     * Closes the connection by setting presence to unavailable then closing the connection to
929     * the XMPP server. The XMPPConnection can still be used for connecting to the server
930     * again.
931     *
932     */
933    public void disconnect() {
934        Presence unavailablePresence = null;
935        if (isAuthenticated()) {
936            unavailablePresence = getStanzaFactory().buildPresenceStanza()
937                            .ofType(Presence.Type.unavailable)
938                            .build();
939        }
940        try {
941            disconnect(unavailablePresence);
942        }
943        catch (NotConnectedException e) {
944            LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
945        }
946    }
947
948    /**
949     * Closes the connection. A custom unavailable presence is sent to the server, followed
950     * by closing the stream. The XMPPConnection can still be used for connecting to the server
951     * again. A custom unavailable presence is useful for communicating offline presence
952     * information such as "On vacation". Typically, just the status text of the presence
953     * stanza is set with online information, but most XMPP servers will deliver the full
954     * presence stanza with whatever data is set.
955     *
956     * @param unavailablePresence the optional presence stanza to send during shutdown.
957     * @throws NotConnectedException if the XMPP connection is not connected.
958     */
959    public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
960        if (unavailablePresence != null) {
961            try {
962                sendStanza(unavailablePresence);
963            } catch (InterruptedException e) {
964                LOGGER.log(Level.FINE,
965                        "Was interrupted while sending unavailable presence. Continuing to disconnect the connection",
966                        e);
967            }
968        }
969        shutdown();
970        callConnectionClosedListener();
971    }
972
973    private final Object notifyConnectionErrorMonitor = new Object();
974
975    /**
976     * Sends out a notification that there was an error with the connection
977     * and closes the connection.
978     *
979     * @param exception the exception that causes the connection close event.
980     */
981    protected final void notifyConnectionError(final Exception exception) {
982        synchronized (notifyConnectionErrorMonitor) {
983            if (!isConnected()) {
984                LOGGER.log(Level.INFO, "Connection was already disconnected when attempting to handle " + exception,
985                                exception);
986                return;
987            }
988
989            // Note that we first have to set the current connection exception and notify waiting threads, as one of them
990            // could hold the instance lock, which we also need later when calling instantShutdown().
991            setCurrentConnectionExceptionAndNotify(exception);
992
993            // Closes the connection temporary. A if the connection supports stream management, then a reconnection is
994            // possible. Note that a connection listener of e.g. XMPPTCPConnection will drop the SM state in
995            // case the Exception is a StreamErrorException.
996            instantShutdown();
997
998            for (StanzaCollector collector : collectors) {
999                collector.notifyConnectionError(exception);
1000            }
1001
1002            Async.go(() -> {
1003                // Notify connection listeners of the error.
1004                callConnectionClosedOnErrorListener(exception);
1005            }, AbstractXMPPConnection.this + " callConnectionClosedOnErrorListener()");
1006        }
1007    }
1008
1009    /**
1010     * Performs an unclean disconnect and shutdown of the connection. Does not send a closing stream stanza.
1011     */
1012    public abstract void instantShutdown();
1013
1014    /**
1015     * Shuts the current connection down.
1016     */
1017    protected abstract void shutdown();
1018
1019    protected final boolean waitForClosingStreamTagFromServer() {
1020        try {
1021            waitForConditionOrThrowConnectionException(() -> closingStreamReceived, "closing stream tag from the server");
1022        } catch (InterruptedException | SmackException | XMPPException e) {
1023            LOGGER.log(Level.INFO, "Exception while waiting for closing stream element from the server " + this, e);
1024            return false;
1025        }
1026        return true;
1027    }
1028
1029    @Override
1030    public void addConnectionListener(ConnectionListener connectionListener) {
1031        if (connectionListener == null) {
1032            return;
1033        }
1034        connectionListeners.add(connectionListener);
1035    }
1036
1037    @Override
1038    public void removeConnectionListener(ConnectionListener connectionListener) {
1039        connectionListeners.remove(connectionListener);
1040    }
1041
1042    @Override
1043    public <I extends IQ> I sendIqRequestAndWaitForResponse(IQ request)
1044            throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1045        StanzaCollector collector = createStanzaCollectorAndSend(request);
1046        IQ resultResponse = collector.nextResultOrThrow();
1047        @SuppressWarnings("unchecked")
1048        I concreteResultResponse = (I) resultResponse;
1049        return concreteResultResponse;
1050    }
1051
1052    @Override
1053    public StanzaCollector createStanzaCollectorAndSend(IQ packet) throws NotConnectedException, InterruptedException {
1054        StanzaFilter packetFilter = new IQReplyFilter(packet, this);
1055        // Create the packet collector before sending the packet
1056        StanzaCollector packetCollector = createStanzaCollectorAndSend(packetFilter, packet);
1057        return packetCollector;
1058    }
1059
1060    @Override
1061    public StanzaCollector createStanzaCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
1062                    throws NotConnectedException, InterruptedException {
1063        StanzaCollector.Configuration configuration = StanzaCollector.newConfiguration()
1064                        .setStanzaFilter(packetFilter)
1065                        .setRequest(packet);
1066        // Create the packet collector before sending the packet
1067        StanzaCollector packetCollector = createStanzaCollector(configuration);
1068        try {
1069            // Now we can send the packet as the collector has been created
1070            sendStanza(packet);
1071        }
1072        catch (InterruptedException | NotConnectedException | RuntimeException e) {
1073            packetCollector.cancel();
1074            throw e;
1075        }
1076        return packetCollector;
1077    }
1078
1079    @Override
1080    public StanzaCollector createStanzaCollector(StanzaFilter packetFilter) {
1081        StanzaCollector.Configuration configuration = StanzaCollector.newConfiguration().setStanzaFilter(packetFilter);
1082        return createStanzaCollector(configuration);
1083    }
1084
1085    @Override
1086    public StanzaCollector createStanzaCollector(StanzaCollector.Configuration configuration) {
1087        StanzaCollector collector = new StanzaCollector(this, configuration);
1088        // Add the collector to the list of active collectors.
1089        collectors.add(collector);
1090        return collector;
1091    }
1092
1093    @Override
1094    public void removeStanzaCollector(StanzaCollector collector) {
1095        collectors.remove(collector);
1096    }
1097
1098    @Override
1099    public final void addStanzaListener(StanzaListener stanzaListener, StanzaFilter stanzaFilter) {
1100        if (stanzaListener == null) {
1101            throw new NullPointerException("Given stanza listener must not be null");
1102        }
1103        ListenerWrapper wrapper = new ListenerWrapper(stanzaListener, stanzaFilter);
1104        synchronized (recvListeners) {
1105            recvListeners.put(stanzaListener, wrapper);
1106        }
1107    }
1108
1109    @Override
1110    public final boolean removeStanzaListener(StanzaListener stanzaListener) {
1111        synchronized (recvListeners) {
1112            return recvListeners.remove(stanzaListener) != null;
1113        }
1114    }
1115
1116    @Override
1117    public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
1118        if (packetListener == null) {
1119            throw new NullPointerException("Packet listener is null.");
1120        }
1121        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
1122        synchronized (syncRecvListeners) {
1123            syncRecvListeners.put(packetListener, wrapper);
1124        }
1125    }
1126
1127    @Override
1128    public boolean removeSyncStanzaListener(StanzaListener packetListener) {
1129        synchronized (syncRecvListeners) {
1130            return syncRecvListeners.remove(packetListener) != null;
1131        }
1132    }
1133
1134    @Override
1135    public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
1136        if (packetListener == null) {
1137            throw new NullPointerException("Packet listener is null.");
1138        }
1139        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
1140        synchronized (asyncRecvListeners) {
1141            asyncRecvListeners.put(packetListener, wrapper);
1142        }
1143    }
1144
1145    @Override
1146    public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
1147        synchronized (asyncRecvListeners) {
1148            return asyncRecvListeners.remove(packetListener) != null;
1149        }
1150    }
1151
1152    @Override
1153    public void addStanzaSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
1154        if (packetListener == null) {
1155            throw new NullPointerException("Packet listener is null.");
1156        }
1157        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
1158        synchronized (sendListeners) {
1159            sendListeners.put(packetListener, wrapper);
1160        }
1161    }
1162
1163    @Override
1164    public void removeStanzaSendingListener(StanzaListener packetListener) {
1165        synchronized (sendListeners) {
1166            sendListeners.remove(packetListener);
1167        }
1168    }
1169
1170    /**
1171     * Process all stanza listeners for sending stanzas.
1172     * <p>
1173     * Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
1174     * </p>
1175     *
1176     * @param sendTopLevelStreamElement the top level stream element which just got send.
1177     */
1178    // TODO: Rename to fireElementSendingListeners().
1179    @SuppressWarnings("javadoc")
1180    protected void firePacketSendingListeners(final TopLevelStreamElement sendTopLevelStreamElement) {
1181        if (debugger != null) {
1182            debugger.onOutgoingStreamElement(sendTopLevelStreamElement);
1183        }
1184
1185        if (!(sendTopLevelStreamElement instanceof Stanza)) {
1186            return;
1187        }
1188        Stanza packet = (Stanza) sendTopLevelStreamElement;
1189
1190        final List<StanzaListener> listenersToNotify = new LinkedList<>();
1191        synchronized (sendListeners) {
1192            for (ListenerWrapper listenerWrapper : sendListeners.values()) {
1193                if (listenerWrapper.filterMatches(packet)) {
1194                    listenersToNotify.add(listenerWrapper.getListener());
1195                }
1196            }
1197        }
1198        if (listenersToNotify.isEmpty()) {
1199            return;
1200        }
1201        // Notify in a new thread, because we can
1202        asyncGo(new Runnable() {
1203            @Override
1204            public void run() {
1205                for (StanzaListener listener : listenersToNotify) {
1206                    try {
1207                        listener.processStanza(packet);
1208                    }
1209                    catch (Exception e) {
1210                        LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
1211                        continue;
1212                    }
1213                }
1214            }
1215        });
1216    }
1217
1218    @Deprecated
1219    @Override
1220    public void addStanzaInterceptor(StanzaListener packetInterceptor,
1221            StanzaFilter packetFilter) {
1222        if (packetInterceptor == null) {
1223            throw new NullPointerException("Packet interceptor is null.");
1224        }
1225        InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
1226        synchronized (interceptors) {
1227            interceptors.put(packetInterceptor, interceptorWrapper);
1228        }
1229    }
1230
1231    @Deprecated
1232    @Override
1233    public void removeStanzaInterceptor(StanzaListener packetInterceptor) {
1234        synchronized (interceptors) {
1235            interceptors.remove(packetInterceptor);
1236        }
1237    }
1238
1239    private static <MPB extends MessageOrPresenceBuilder<MP, MPB>, MP extends MessageOrPresence<MPB>> void addInterceptor(
1240                    Map<Consumer<MPB>, GenericInterceptorWrapper<MPB, MP>> interceptors, Consumer<MPB> interceptor,
1241                    Predicate<MP> filter) {
1242        Objects.requireNonNull(interceptor, "Interceptor must not be null");
1243
1244        GenericInterceptorWrapper<MPB, MP> interceptorWrapper = new GenericInterceptorWrapper<>(interceptor, filter);
1245
1246        synchronized (interceptors) {
1247            interceptors.put(interceptor, interceptorWrapper);
1248        }
1249    }
1250
1251    private static <MPB extends MessageOrPresenceBuilder<MP, MPB>, MP extends MessageOrPresence<MPB>> void removeInterceptor(
1252                    Map<Consumer<MPB>, GenericInterceptorWrapper<MPB, MP>> interceptors, Consumer<MPB> interceptor) {
1253        synchronized (interceptors) {
1254            interceptors.remove(interceptor);
1255        }
1256    }
1257
1258    @Override
1259    public void addMessageInterceptor(Consumer<MessageBuilder> messageInterceptor, Predicate<Message> messageFilter) {
1260        addInterceptor(messageInterceptors, messageInterceptor, messageFilter);
1261    }
1262
1263    @Override
1264    public void removeMessageInterceptor(Consumer<MessageBuilder> messageInterceptor) {
1265        removeInterceptor(messageInterceptors, messageInterceptor);
1266    }
1267
1268    @Override
1269    public void addPresenceInterceptor(Consumer<PresenceBuilder> presenceInterceptor,
1270                    Predicate<Presence> presenceFilter) {
1271        addInterceptor(presenceInterceptors, presenceInterceptor, presenceFilter);
1272    }
1273
1274    @Override
1275    public void removePresenceInterceptor(Consumer<PresenceBuilder> presenceInterceptor) {
1276        removeInterceptor(presenceInterceptors, presenceInterceptor);
1277    }
1278
1279    private static <MPB extends MessageOrPresenceBuilder<MP, MPB>, MP extends MessageOrPresence<MPB>> MP fireMessageOrPresenceInterceptors(
1280                    MP messageOrPresence, Map<Consumer<MPB>, GenericInterceptorWrapper<MPB, MP>> interceptors) {
1281        List<Consumer<MPB>> interceptorsToInvoke = new LinkedList<>();
1282        synchronized (interceptors) {
1283            for (GenericInterceptorWrapper<MPB, MP> interceptorWrapper : interceptors.values()) {
1284                if (interceptorWrapper.filterMatches(messageOrPresence)) {
1285                    Consumer<MPB> interceptor = interceptorWrapper.getInterceptor();
1286                    interceptorsToInvoke.add(interceptor);
1287                }
1288            }
1289        }
1290
1291        // Avoid transforming the stanza to a builder if there is no interceptor.
1292        if (interceptorsToInvoke.isEmpty()) {
1293            return messageOrPresence;
1294        }
1295
1296        MPB builder = messageOrPresence.asBuilder();
1297        for (Consumer<MPB> interceptor : interceptorsToInvoke) {
1298            interceptor.accept(builder);
1299        }
1300
1301        // Now that the interceptors have (probably) modified the stanza in its builder form, we need to re-assemble it.
1302        messageOrPresence = builder.build();
1303        return messageOrPresence;
1304    }
1305
1306    /**
1307     * Process interceptors. Interceptors may modify the stanza that is about to be sent.
1308     * Since the thread that requested to send the stanza will invoke all interceptors, it
1309     * is important that interceptors perform their work as soon as possible so that the
1310     * thread does not remain blocked for a long period.
1311     *
1312     * @param packet the stanza that is going to be sent to the server.
1313     * @return the, potentially modified stanza, after the interceptors are run.
1314     */
1315    private Stanza firePacketInterceptors(Stanza packet) {
1316        List<StanzaListener> interceptorsToInvoke = new LinkedList<>();
1317        synchronized (interceptors) {
1318            for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
1319                if (interceptorWrapper.filterMatches(packet)) {
1320                    interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
1321                }
1322            }
1323        }
1324        for (StanzaListener interceptor : interceptorsToInvoke) {
1325            try {
1326                interceptor.processStanza(packet);
1327            } catch (Exception e) {
1328                LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
1329            }
1330        }
1331
1332        final Stanza stanzaAfterInterceptors;
1333        if (packet instanceof Message) {
1334            Message message = (Message) packet;
1335            stanzaAfterInterceptors = fireMessageOrPresenceInterceptors(message, messageInterceptors);
1336        }
1337        else if (packet instanceof Presence) {
1338            Presence presence = (Presence) packet;
1339            stanzaAfterInterceptors = fireMessageOrPresenceInterceptors(presence, presenceInterceptors);
1340        } else {
1341            // We do not (yet) support interceptors for IQ stanzas.
1342            assert packet instanceof IQ;
1343            stanzaAfterInterceptors = packet;
1344        }
1345
1346        return stanzaAfterInterceptors;
1347    }
1348
1349    /**
1350     * Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
1351     * by setup the system property <code>smack.debuggerClass</code> to the implementation.
1352     *
1353     * @throws IllegalStateException if the reader or writer isn't yet initialized.
1354     * @throws IllegalArgumentException if the SmackDebugger can't be loaded.
1355     */
1356    protected void initDebugger() {
1357        if (reader == null || writer == null) {
1358            throw new NullPointerException("Reader or writer isn't initialized.");
1359        }
1360        // If debugging is enabled, we open a window and write out all network traffic.
1361        if (debugger != null) {
1362            // Obtain new reader and writer from the existing debugger
1363            reader = debugger.newConnectionReader(reader);
1364            writer = debugger.newConnectionWriter(writer);
1365        }
1366    }
1367
1368    @Override
1369    public long getReplyTimeout() {
1370        return replyTimeout;
1371    }
1372
1373    @Override
1374    public void setReplyTimeout(long timeout) {
1375        if (Long.MAX_VALUE - System.currentTimeMillis() < timeout) {
1376            throw new IllegalArgumentException("Extremely long reply timeout");
1377        }
1378        else {
1379            replyTimeout = timeout;
1380        }
1381    }
1382
1383    private SmackConfiguration.UnknownIqRequestReplyMode unknownIqRequestReplyMode = SmackConfiguration.getUnknownIqRequestReplyMode();
1384
1385    /**
1386     * Set how Smack behaves when an unknown IQ request has been received.
1387     *
1388     * @param unknownIqRequestReplyMode reply mode.
1389     */
1390    public void setUnknownIqRequestReplyMode(UnknownIqRequestReplyMode unknownIqRequestReplyMode) {
1391        this.unknownIqRequestReplyMode = Objects.requireNonNull(unknownIqRequestReplyMode, "Mode must not be null");
1392    }
1393
1394    protected final NonzaCallback.Builder buildNonzaCallback() {
1395        return new NonzaCallback.Builder(this);
1396    }
1397
1398    protected <SN extends Nonza, FN extends Nonza> SN sendAndWaitForResponse(Nonza nonza, Class<SN> successNonzaClass,
1399                    Class<FN> failedNonzaClass)
1400                    throws NoResponseException, NotConnectedException, InterruptedException, FailedNonzaException {
1401        NonzaCallback.Builder builder = buildNonzaCallback();
1402        SN successNonza = NonzaCallback.sendAndWaitForResponse(builder, nonza, successNonzaClass, failedNonzaClass);
1403        return successNonza;
1404    }
1405
1406    private void maybeNotifyDebuggerAboutIncoming(TopLevelStreamElement incomingTopLevelStreamElement) {
1407        final SmackDebugger debugger = this.debugger;
1408        if (debugger != null) {
1409            debugger.onIncomingStreamElement(incomingTopLevelStreamElement);
1410        }
1411    }
1412
1413    protected final void parseAndProcessNonza(XmlPullParser parser) throws IOException, XmlPullParserException, SmackParsingException {
1414        ParserUtils.assertAtStartTag(parser);
1415
1416        final int initialDepth = parser.getDepth();
1417        final String element = parser.getName();
1418        final String namespace = parser.getNamespace();
1419        final QName key = new QName(namespace, element);
1420
1421        NonzaProvider<? extends Nonza> nonzaProvider = ProviderManager.getNonzaProvider(key);
1422        if (nonzaProvider == null) {
1423            LOGGER.severe("Unknown nonza: " + key);
1424            ParserUtils.forwardToEndTagOfDepth(parser, initialDepth);
1425            return;
1426        }
1427
1428        List<NonzaCallback> nonzaCallbacks;
1429        synchronized (nonzaCallbacksMap) {
1430            nonzaCallbacks = nonzaCallbacksMap.getAll(key);
1431            nonzaCallbacks = CollectionUtil.newListWith(nonzaCallbacks);
1432        }
1433        if (nonzaCallbacks == null) {
1434            LOGGER.info("No nonza callback for " + key);
1435            ParserUtils.forwardToEndTagOfDepth(parser, initialDepth);
1436            return;
1437        }
1438
1439        Nonza nonza = nonzaProvider.parse(parser, incomingStreamXmlEnvironment);
1440
1441        maybeNotifyDebuggerAboutIncoming(nonza);
1442
1443        for (NonzaCallback nonzaCallback : nonzaCallbacks) {
1444            nonzaCallback.onNonzaReceived(nonza);
1445        }
1446    }
1447
1448    protected void parseAndProcessStanza(XmlPullParser parser)
1449                    throws XmlPullParserException, IOException, InterruptedException {
1450        ParserUtils.assertAtStartTag(parser);
1451        int parserDepth = parser.getDepth();
1452        Stanza stanza = null;
1453        try {
1454            stanza = PacketParserUtils.parseStanza(parser, incomingStreamXmlEnvironment);
1455        }
1456        catch (XmlPullParserException | SmackParsingException | IOException | IllegalArgumentException e) {
1457            CharSequence content = PacketParserUtils.parseContentDepth(parser,
1458                            parserDepth);
1459            UnparseableStanza message = new UnparseableStanza(content, e);
1460            ParsingExceptionCallback callback = getParsingExceptionCallback();
1461            if (callback != null) {
1462                callback.handleUnparsableStanza(message);
1463            }
1464        }
1465        ParserUtils.assertAtEndTag(parser);
1466        if (stanza != null) {
1467            processStanza(stanza);
1468        }
1469    }
1470
1471    /**
1472     * Processes a stanza after it's been fully parsed by looping through the installed
1473     * stanza collectors and listeners and letting them examine the stanza to see if
1474     * they are a match with the filter.
1475     *
1476     * @param stanza the stanza to process.
1477     * @throws InterruptedException if the calling thread was interrupted.
1478     */
1479    protected void processStanza(final Stanza stanza) throws InterruptedException {
1480        assert stanza != null;
1481
1482        maybeNotifyDebuggerAboutIncoming(stanza);
1483
1484        lastStanzaReceived = System.currentTimeMillis();
1485        // Deliver the incoming packet to listeners.
1486        invokeStanzaCollectorsAndNotifyRecvListeners(stanza);
1487    }
1488
1489    /**
1490     * Invoke {@link StanzaCollector#processStanza(Stanza)} for every
1491     * StanzaCollector with the given packet. Also notify the receive listeners with a matching stanza filter about the packet.
1492     * <p>
1493     * This method will be invoked by the connections incoming processing thread which may be shared across multiple connections and
1494     * thus it is important that no user code, e.g. in form of a callback, is invoked by this method. For the same reason,
1495     * this method must not block for an extended period of time.
1496     * </p>
1497     *
1498     * @param packet the stanza to notify the StanzaCollectors and receive listeners about.
1499     */
1500    protected void invokeStanzaCollectorsAndNotifyRecvListeners(final Stanza packet) {
1501        if (packet instanceof IQ) {
1502            final IQ iq = (IQ) packet;
1503            if (iq.isRequestIQ()) {
1504                final IQ iqRequest = iq;
1505                final QName key = iqRequest.getChildElementQName();
1506                IQRequestHandler iqRequestHandler;
1507                final IQ.Type type = iq.getType();
1508                switch (type) {
1509                case set:
1510                    synchronized (setIqRequestHandler) {
1511                        iqRequestHandler = setIqRequestHandler.get(key);
1512                    }
1513                    break;
1514                case get:
1515                    synchronized (getIqRequestHandler) {
1516                        iqRequestHandler = getIqRequestHandler.get(key);
1517                    }
1518                    break;
1519                default:
1520                    throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
1521                }
1522                if (iqRequestHandler == null) {
1523                    StanzaError.Condition replyCondition;
1524                    switch (unknownIqRequestReplyMode) {
1525                    case doNotReply:
1526                        return;
1527                    case replyFeatureNotImplemented:
1528                        replyCondition = StanzaError.Condition.feature_not_implemented;
1529                        break;
1530                    case replyServiceUnavailable:
1531                        replyCondition = StanzaError.Condition.service_unavailable;
1532                        break;
1533                    default:
1534                        throw new AssertionError();
1535                    }
1536
1537                    // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
1538                    // IQ of type 'error' with condition 'service-unavailable'.
1539                    final ErrorIQ errorIQ = IQ.createErrorResponse(iq, StanzaError.getBuilder(
1540                                    replyCondition).build());
1541                    // Use async sendStanza() here, since if sendStanza() would block, then some connections, e.g.
1542                    // XmppNioTcpConnection, would deadlock, as this operation is performed in the same thread that is
1543                    asyncGo(() -> {
1544                        try {
1545                            sendStanza(errorIQ);
1546                        }
1547                        catch (InterruptedException | NotConnectedException e) {
1548                            LOGGER.log(Level.WARNING, "Exception while sending error IQ to unkown IQ request", e);
1549                        }
1550                    });
1551                } else {
1552                    Executor executorService = null;
1553                    switch (iqRequestHandler.getMode()) {
1554                    case sync:
1555                        executorService = ASYNC_BUT_ORDERED.asExecutorFor(this);
1556                        break;
1557                    case async:
1558                        executorService = this::asyncGoLimited;
1559                        break;
1560                    }
1561                    final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
1562                    executorService.execute(new Runnable() {
1563                        @Override
1564                        public void run() {
1565                            IQ response = finalIqRequestHandler.handleIQRequest(iq);
1566                            if (response == null) {
1567                                // It is not ideal if the IQ request handler does not return an IQ response, because RFC
1568                                // 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
1569                                // file transfer one, does not always return a result, so we need to handle this case.
1570                                // Also sometimes a request handler may decide that it's better to not send a response,
1571                                // e.g. to avoid presence leaks.
1572                                return;
1573                            }
1574
1575                            assert response.isResponseIQ();
1576
1577                            response.setTo(iqRequest.getFrom());
1578                            response.setStanzaId(iqRequest.getStanzaId());
1579                            try {
1580                                sendStanza(response);
1581                            }
1582                            catch (InterruptedException | NotConnectedException e) {
1583                                LOGGER.log(Level.WARNING, "Exception while sending response to IQ request", e);
1584                            }
1585                        }
1586                    });
1587                }
1588                // The following returns makes it impossible for packet listeners and collectors to
1589                // filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
1590                // desired behavior.
1591                return;
1592            }
1593        }
1594
1595        // First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
1596        // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
1597        // their own thread.
1598        final Collection<StanzaListener> listenersToNotify = new LinkedList<>();
1599        extractMatchingListeners(packet, asyncRecvListeners, listenersToNotify);
1600        for (final StanzaListener listener : listenersToNotify) {
1601            asyncGoLimited(new Runnable() {
1602                @Override
1603                public void run() {
1604                    try {
1605                        listener.processStanza(packet);
1606                    } catch (Exception e) {
1607                        LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
1608                    }
1609                }
1610            });
1611        }
1612
1613        // Loop through all collectors and notify the appropriate ones.
1614        for (StanzaCollector collector : collectors) {
1615            collector.processStanza(packet);
1616        }
1617
1618        listenersToNotify.clear();
1619        extractMatchingListeners(packet, recvListeners, listenersToNotify);
1620        for (StanzaListener stanzaListener : listenersToNotify) {
1621            inOrderListeners.performAsyncButOrdered(stanzaListener, () -> {
1622                try {
1623                    stanzaListener.processStanza(packet);
1624                }
1625                catch (NotConnectedException e) {
1626                    LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
1627                }
1628                catch (Exception e) {
1629                    LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
1630                }
1631            });
1632        }
1633
1634        // Notify the receive listeners interested in the packet
1635        listenersToNotify.clear();
1636        extractMatchingListeners(packet, syncRecvListeners, listenersToNotify);
1637        // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
1638        // threaded executor service and therefore keeps the order.
1639        ASYNC_BUT_ORDERED.performAsyncButOrdered(this, new Runnable() {
1640            @Override
1641            public void run() {
1642                // As listeners are able to remove themselves and because the timepoint where it is decided to invoke a
1643                // listener is a different timepoint where the listener is actually invoked (here), we have to check
1644                // again if the listener is still active.
1645                Iterator<StanzaListener> it = listenersToNotify.iterator();
1646                synchronized (syncRecvListeners) {
1647                    while (it.hasNext()) {
1648                        StanzaListener stanzaListener = it.next();
1649                        if (!syncRecvListeners.containsKey(stanzaListener)) {
1650                            // The listener was removed from syncRecvListener, also remove him from listenersToNotify.
1651                            it.remove();
1652                        }
1653                    }
1654                }
1655                for (StanzaListener listener : listenersToNotify) {
1656                    try {
1657                        listener.processStanza(packet);
1658                    } catch (NotConnectedException e) {
1659                        LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
1660                        break;
1661                    } catch (Exception e) {
1662                        LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
1663                    }
1664                }
1665            }
1666        });
1667    }
1668
1669    private static void extractMatchingListeners(Stanza stanza, Map<StanzaListener, ListenerWrapper> listeners,
1670                    Collection<StanzaListener> listenersToNotify) {
1671        synchronized (listeners) {
1672            for (ListenerWrapper listenerWrapper : listeners.values()) {
1673                if (listenerWrapper.filterMatches(stanza)) {
1674                    listenersToNotify.add(listenerWrapper.getListener());
1675                }
1676            }
1677        }
1678    }
1679
1680    /**
1681     * Sets whether the connection has already logged in the server. This method assures that the
1682     * {@link #wasAuthenticated} flag is never reset once it has ever been set.
1683     *
1684     */
1685    protected void setWasAuthenticated() {
1686        // Never reset the flag if the connection has ever been authenticated
1687        if (!wasAuthenticated) {
1688            wasAuthenticated = authenticated;
1689        }
1690    }
1691
1692    protected void callConnectionConnectingListener() {
1693        for (ConnectionListener listener : connectionListeners) {
1694            listener.connecting(this);
1695        }
1696    }
1697
1698    protected void callConnectionConnectedListener() {
1699        for (ConnectionListener listener : connectionListeners) {
1700            listener.connected(this);
1701        }
1702    }
1703
1704    protected void callConnectionAuthenticatedListener(boolean resumed) {
1705        for (ConnectionListener listener : connectionListeners) {
1706            try {
1707                listener.authenticated(this, resumed);
1708            } catch (Exception e) {
1709                // Catch and print any exception so we can recover
1710                // from a faulty listener and finish the shutdown process
1711                LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
1712            }
1713        }
1714    }
1715
1716    void callConnectionClosedListener() {
1717        for (ConnectionListener listener : connectionListeners) {
1718            try {
1719                listener.connectionClosed();
1720            }
1721            catch (Exception e) {
1722                // Catch and print any exception so we can recover
1723                // from a faulty listener and finish the shutdown process
1724                LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
1725            }
1726        }
1727    }
1728
1729    private void callConnectionClosedOnErrorListener(Exception e) {
1730        boolean logWarning = true;
1731        if (e instanceof StreamErrorException) {
1732            StreamErrorException see = (StreamErrorException) e;
1733            if (see.getStreamError().getCondition() == StreamError.Condition.not_authorized
1734                            && wasAuthenticated) {
1735                logWarning = false;
1736                LOGGER.log(Level.FINE,
1737                                "Connection closed with not-authorized stream error after it was already authenticated. The account was likely deleted/unregistered on the server");
1738            }
1739        }
1740        if (logWarning) {
1741            LOGGER.log(Level.WARNING, "Connection " + this + " closed with error", e);
1742        }
1743        for (ConnectionListener listener : connectionListeners) {
1744            try {
1745                listener.connectionClosedOnError(e);
1746            }
1747            catch (Exception e2) {
1748                // Catch and print any exception so we can recover
1749                // from a faulty listener
1750                LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
1751            }
1752        }
1753    }
1754
1755    /**
1756     * A wrapper class to associate a stanza filter with a listener.
1757     */
1758    protected static class ListenerWrapper {
1759
1760        private final StanzaListener packetListener;
1761        private final StanzaFilter packetFilter;
1762
1763        /**
1764         * Create a class which associates a stanza filter with a listener.
1765         *
1766         * @param packetListener the stanza listener.
1767         * @param packetFilter the associated filter or null if it listen for all packets.
1768         */
1769        public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
1770            this.packetListener = packetListener;
1771            this.packetFilter = packetFilter;
1772        }
1773
1774        public boolean filterMatches(Stanza packet) {
1775            return packetFilter == null || packetFilter.accept(packet);
1776        }
1777
1778        public StanzaListener getListener() {
1779            return packetListener;
1780        }
1781    }
1782
1783    /**
1784     * A wrapper class to associate a stanza filter with an interceptor.
1785     */
1786    @Deprecated
1787    // TODO: Remove once addStanzaInterceptor is gone.
1788    protected static class InterceptorWrapper {
1789
1790        private final StanzaListener packetInterceptor;
1791        private final StanzaFilter packetFilter;
1792
1793        /**
1794         * Create a class which associates a stanza filter with an interceptor.
1795         *
1796         * @param packetInterceptor the interceptor.
1797         * @param packetFilter the associated filter or null if it intercepts all packets.
1798         */
1799        public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
1800            this.packetInterceptor = packetInterceptor;
1801            this.packetFilter = packetFilter;
1802        }
1803
1804        public boolean filterMatches(Stanza packet) {
1805            return packetFilter == null || packetFilter.accept(packet);
1806        }
1807
1808        public StanzaListener getInterceptor() {
1809            return packetInterceptor;
1810        }
1811    }
1812
1813    private static final class GenericInterceptorWrapper<MPB extends MessageOrPresenceBuilder<MP, MPB>, MP extends MessageOrPresence<MPB>> {
1814        private final Consumer<MPB> stanzaInterceptor;
1815        private final Predicate<MP> stanzaFilter;
1816
1817        private GenericInterceptorWrapper(Consumer<MPB> stanzaInterceptor, Predicate<MP> stanzaFilter) {
1818            this.stanzaInterceptor = stanzaInterceptor;
1819            this.stanzaFilter = stanzaFilter;
1820        }
1821
1822        private boolean filterMatches(MP stanza) {
1823            return stanzaFilter == null || stanzaFilter.test(stanza);
1824        }
1825
1826        public Consumer<MPB> getInterceptor() {
1827            return stanzaInterceptor;
1828        }
1829    }
1830
1831    @Override
1832    public int getConnectionCounter() {
1833        return connectionCounterValue;
1834    }
1835
1836    @Override
1837    public void setFromMode(FromMode fromMode) {
1838        this.fromMode = fromMode;
1839    }
1840
1841    @Override
1842    public FromMode getFromMode() {
1843        return this.fromMode;
1844    }
1845
1846    protected final void parseFeatures(XmlPullParser parser) throws XmlPullParserException, IOException, SmackParsingException {
1847        streamFeatures.clear();
1848        final int initialDepth = parser.getDepth();
1849        while (true) {
1850            XmlPullParser.Event eventType = parser.next();
1851
1852            if (eventType == XmlPullParser.Event.START_ELEMENT && parser.getDepth() == initialDepth + 1) {
1853                FullyQualifiedElement streamFeature = null;
1854                String name = parser.getName();
1855                String namespace = parser.getNamespace();
1856                switch (name) {
1857                case StartTls.ELEMENT:
1858                    streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
1859                    break;
1860                case Mechanisms.ELEMENT:
1861                    streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
1862                    break;
1863                case Bind.ELEMENT:
1864                    streamFeature = Bind.Feature.INSTANCE;
1865                    break;
1866                case Session.ELEMENT:
1867                    streamFeature = PacketParserUtils.parseSessionFeature(parser);
1868                    break;
1869                case Compress.Feature.ELEMENT:
1870                    streamFeature = PacketParserUtils.parseCompressionFeature(parser);
1871                    break;
1872                default:
1873                    ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
1874                    if (provider != null) {
1875                        streamFeature = provider.parse(parser, incomingStreamXmlEnvironment);
1876                    }
1877                    break;
1878                }
1879                if (streamFeature != null) {
1880                    addStreamFeature(streamFeature);
1881                }
1882            }
1883            else if (eventType == XmlPullParser.Event.END_ELEMENT && parser.getDepth() == initialDepth) {
1884                break;
1885            }
1886        }
1887    }
1888
1889    protected final void parseFeaturesAndNotify(XmlPullParser parser) throws Exception {
1890        parseFeatures(parser);
1891
1892        if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
1893            // Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
1894            if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
1895                            || config.getSecurityMode() == SecurityMode.disabled) {
1896                tlsHandled = saslFeatureReceived = true;
1897                notifyWaitingThreads();
1898            }
1899        }
1900
1901        // If the server reported the bind feature then we are that that we did SASL and maybe
1902        // STARTTLS. We can then report that the last 'stream:features' have been parsed
1903        if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
1904            if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
1905                            || !config.isCompressionEnabled()) {
1906                // This where the last stream features from the server, either it did not contain
1907                // compression or we disabled it.
1908                lastFeaturesReceived = true;
1909                notifyWaitingThreads();
1910            }
1911        }
1912        afterFeaturesReceived();
1913    }
1914
1915    @SuppressWarnings("unused")
1916    protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {
1917        // Default implementation does nothing
1918    }
1919
1920    @SuppressWarnings("unchecked")
1921    @Override
1922    public <F extends FullyQualifiedElement> F getFeature(QName qname) {
1923        return (F) streamFeatures.get(qname);
1924    }
1925
1926    @Override
1927    public boolean hasFeature(QName qname) {
1928        return streamFeatures.containsKey(qname);
1929    }
1930
1931    protected void addStreamFeature(FullyQualifiedElement feature) {
1932        QName key = feature.getQName();
1933        streamFeatures.put(key, feature);
1934    }
1935
1936    @Override
1937    public SmackFuture<IQ, Exception> sendIqRequestAsync(IQ request) {
1938        return sendIqRequestAsync(request, getReplyTimeout());
1939    }
1940
1941    @Override
1942    public SmackFuture<IQ, Exception> sendIqRequestAsync(IQ request, long timeout) {
1943        StanzaFilter replyFilter = new IQReplyFilter(request, this);
1944        return sendAsync(request, replyFilter, timeout);
1945    }
1946
1947    @Override
1948    public <S extends Stanza> SmackFuture<S, Exception> sendAsync(S stanza, final StanzaFilter replyFilter) {
1949        return sendAsync(stanza, replyFilter, getReplyTimeout());
1950    }
1951
1952    @SuppressWarnings("FutureReturnValueIgnored")
1953    @Override
1954    public <S extends Stanza> SmackFuture<S, Exception> sendAsync(S stanza, final StanzaFilter replyFilter, long timeout) {
1955        Objects.requireNonNull(stanza, "stanza must not be null");
1956        // While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
1957        // disallow it here in the async API as it makes no sense
1958        Objects.requireNonNull(replyFilter, "replyFilter must not be null");
1959
1960        final InternalSmackFuture<S, Exception> future = new InternalSmackFuture<>();
1961
1962        final StanzaListener stanzaListener = new StanzaListener() {
1963            @Override
1964            public void processStanza(Stanza stanza) throws NotConnectedException, InterruptedException {
1965                boolean removed = removeAsyncStanzaListener(this);
1966                if (!removed) {
1967                    // We lost a race against the "no response" handling runnable. Avoid calling the callback, as the
1968                    // exception callback will be invoked (if any).
1969                    return;
1970                }
1971                try {
1972                    XMPPErrorException.ifHasErrorThenThrow(stanza);
1973                    @SuppressWarnings("unchecked")
1974                    S s = (S) stanza;
1975                    future.setResult(s);
1976                }
1977                catch (XMPPErrorException exception) {
1978                    future.setException(exception);
1979                }
1980            }
1981        };
1982        schedule(new Runnable() {
1983            @Override
1984            public void run() {
1985                boolean removed = removeAsyncStanzaListener(stanzaListener);
1986                if (!removed) {
1987                    // We lost a race against the stanza listener, he already removed itself because he received a
1988                    // reply. There is nothing more to do here.
1989                    return;
1990                }
1991
1992                // If the packetListener got removed, then it was never run and
1993                // we never received a response, inform the exception callback
1994                Exception exception;
1995                if (!isConnected()) {
1996                    // If the connection is no longer connected, throw a not connected exception.
1997                    exception = new NotConnectedException(AbstractXMPPConnection.this, replyFilter);
1998                }
1999                else {
2000                    exception = NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter);
2001                }
2002                future.setException(exception);
2003            }
2004        }, timeout, TimeUnit.MILLISECONDS);
2005
2006        addAsyncStanzaListener(stanzaListener, replyFilter);
2007        try {
2008            sendStanza(stanza);
2009        }
2010        catch (NotConnectedException | InterruptedException exception) {
2011            future.setException(exception);
2012        }
2013
2014        return future;
2015    }
2016
2017    @SuppressWarnings("FutureReturnValueIgnored")
2018    @Override
2019    public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
2020        final StanzaListener packetListener = new StanzaListener() {
2021            @Override
2022            public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException, NotLoggedInException {
2023                try {
2024                    callback.processStanza(packet);
2025                } finally {
2026                    removeSyncStanzaListener(this);
2027                }
2028            }
2029        };
2030        addSyncStanzaListener(packetListener, packetFilter);
2031        schedule(new Runnable() {
2032            @Override
2033            public void run() {
2034                removeSyncStanzaListener(packetListener);
2035            }
2036        }, getReplyTimeout(), TimeUnit.MILLISECONDS);
2037    }
2038
2039    @Override
2040    public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
2041        final QName key = iqRequestHandler.getQName();
2042        switch (iqRequestHandler.getType()) {
2043        case set:
2044            synchronized (setIqRequestHandler) {
2045                return setIqRequestHandler.put(key, iqRequestHandler);
2046            }
2047        case get:
2048            synchronized (getIqRequestHandler) {
2049                return getIqRequestHandler.put(key, iqRequestHandler);
2050            }
2051        default:
2052            throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
2053        }
2054    }
2055
2056    @Override
2057    public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
2058        return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
2059                        iqRequestHandler.getType());
2060    }
2061
2062    @Override
2063    public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
2064        final QName key = new QName(namespace, element);
2065        switch (type) {
2066        case set:
2067            synchronized (setIqRequestHandler) {
2068                return setIqRequestHandler.remove(key);
2069            }
2070        case get:
2071            synchronized (getIqRequestHandler) {
2072                return getIqRequestHandler.remove(key);
2073            }
2074        default:
2075            throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
2076        }
2077    }
2078
2079    private long lastStanzaReceived;
2080
2081    @Override
2082    public long getLastStanzaReceived() {
2083        return lastStanzaReceived;
2084    }
2085
2086    /**
2087     * Get the timestamp when the connection was the first time authenticated, i.e., when the first successful login was
2088     * performed. Note that this value is not reset on disconnect, so it represents the timestamp from the last
2089     * authenticated connection. The value is also not reset on stream resumption.
2090     *
2091     * @return the timestamp or {@code null}.
2092     * @since 4.3.3
2093     */
2094    public final long getAuthenticatedConnectionInitiallyEstablishedTimestamp() {
2095        return authenticatedConnectionInitiallyEstablishedTimestamp;
2096    }
2097
2098    /**
2099     * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
2100     * stanza.
2101     *
2102     * @param callback the callback to install
2103     */
2104    public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
2105        parsingExceptionCallback = callback;
2106    }
2107
2108    /**
2109     * Get the current active parsing exception callback.
2110     *
2111     * @return the active exception callback or null if there is none
2112     */
2113    public ParsingExceptionCallback getParsingExceptionCallback() {
2114        return parsingExceptionCallback;
2115    }
2116
2117    @Override
2118    public final String toString() {
2119        EntityFullJid localEndpoint = getUser();
2120        String localEndpointString = localEndpoint == null ?  "not-authenticated" : localEndpoint.toString();
2121        return getClass().getSimpleName() + '[' + localEndpointString + "] (" + getConnectionCounter() + ')';
2122    }
2123
2124    /**
2125     * A queue of deferred runnables that where not executed immediately because {@link #currentAsyncRunnables} reached
2126     * {@link #maxAsyncRunnables}. Note that we use a {@code LinkedList} in order to avoid space blowups in case the
2127     * list ever becomes very big and shrinks again.
2128     */
2129    private final Queue<Runnable> deferredAsyncRunnables = new LinkedList<>();
2130
2131    private int deferredAsyncRunnablesCount;
2132
2133    private int deferredAsyncRunnablesCountPrevious;
2134
2135    private int maxAsyncRunnables = SmackConfiguration.getDefaultConcurrencyLevelLimit();
2136
2137    private int currentAsyncRunnables;
2138
2139    protected void asyncGoLimited(final Runnable runnable) {
2140        Runnable wrappedRunnable = new Runnable() {
2141            @Override
2142            public void run() {
2143                runnable.run();
2144
2145                synchronized (deferredAsyncRunnables) {
2146                    Runnable defferredRunnable = deferredAsyncRunnables.poll();
2147                    if (defferredRunnable == null) {
2148                        currentAsyncRunnables--;
2149                    } else {
2150                        deferredAsyncRunnablesCount--;
2151                        asyncGo(defferredRunnable);
2152                    }
2153                }
2154            }
2155        };
2156
2157        synchronized (deferredAsyncRunnables) {
2158            if (currentAsyncRunnables < maxAsyncRunnables) {
2159                currentAsyncRunnables++;
2160                asyncGo(wrappedRunnable);
2161            } else {
2162                deferredAsyncRunnablesCount++;
2163                deferredAsyncRunnables.add(wrappedRunnable);
2164            }
2165
2166            final int HIGH_WATERMARK = 100;
2167            final int INFORM_WATERMARK = 20;
2168
2169            final int deferredAsyncRunnablesCount = this.deferredAsyncRunnablesCount;
2170
2171            if (deferredAsyncRunnablesCount >= HIGH_WATERMARK
2172                    && deferredAsyncRunnablesCountPrevious < HIGH_WATERMARK) {
2173                LOGGER.log(Level.WARNING, "High watermark of " + HIGH_WATERMARK + " simultaneous executing runnables reached");
2174            } else if (deferredAsyncRunnablesCount >= INFORM_WATERMARK
2175                    && deferredAsyncRunnablesCountPrevious < INFORM_WATERMARK) {
2176                LOGGER.log(Level.INFO, INFORM_WATERMARK + " simultaneous executing runnables reached");
2177            }
2178
2179            deferredAsyncRunnablesCountPrevious = deferredAsyncRunnablesCount;
2180        }
2181    }
2182
2183    public void setMaxAsyncOperations(int maxAsyncOperations) {
2184        if (maxAsyncOperations < 1) {
2185            throw new IllegalArgumentException("Max async operations must be greater than 0");
2186        }
2187
2188        synchronized (deferredAsyncRunnables) {
2189            maxAsyncRunnables = maxAsyncOperations;
2190        }
2191    }
2192
2193    protected static void asyncGo(Runnable runnable) {
2194        CACHED_EXECUTOR_SERVICE.execute(runnable);
2195    }
2196
2197    @SuppressWarnings("static-method")
2198    protected final SmackReactor getReactor() {
2199        return SMACK_REACTOR;
2200    }
2201
2202    protected static ScheduledAction schedule(Runnable runnable, long delay, TimeUnit unit) {
2203        return SMACK_REACTOR.schedule(runnable, delay, unit, ScheduledAction.Kind.NonBlocking);
2204    }
2205
2206    protected void onStreamOpen(XmlPullParser parser) {
2207        // We found an opening stream.
2208        if ("jabber:client".equals(parser.getNamespace(null))) {
2209            streamId = parser.getAttributeValue("", "id");
2210            incomingStreamXmlEnvironment = XmlEnvironment.from(parser);
2211
2212            String reportedServerDomainString = parser.getAttributeValue("", "from");
2213            if (reportedServerDomainString == null) {
2214                // RFC 6120 § 4.7.1. makes no explicit statement whether or not 'from' in the stream open from the server
2215                // in c2s connections is required or not.
2216                return;
2217            }
2218            DomainBareJid reportedServerDomain;
2219            try {
2220                reportedServerDomain = JidCreate.domainBareFrom(reportedServerDomainString);
2221                DomainBareJid configuredXmppServiceDomain = config.getXMPPServiceDomain();
2222                if (!configuredXmppServiceDomain.equals(reportedServerDomain)) {
2223                    LOGGER.warning("Domain reported by server '" + reportedServerDomain
2224                            + "' does not match configured domain '" + configuredXmppServiceDomain + "'");
2225                }
2226            } catch (XmppStringprepException e) {
2227                LOGGER.log(Level.WARNING, "XMPP service domain '" + reportedServerDomainString
2228                        + "' as reported by server could not be transformed to a valid JID", e);
2229            }
2230        }
2231    }
2232
2233    protected void sendStreamOpen() throws NotConnectedException, InterruptedException {
2234        // If possible, provide the receiving entity of the stream open tag, i.e. the server, as much information as
2235        // possible. The 'to' attribute is *always* available. The 'from' attribute if set by the user and no external
2236        // mechanism is used to determine the local entity (user). And the 'id' attribute is available after the first
2237        // response from the server (see e.g. RFC 6120 § 9.1.1 Step 2.)
2238        CharSequence to = getXMPPServiceDomain();
2239        CharSequence from = null;
2240        CharSequence localpart = config.getUsername();
2241        if (localpart != null) {
2242            from = XmppStringUtils.completeJidFrom(localpart, to);
2243        }
2244        String id = getStreamId();
2245
2246        StreamOpen streamOpen = new StreamOpen(to, from, id, config.getXmlLang(), StreamOpen.StreamContentNamespace.client);
2247        sendNonza(streamOpen);
2248
2249        XmlEnvironment.Builder xmlEnvironmentBuilder = XmlEnvironment.builder();
2250        xmlEnvironmentBuilder.with(streamOpen);
2251        outgoingStreamXmlEnvironment = xmlEnvironmentBuilder.build();
2252    }
2253
2254    protected final SmackTlsContext getSmackTlsContext() {
2255        return config.smackTlsContext;
2256    }
2257}