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