001/**
002 *
003 * Copyright 2009 Jive Software.
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.ArrayList;
023import java.util.Collection;
024import java.util.HashMap;
025import java.util.LinkedHashMap;
026import java.util.LinkedList;
027import java.util.List;
028import java.util.Map;
029import java.util.Set;
030import java.util.concurrent.ArrayBlockingQueue;
031import java.util.concurrent.ConcurrentLinkedQueue;
032import java.util.concurrent.CopyOnWriteArraySet;
033import java.util.concurrent.ExecutorService;
034import java.util.concurrent.Executors;
035import java.util.concurrent.ScheduledExecutorService;
036import java.util.concurrent.ScheduledFuture;
037import java.util.concurrent.ThreadPoolExecutor;
038import java.util.concurrent.TimeUnit;
039import java.util.concurrent.atomic.AtomicInteger;
040import java.util.concurrent.locks.Lock;
041import java.util.concurrent.locks.ReentrantLock;
042import java.util.logging.Level;
043import java.util.logging.Logger;
044
045import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
046import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
047import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
048import org.jivesoftware.smack.SmackException.NoResponseException;
049import org.jivesoftware.smack.SmackException.NotConnectedException;
050import org.jivesoftware.smack.SmackException.ConnectionException;
051import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
052import org.jivesoftware.smack.SmackException.SecurityRequiredException;
053import org.jivesoftware.smack.XMPPException.XMPPErrorException;
054import org.jivesoftware.smack.compress.packet.Compress;
055import org.jivesoftware.smack.compression.XMPPInputOutputStream;
056import org.jivesoftware.smack.debugger.SmackDebugger;
057import org.jivesoftware.smack.filter.IQReplyFilter;
058import org.jivesoftware.smack.filter.StanzaFilter;
059import org.jivesoftware.smack.filter.StanzaIdFilter;
060import org.jivesoftware.smack.iqrequest.IQRequestHandler;
061import org.jivesoftware.smack.packet.Bind;
062import org.jivesoftware.smack.packet.ErrorIQ;
063import org.jivesoftware.smack.packet.IQ;
064import org.jivesoftware.smack.packet.Mechanisms;
065import org.jivesoftware.smack.packet.Stanza;
066import org.jivesoftware.smack.packet.ExtensionElement;
067import org.jivesoftware.smack.packet.Presence;
068import org.jivesoftware.smack.packet.Session;
069import org.jivesoftware.smack.packet.StartTls;
070import org.jivesoftware.smack.packet.PlainStreamElement;
071import org.jivesoftware.smack.packet.XMPPError;
072import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
073import org.jivesoftware.smack.parsing.UnparsablePacket;
074import org.jivesoftware.smack.provider.ExtensionElementProvider;
075import org.jivesoftware.smack.provider.ProviderManager;
076import org.jivesoftware.smack.util.DNSUtil;
077import org.jivesoftware.smack.util.Objects;
078import org.jivesoftware.smack.util.PacketParserUtils;
079import org.jivesoftware.smack.util.ParserUtils;
080import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
081import org.jivesoftware.smack.util.StringUtils;
082import org.jivesoftware.smack.util.dns.HostAddress;
083import org.jxmpp.util.XmppStringUtils;
084import org.xmlpull.v1.XmlPullParser;
085import org.xmlpull.v1.XmlPullParserException;
086
087
088public abstract class AbstractXMPPConnection implements XMPPConnection {
089    private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());
090
091    /** 
092     * Counter to uniquely identify connections that are created.
093     */
094    private final static AtomicInteger connectionCounter = new AtomicInteger(0);
095
096    static {
097        // Ensure the SmackConfiguration class is loaded by calling a method in it.
098        SmackConfiguration.getVersion();
099    }
100
101    /**
102     * Get the collection of listeners that are interested in connection creation events.
103     * 
104     * @return a collection of listeners interested on new connections.
105     */
106    protected static Collection<ConnectionCreationListener> getConnectionCreationListeners() {
107        return XMPPConnectionRegistry.getConnectionCreationListeners();
108    }
109 
110    /**
111     * A collection of ConnectionListeners which listen for connection closing
112     * and reconnection events.
113     */
114    protected final Set<ConnectionListener> connectionListeners =
115            new CopyOnWriteArraySet<ConnectionListener>();
116
117    /**
118     * A collection of PacketCollectors which collects packets for a specified filter
119     * and perform blocking and polling operations on the result queue.
120     * <p>
121     * We use a ConcurrentLinkedQueue here, because its Iterator is weakly
122     * consistent and we want {@link #invokePacketCollectors(Stanza)} for-each
123     * loop to be lock free. As drawback, removing a PacketCollector is O(n).
124     * The alternative would be a synchronized HashSet, but this would mean a
125     * synchronized block around every usage of <code>collectors</code>.
126     * </p>
127     */
128    private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>();
129
130    /**
131     * List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received.
132     */
133    private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();
134
135    /**
136     * List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received.
137     */
138    private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();
139
140    /**
141     * List of PacketListeners that will be notified when a new stanza(/packet) was sent.
142     */
143    private final Map<StanzaListener, ListenerWrapper> sendListeners =
144            new HashMap<StanzaListener, ListenerWrapper>();
145
146    /**
147     * List of PacketListeners that will be notified when a new stanza(/packet) is about to be
148     * sent to the server. These interceptors may modify the stanza(/packet) before it is being
149     * actually sent to the server.
150     */
151    private final Map<StanzaListener, InterceptorWrapper> interceptors =
152            new HashMap<StanzaListener, InterceptorWrapper>();
153
154    protected final Lock connectionLock = new ReentrantLock();
155
156    protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>();
157
158    /**
159     * The full JID of the authenticated user, as returned by the resource binding response of the server.
160     * <p>
161     * It is important that we don't infer the user from the login() arguments and the configurations service name, as,
162     * for example, when SASL External is used, the username is not given to login but taken from the 'external'
163     * certificate.
164     * </p>
165     */
166    protected String user;
167
168    protected boolean connected = false;
169
170    /**
171     * The stream ID, see RFC 6120 § 4.7.3
172     */
173    protected String streamId;
174
175    /**
176     * 
177     */
178    private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout();
179
180    /**
181     * The SmackDebugger allows to log and debug XML traffic.
182     */
183    protected SmackDebugger debugger = null;
184
185    /**
186     * The Reader which is used for the debugger.
187     */
188    protected Reader reader;
189
190    /**
191     * The Writer which is used for the debugger.
192     */
193    protected Writer writer;
194
195    /**
196     * Set to success if the last features stanza from the server has been parsed. A XMPP connection
197     * handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
198     * stanza is send by the server. This is set to true once the last feature stanza has been
199     * parsed.
200     */
201    protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>(
202                    AbstractXMPPConnection.this);
203
204    /**
205     * Set to success if the sasl feature has been received.
206     */
207    protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>(
208                    AbstractXMPPConnection.this);
209 
210    /**
211     * The SASLAuthentication manager that is responsible for authenticating with the server.
212     */
213    protected SASLAuthentication saslAuthentication = new SASLAuthentication(this);
214
215    /**
216     * A number to uniquely identify connections that are created. This is distinct from the
217     * connection ID, which is a value sent by the server once a connection is made.
218     */
219    protected final int connectionCounterValue = connectionCounter.getAndIncrement();
220
221    /**
222     * Holds the initial configuration used while creating the connection.
223     */
224    protected final ConnectionConfiguration config;
225
226    /**
227     * Defines how the from attribute of outgoing stanzas should be handled.
228     */
229    private FromMode fromMode = FromMode.OMITTED;
230
231    protected XMPPInputOutputStream compressionHandler;
232
233    private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();
234
235    /**
236     * ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is
237     * important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the
238     * PacketListeners are invoked in the same order the stanzas arrived.
239     */
240    private final ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
241                    new ArrayBlockingQueue<Runnable>(100), new SmackExecutorThreadFactory(connectionCounterValue, "Incoming Processor"));
242
243    /**
244     * This scheduled thread pool executor is used to remove pending callbacks.
245     */
246    private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor(
247                    new SmackExecutorThreadFactory(connectionCounterValue, "Remove Callbacks"));
248
249    /**
250     * A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
251     * them 'daemon'.
252     */
253    private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool(
254                    // @formatter:off
255                    new SmackExecutorThreadFactory(    // threadFactory
256                                    connectionCounterValue,
257                                    "Cached Executor"
258                                    )
259                    // @formatter:on
260                    );
261
262    /**
263     * A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to
264     * decouple incoming stanza processing from callback invocation. It is important that order of callback invocation
265     * is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service.
266     */
267    private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory(
268                    getConnectionCounter(), "Single Threaded Executor"));
269
270    /**
271     * The used host to establish the connection to
272     */
273    protected String host;
274
275    /**
276     * The used port to establish the connection to
277     */
278    protected int port;
279
280    /**
281     * Flag that indicates if the user is currently authenticated with the server.
282     */
283    protected boolean authenticated = false;
284
285    /**
286     * Flag that indicates if the user was authenticated with the server when the connection
287     * to the server was closed (abruptly or not).
288     */
289    protected boolean wasAuthenticated = false;
290
291    private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>();
292    private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>();
293
294    /**
295     * Create a new XMPPConnection to an XMPP server.
296     * 
297     * @param configuration The configuration which is used to establish the connection.
298     */
299    protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
300        config = configuration;
301    }
302
303    /**
304     * Get the connection configuration used by this connection.
305     *
306     * @return the connection configuration.
307     */
308    public ConnectionConfiguration getConfiguration() {
309        return config;
310    }
311
312    @Override
313    public String getServiceName() {
314        if (serviceName != null) {
315            return serviceName;
316        }
317        return config.getServiceName();
318    }
319
320    @Override
321    public String getHost() {
322        return host;
323    }
324
325    @Override
326    public int getPort() {
327        return port;
328    }
329
330    @Override
331    public abstract boolean isSecureConnection();
332
333    protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException;
334
335    @Override
336    public abstract void send(PlainStreamElement element) throws NotConnectedException;
337
338    @Override
339    public abstract boolean isUsingCompression();
340
341    /**
342     * Establishes a connection to the XMPP server and performs an automatic login
343     * only if the previous connection state was logged (authenticated). It basically
344     * creates and maintains a connection to the server.
345     * <p>
346     * Listeners will be preserved from a previous connection.
347     * 
348     * @throws XMPPException if an error occurs on the XMPP protocol level.
349     * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
350     * @throws IOException 
351     * @throws ConnectionException with detailed information about the failed connection.
352     * @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
353     */
354    public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException {
355        // Check if not already connected
356        throwAlreadyConnectedExceptionIfAppropriate();
357
358        // Reset the connection state
359        saslAuthentication.init();
360        saslFeatureReceived.init();
361        lastFeaturesReceived.init();
362        streamId = null;
363
364        // Perform the actual connection to the XMPP service
365        connectInternal();
366        return this;
367    }
368
369    /**
370     * Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
371     * way of XMPP connection establishment. Implementations are required to perform an automatic
372     * login if the previous connection state was logged (authenticated).
373     * 
374     * @throws SmackException
375     * @throws IOException
376     * @throws XMPPException
377     */
378    protected abstract void connectInternal() throws SmackException, IOException, XMPPException;
379
380    private String usedUsername, usedPassword, usedResource;
381
382    /**
383     * Logs in to the server using the strongest SASL mechanism supported by
384     * the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the 
385     * authentication process without a response from the server, a
386     * {@link SmackException.NoResponseException} will be thrown.
387     * <p>
388     * Before logging in (i.e. authenticate) to the server the connection must be connected
389     * by calling {@link #connect}.
390     * </p>
391     * <p>
392     * It is possible to log in without sending an initial available presence by using
393     * {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
394     * Finally, if you want to not pass a password and instead use a more advanced mechanism
395     * while using SASL then you may be interested in using
396     * {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
397     * For more advanced login settings see {@link ConnectionConfiguration}.
398     * </p>
399     * 
400     * @throws XMPPException if an error occurs on the XMPP protocol level.
401     * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
402     * @throws IOException if an I/O error occurs during login.
403     */
404    public synchronized void login() throws XMPPException, SmackException, IOException {
405        if (isAnonymous()) {
406            throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?");
407            throwAlreadyLoggedInExceptionIfAppropriate();
408            loginAnonymously();
409        } else {
410            // The previously used username, password and resource take over precedence over the
411            // ones from the connection configuration
412            CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
413            String password = usedPassword != null ? usedPassword : config.getPassword();
414            String resource = usedResource != null ? usedResource : config.getResource();
415            login(username, password, resource);
416        }
417    }
418
419    /**
420     * Same as {@link #login(CharSequence, String, String)}, but takes the resource from the connection
421     * configuration.
422     * 
423     * @param username
424     * @param password
425     * @throws XMPPException
426     * @throws SmackException
427     * @throws IOException
428     * @see #login
429     */
430    public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
431                    IOException {
432        login(username, password, config.getResource());
433    }
434
435    /**
436     * Login with the given username (authorization identity). You may omit the password if a callback handler is used.
437     * If resource is null, then the server will generate one.
438     * 
439     * @param username
440     * @param password
441     * @param resource
442     * @throws XMPPException
443     * @throws SmackException
444     * @throws IOException
445     * @see #login
446     */
447    public synchronized void login(CharSequence username, String password, String resource) throws XMPPException,
448                    SmackException, IOException {
449        if (!config.allowNullOrEmptyUsername) {
450            StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty");
451        }
452        throwNotConnectedExceptionIfAppropriate();
453        throwAlreadyLoggedInExceptionIfAppropriate();
454        usedUsername = username != null ? username.toString() : null;
455        usedPassword = password;
456        usedResource = resource;
457        loginNonAnonymously(usedUsername, usedPassword, usedResource);
458    }
459
460    protected abstract void loginNonAnonymously(String username, String password, String resource)
461                    throws XMPPException, SmackException, IOException;
462
463    protected abstract void loginAnonymously() throws XMPPException, SmackException, IOException;
464
465    @Override
466    public final boolean isConnected() {
467        return connected;
468    }
469
470    @Override
471    public final boolean isAuthenticated() {
472        return authenticated;
473    }
474
475    @Override
476    public final String getUser() {
477        return user;
478    }
479
480    @Override
481    public String getStreamId() {
482        if (!isConnected()) {
483            return null;
484        }
485        return streamId;
486    }
487
488    // TODO remove this suppression once "disable legacy session" code has been removed from Smack
489    @SuppressWarnings("deprecation")
490    protected void bindResourceAndEstablishSession(String resource) throws XMPPErrorException,
491                    IOException, SmackException {
492
493        // Wait until either:
494        // - the servers last features stanza has been parsed
495        // - the timeout occurs
496        LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
497        lastFeaturesReceived.checkIfSuccessOrWait();
498
499
500        if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
501            // Server never offered resource binding, which is REQURIED in XMPP client and
502            // server implementations as per RFC6120 7.2
503            throw new ResourceBindingNotOfferedException();
504        }
505
506        // Resource binding, see RFC6120 7.
507        // Note that we can not use IQReplyFilter here, since the users full JID is not yet
508        // available. It will become available right after the resource has been successfully bound.
509        Bind bindResource = Bind.newSet(resource);
510        PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
511        Bind response = packetCollector.nextResultOrThrow();
512        // Set the connections user to the result of resource binding. It is important that we don't infer the user
513        // from the login() arguments and the configurations service name, as, for example, when SASL External is used,
514        // the username is not given to login but taken from the 'external' certificate.
515        user = response.getJid();
516        serviceName = XmppStringUtils.parseDomain(user);
517
518        Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
519        // Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
520        // For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
521        if (sessionFeature != null && !sessionFeature.isOptional() && !getConfiguration().isLegacySessionDisabled()) {
522            Session session = new Session();
523            packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session);
524            packetCollector.nextResultOrThrow();
525        }
526    }
527
528    protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException {
529        // Indicate that we're now authenticated.
530        this.authenticated = true;
531
532        // If debugging is enabled, change the the debug window title to include the
533        // name we are now logged-in as.
534        // If DEBUG was set to true AFTER the connection was created the debugger
535        // will be null
536        if (config.isDebuggerEnabled() && debugger != null) {
537            debugger.userHasLogged(user);
538        }
539        callConnectionAuthenticatedListener(resumed);
540
541        // Set presence to online. It is important that this is done after
542        // callConnectionAuthenticatedListener(), as this call will also
543        // eventually load the roster. And we should load the roster before we
544        // send the initial presence.
545        if (config.isSendPresence() && !resumed) {
546            sendStanza(new Presence(Presence.Type.available));
547        }
548    }
549
550    @Override
551    public final boolean isAnonymous() {
552        return config.getUsername() == null && usedUsername == null
553                        && !config.allowNullOrEmptyUsername;
554    }
555
556    private String serviceName;
557
558    protected List<HostAddress> hostAddresses;
559
560    /**
561     * Populates {@link #hostAddresses} with at least one host address.
562     *
563     * @return a list of host addresses where DNS (SRV) RR resolution failed.
564     */
565    protected List<HostAddress> populateHostAddresses() {
566        List<HostAddress> failedAddresses = new LinkedList<>();
567        // N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName
568        if (config.host != null) {
569            hostAddresses = new ArrayList<HostAddress>(1);
570            HostAddress hostAddress;
571            hostAddress = new HostAddress(config.host, config.port);
572            hostAddresses.add(hostAddress);
573        } else {
574            hostAddresses = DNSUtil.resolveXMPPDomain(config.serviceName, failedAddresses);
575        }
576        // If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the
577        // config.host one or the host representing the service name by DNSUtil
578        assert(!hostAddresses.isEmpty());
579        return failedAddresses;
580    }
581
582    protected Lock getConnectionLock() {
583        return connectionLock;
584    }
585
586    protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
587        throwNotConnectedExceptionIfAppropriate(null);
588    }
589
590    protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException {
591        if (!isConnected()) {
592            throw new NotConnectedException(optionalHint);
593        }
594    }
595
596    protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
597        if (isConnected()) {
598            throw new AlreadyConnectedException();
599        }
600    }
601
602    protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
603        if (isAuthenticated()) {
604            throw new AlreadyLoggedInException();
605        }
606    }
607
608    @Deprecated
609    @Override
610    public void sendPacket(Stanza packet) throws NotConnectedException {
611        sendStanza(packet);
612    }
613
614    @Override
615    public void sendStanza(Stanza packet) throws NotConnectedException {
616        Objects.requireNonNull(packet, "Packet must not be null");
617
618        throwNotConnectedExceptionIfAppropriate();
619        switch (fromMode) {
620        case OMITTED:
621            packet.setFrom(null);
622            break;
623        case USER:
624            packet.setFrom(getUser());
625            break;
626        case UNCHANGED:
627        default:
628            break;
629        }
630        // Invoke interceptors for the new packet that is about to be sent. Interceptors may modify
631        // the content of the packet.
632        firePacketInterceptors(packet);
633        sendStanzaInternal(packet);
634    }
635
636    /**
637     * Returns the SASLAuthentication manager that is responsible for authenticating with
638     * the server.
639     * 
640     * @return the SASLAuthentication manager that is responsible for authenticating with
641     *         the server.
642     */
643    protected SASLAuthentication getSASLAuthentication() {
644        return saslAuthentication;
645    }
646
647    /**
648     * Closes the connection by setting presence to unavailable then closing the connection to
649     * the XMPP server. The XMPPConnection can still be used for connecting to the server
650     * again.
651     *
652     */
653    public void disconnect() {
654        try {
655            disconnect(new Presence(Presence.Type.unavailable));
656        }
657        catch (NotConnectedException e) {
658            LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
659        }
660    }
661
662    /**
663     * Closes the connection. A custom unavailable presence is sent to the server, followed
664     * by closing the stream. The XMPPConnection can still be used for connecting to the server
665     * again. A custom unavailable presence is useful for communicating offline presence
666     * information such as "On vacation". Typically, just the status text of the presence
667     * stanza(/packet) is set with online information, but most XMPP servers will deliver the full
668     * presence stanza(/packet) with whatever data is set.
669     * 
670     * @param unavailablePresence the presence stanza(/packet) to send during shutdown.
671     * @throws NotConnectedException 
672     */
673    public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
674        sendStanza(unavailablePresence);
675        shutdown();
676        callConnectionClosedListener();
677    }
678
679    /**
680     * Shuts the current connection down.
681     */
682    protected abstract void shutdown();
683
684    @Override
685    public void addConnectionListener(ConnectionListener connectionListener) {
686        if (connectionListener == null) {
687            return;
688        }
689        connectionListeners.add(connectionListener);
690    }
691
692    @Override
693    public void removeConnectionListener(ConnectionListener connectionListener) {
694        connectionListeners.remove(connectionListener);
695    }
696
697    @Override
698    public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException {
699        StanzaFilter packetFilter = new IQReplyFilter(packet, this);
700        // Create the packet collector before sending the packet
701        PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet);
702        return packetCollector;
703    }
704
705    @Override
706    public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
707                    throws NotConnectedException {
708        // Create the packet collector before sending the packet
709        PacketCollector packetCollector = createPacketCollector(packetFilter);
710        try {
711            // Now we can send the packet as the collector has been created
712            sendStanza(packet);
713        }
714        catch (NotConnectedException | RuntimeException e) {
715            packetCollector.cancel();
716            throw e;
717        }
718        return packetCollector;
719    }
720
721    @Override
722    public PacketCollector createPacketCollector(StanzaFilter packetFilter) {
723        PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter);
724        return createPacketCollector(configuration);
725    }
726
727    @Override
728    public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) {
729        PacketCollector collector = new PacketCollector(this, configuration);
730        // Add the collector to the list of active collectors.
731        collectors.add(collector);
732        return collector;
733    }
734
735    @Override
736    public void removePacketCollector(PacketCollector collector) {
737        collectors.remove(collector);
738    }
739
740    @Override
741    @Deprecated
742    public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) {
743        addAsyncStanzaListener(packetListener, packetFilter);
744    }
745
746    @Override
747    @Deprecated
748    public boolean removePacketListener(StanzaListener packetListener) {
749        return removeAsyncStanzaListener(packetListener);
750    }
751
752    @Override
753    public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
754        if (packetListener == null) {
755            throw new NullPointerException("Packet listener is null.");
756        }
757        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
758        synchronized (syncRecvListeners) {
759            syncRecvListeners.put(packetListener, wrapper);
760        }
761    }
762
763    @Override
764    public boolean removeSyncStanzaListener(StanzaListener packetListener) {
765        synchronized (syncRecvListeners) {
766            return syncRecvListeners.remove(packetListener) != null;
767        }
768    }
769
770    @Override
771    public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
772        if (packetListener == null) {
773            throw new NullPointerException("Packet listener is null.");
774        }
775        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
776        synchronized (asyncRecvListeners) {
777            asyncRecvListeners.put(packetListener, wrapper);
778        }
779    }
780
781    @Override
782    public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
783        synchronized (asyncRecvListeners) {
784            return asyncRecvListeners.remove(packetListener) != null;
785        }
786    }
787
788    @Override
789    public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
790        if (packetListener == null) {
791            throw new NullPointerException("Packet listener is null.");
792        }
793        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
794        synchronized (sendListeners) {
795            sendListeners.put(packetListener, wrapper);
796        }
797    }
798
799    @Override
800    public void removePacketSendingListener(StanzaListener packetListener) {
801        synchronized (sendListeners) {
802            sendListeners.remove(packetListener);
803        }
804    }
805
806    /**
807     * Process all stanza(/packet) listeners for sending packets.
808     * <p>
809     * Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
810     * </p>
811     * 
812     * @param packet the stanza(/packet) to process.
813     */
814    @SuppressWarnings("javadoc")
815    protected void firePacketSendingListeners(final Stanza packet) {
816        final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
817        synchronized (sendListeners) {
818            for (ListenerWrapper listenerWrapper : sendListeners.values()) {
819                if (listenerWrapper.filterMatches(packet)) {
820                    listenersToNotify.add(listenerWrapper.getListener());
821                }
822            }
823        }
824        if (listenersToNotify.isEmpty()) {
825            return;
826        }
827        // Notify in a new thread, because we can
828        asyncGo(new Runnable() {
829            @Override
830            public void run() {
831                for (StanzaListener listener : listenersToNotify) {
832                    try {
833                        listener.processPacket(packet);
834                    }
835                    catch (Exception e) {
836                        LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
837                        continue;
838                    }
839                }
840            }});
841    }
842
843    @Override
844    public void addPacketInterceptor(StanzaListener packetInterceptor,
845            StanzaFilter packetFilter) {
846        if (packetInterceptor == null) {
847            throw new NullPointerException("Packet interceptor is null.");
848        }
849        InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
850        synchronized (interceptors) {
851            interceptors.put(packetInterceptor, interceptorWrapper);
852        }
853    }
854
855    @Override
856    public void removePacketInterceptor(StanzaListener packetInterceptor) {
857        synchronized (interceptors) {
858            interceptors.remove(packetInterceptor);
859        }
860    }
861
862    /**
863     * Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent.
864     * Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it
865     * is important that interceptors perform their work as soon as possible so that the
866     * thread does not remain blocked for a long period.
867     * 
868     * @param packet the stanza(/packet) that is going to be sent to the server
869     */
870    private void firePacketInterceptors(Stanza packet) {
871        List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>();
872        synchronized (interceptors) {
873            for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
874                if (interceptorWrapper.filterMatches(packet)) {
875                    interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
876                }
877            }
878        }
879        for (StanzaListener interceptor : interceptorsToInvoke) {
880            try {
881                interceptor.processPacket(packet);
882            } catch (Exception e) {
883                LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
884            }
885        }
886    }
887
888    /**
889     * Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
890     * by setup the system property <code>smack.debuggerClass</code> to the implementation.
891     * 
892     * @throws IllegalStateException if the reader or writer isn't yet initialized.
893     * @throws IllegalArgumentException if the SmackDebugger can't be loaded.
894     */
895    protected void initDebugger() {
896        if (reader == null || writer == null) {
897            throw new NullPointerException("Reader or writer isn't initialized.");
898        }
899        // If debugging is enabled, we open a window and write out all network traffic.
900        if (config.isDebuggerEnabled()) {
901            if (debugger == null) {
902                debugger = SmackConfiguration.createDebugger(this, writer, reader);
903            }
904
905            if (debugger == null) {
906                LOGGER.severe("Debugging enabled but could not find debugger class");
907            } else {
908                // Obtain new reader and writer from the existing debugger
909                reader = debugger.newConnectionReader(reader);
910                writer = debugger.newConnectionWriter(writer);
911            }
912        }
913    }
914
915    @Override
916    public long getPacketReplyTimeout() {
917        return packetReplyTimeout;
918    }
919
920    @Override
921    public void setPacketReplyTimeout(long timeout) {
922        packetReplyTimeout = timeout;
923    }
924
925    private static boolean replyToUnknownIqDefault = true;
926
927    /**
928     * Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured
929     * default is 'true'.
930     *
931     * @param replyToUnkownIqDefault
932     * @see #setReplyToUnknownIq(boolean)
933     */
934    public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) {
935        AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault;
936    }
937
938    private boolean replyToUnkownIq = replyToUnknownIqDefault;
939
940    /**
941     * Set if Smack will automatically send
942     * {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a
943     * registered {@link IQRequestHandler} is received.
944     *
945     * @param replyToUnknownIq
946     */
947    public void setReplyToUnknownIq(boolean replyToUnknownIq) {
948        this.replyToUnkownIq = replyToUnknownIq;
949    }
950
951    protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
952        ParserUtils.assertAtStartTag(parser);
953        int parserDepth = parser.getDepth();
954        Stanza stanza = null;
955        try {
956            stanza = PacketParserUtils.parseStanza(parser);
957        }
958        catch (Exception e) {
959            CharSequence content = PacketParserUtils.parseContentDepth(parser,
960                            parserDepth);
961            UnparsablePacket message = new UnparsablePacket(content, e);
962            ParsingExceptionCallback callback = getParsingExceptionCallback();
963            if (callback != null) {
964                callback.handleUnparsablePacket(message);
965            }
966        }
967        ParserUtils.assertAtEndTag(parser);
968        if (stanza != null) {
969            processPacket(stanza);
970        }
971    }
972
973    /**
974     * Processes a stanza(/packet) after it's been fully parsed by looping through the installed
975     * stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if
976     * they are a match with the filter.
977     *
978     * @param packet the stanza(/packet) to process.
979     */
980    protected void processPacket(Stanza packet) {
981        assert(packet != null);
982        lastStanzaReceived = System.currentTimeMillis();
983        // Deliver the incoming packet to listeners.
984        executorService.submit(new ListenerNotification(packet));
985    }
986
987    /**
988     * A runnable to notify all listeners and stanza(/packet) collectors of a packet.
989     */
990    private class ListenerNotification implements Runnable {
991
992        private final Stanza packet;
993
994        public ListenerNotification(Stanza packet) {
995            this.packet = packet;
996        }
997
998        public void run() {
999            invokePacketCollectorsAndNotifyRecvListeners(packet);
1000        }
1001    }
1002
1003    /**
1004     * Invoke {@link PacketCollector#processPacket(Stanza)} for every
1005     * PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet.
1006     *
1007     * @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about.
1008     */
1009    protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) {
1010        if (packet instanceof IQ) {
1011            final IQ iq = (IQ) packet;
1012            final IQ.Type type = iq.getType();
1013            switch (type) {
1014            case set:
1015            case get:
1016                final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
1017                IQRequestHandler iqRequestHandler = null;
1018                switch (type) {
1019                case set:
1020                    synchronized (setIqRequestHandler) {
1021                        iqRequestHandler = setIqRequestHandler.get(key);
1022                    }
1023                    break;
1024                case get:
1025                    synchronized (getIqRequestHandler) {
1026                        iqRequestHandler = getIqRequestHandler.get(key);
1027                    }
1028                    break;
1029                default:
1030                    throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
1031                }
1032                if (iqRequestHandler == null) {
1033                    if (!replyToUnkownIq) {
1034                        return;
1035                    }
1036                    // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
1037                    // IQ of type "error" with code 501 ("feature-not-implemented")
1038                    ErrorIQ errorIQ = IQ.createErrorResponse(iq, new XMPPError(
1039                                    XMPPError.Condition.feature_not_implemented));
1040                    try {
1041                        sendStanza(errorIQ);
1042                    }
1043                    catch (NotConnectedException e) {
1044                        LOGGER.log(Level.WARNING, "NotConnectedException while sending error IQ to unkown IQ request", e);
1045                    }
1046                } else {
1047                    ExecutorService executorService = null;
1048                    switch (iqRequestHandler.getMode()) {
1049                    case sync:
1050                        executorService = singleThreadedExecutorService;
1051                        break;
1052                    case async:
1053                        executorService = cachedExecutorService;
1054                        break;
1055                    }
1056                    final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
1057                    executorService.execute(new Runnable() {
1058                        @Override
1059                        public void run() {
1060                            IQ response = finalIqRequestHandler.handleIQRequest(iq);
1061                            if (response == null) {
1062                                // It is not ideal if the IQ request handler does not return an IQ response, because RFC
1063                                // 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
1064                                // file transfer one, does not always return a result, so we need to handle this case.
1065                                // Also sometimes a request handler may decide that it's better to not send a response,
1066                                // e.g. to avoid presence leaks.
1067                                return;
1068                            }
1069                            try {
1070                                sendStanza(response);
1071                            }
1072                            catch (NotConnectedException e) {
1073                                LOGGER.log(Level.WARNING, "NotConnectedException while sending response to IQ request", e);
1074                            }
1075                        }
1076                    });
1077                    // The following returns makes it impossible for packet listeners and collectors to
1078                    // filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
1079                    // desired behavior.
1080                    return;
1081                }
1082                break;
1083            default:
1084                break;
1085            }
1086        }
1087
1088        // First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
1089        // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
1090        // their own thread.
1091        final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
1092        synchronized (asyncRecvListeners) {
1093            for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
1094                if (listenerWrapper.filterMatches(packet)) {
1095                    listenersToNotify.add(listenerWrapper.getListener());
1096                }
1097            }
1098        }
1099
1100        for (final StanzaListener listener : listenersToNotify) {
1101            asyncGo(new Runnable() {
1102                @Override
1103                public void run() {
1104                    try {
1105                        listener.processPacket(packet);
1106                    } catch (Exception e) {
1107                        LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
1108                    }
1109                }
1110            });
1111        }
1112
1113        // Loop through all collectors and notify the appropriate ones.
1114        for (PacketCollector collector: collectors) {
1115            collector.processPacket(packet);
1116        }
1117
1118        // Notify the receive listeners interested in the packet
1119        listenersToNotify.clear();
1120        synchronized (syncRecvListeners) {
1121            for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
1122                if (listenerWrapper.filterMatches(packet)) {
1123                    listenersToNotify.add(listenerWrapper.getListener());
1124                }
1125            }
1126        }
1127
1128        // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
1129        // threaded executor service and therefore keeps the order.
1130        singleThreadedExecutorService.execute(new Runnable() {
1131            @Override
1132            public void run() {
1133                for (StanzaListener listener : listenersToNotify) {
1134                    try {
1135                        listener.processPacket(packet);
1136                    } catch(NotConnectedException e) {
1137                        LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
1138                        break;
1139                    } catch (Exception e) {
1140                        LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
1141                    }
1142                }
1143            }
1144        });
1145
1146    }
1147
1148    /**
1149     * Sets whether the connection has already logged in the server. This method assures that the
1150     * {@link #wasAuthenticated} flag is never reset once it has ever been set.
1151     * 
1152     */
1153    protected void setWasAuthenticated() {
1154        // Never reset the flag if the connection has ever been authenticated
1155        if (!wasAuthenticated) {
1156            wasAuthenticated = authenticated;
1157        }
1158    }
1159
1160    protected void callConnectionConnectedListener() {
1161        for (ConnectionListener listener : connectionListeners) {
1162            listener.connected(this);
1163        }
1164    }
1165
1166    protected void callConnectionAuthenticatedListener(boolean resumed) {
1167        for (ConnectionListener listener : connectionListeners) {
1168            try {
1169                listener.authenticated(this, resumed);
1170            } catch (Exception e) {
1171                // Catch and print any exception so we can recover
1172                // from a faulty listener and finish the shutdown process
1173                LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
1174            }
1175        }
1176    }
1177
1178    void callConnectionClosedListener() {
1179        for (ConnectionListener listener : connectionListeners) {
1180            try {
1181                listener.connectionClosed();
1182            }
1183            catch (Exception e) {
1184                // Catch and print any exception so we can recover
1185                // from a faulty listener and finish the shutdown process
1186                LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
1187            }
1188        }
1189    }
1190
1191    protected void callConnectionClosedOnErrorListener(Exception e) {
1192        LOGGER.log(Level.WARNING, "Connection closed with error", e);
1193        for (ConnectionListener listener : connectionListeners) {
1194            try {
1195                listener.connectionClosedOnError(e);
1196            }
1197            catch (Exception e2) {
1198                // Catch and print any exception so we can recover
1199                // from a faulty listener
1200                LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
1201            }
1202        }
1203    }
1204
1205    /**
1206     * Sends a notification indicating that the connection was reconnected successfully.
1207     */
1208    protected void notifyReconnection() {
1209        // Notify connection listeners of the reconnection.
1210        for (ConnectionListener listener : connectionListeners) {
1211            try {
1212                listener.reconnectionSuccessful();
1213            }
1214            catch (Exception e) {
1215                // Catch and print any exception so we can recover
1216                // from a faulty listener
1217                LOGGER.log(Level.WARNING, "notifyReconnection()", e);
1218            }
1219        }
1220    }
1221
1222    /**
1223     * A wrapper class to associate a stanza(/packet) filter with a listener.
1224     */
1225    protected static class ListenerWrapper {
1226
1227        private final StanzaListener packetListener;
1228        private final StanzaFilter packetFilter;
1229
1230        /**
1231         * Create a class which associates a stanza(/packet) filter with a listener.
1232         * 
1233         * @param packetListener the stanza(/packet) listener.
1234         * @param packetFilter the associated filter or null if it listen for all packets.
1235         */
1236        public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
1237            this.packetListener = packetListener;
1238            this.packetFilter = packetFilter;
1239        }
1240
1241        public boolean filterMatches(Stanza packet) {
1242            return packetFilter == null || packetFilter.accept(packet);
1243        }
1244
1245        public StanzaListener getListener() {
1246            return packetListener;
1247        }
1248    }
1249
1250    /**
1251     * A wrapper class to associate a stanza(/packet) filter with an interceptor.
1252     */
1253    protected static class InterceptorWrapper {
1254
1255        private final StanzaListener packetInterceptor;
1256        private final StanzaFilter packetFilter;
1257
1258        /**
1259         * Create a class which associates a stanza(/packet) filter with an interceptor.
1260         * 
1261         * @param packetInterceptor the interceptor.
1262         * @param packetFilter the associated filter or null if it intercepts all packets.
1263         */
1264        public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
1265            this.packetInterceptor = packetInterceptor;
1266            this.packetFilter = packetFilter;
1267        }
1268
1269        public boolean filterMatches(Stanza packet) {
1270            return packetFilter == null || packetFilter.accept(packet);
1271        }
1272
1273        public StanzaListener getInterceptor() {
1274            return packetInterceptor;
1275        }
1276    }
1277
1278    @Override
1279    public int getConnectionCounter() {
1280        return connectionCounterValue;
1281    }
1282
1283    @Override
1284    public void setFromMode(FromMode fromMode) {
1285        this.fromMode = fromMode;
1286    }
1287
1288    @Override
1289    public FromMode getFromMode() {
1290        return this.fromMode;
1291    }
1292
1293    @Override
1294    protected void finalize() throws Throwable {
1295        LOGGER.fine("finalizing XMPPConnection ( " + getConnectionCounter()
1296                        + "): Shutting down executor services");
1297        try {
1298            // It's usually not a good idea to rely on finalize. But this is the easiest way to
1299            // avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a
1300            // reference to their ExecutorService which prevents the ExecutorService from being
1301            // gc'ed. It is possible that the XMPPConnection instance is gc'ed while the
1302            // listenerExecutor ExecutorService call not be gc'ed until it got shut down.
1303            executorService.shutdownNow();
1304            cachedExecutorService.shutdown();
1305            removeCallbacksService.shutdownNow();
1306            singleThreadedExecutorService.shutdownNow();
1307        } catch (Throwable t) {
1308            LOGGER.log(Level.WARNING, "finalize() threw trhowable", t);
1309        }
1310        finally {
1311            super.finalize();
1312        }
1313    }
1314
1315    protected final void parseFeatures(XmlPullParser parser) throws XmlPullParserException,
1316                    IOException, SmackException {
1317        streamFeatures.clear();
1318        final int initialDepth = parser.getDepth();
1319        while (true) {
1320            int eventType = parser.next();
1321
1322            if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) {
1323                ExtensionElement streamFeature = null;
1324                String name = parser.getName();
1325                String namespace = parser.getNamespace();
1326                switch (name) {
1327                case StartTls.ELEMENT:
1328                    streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
1329                    break;
1330                case Mechanisms.ELEMENT:
1331                    streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
1332                    break;
1333                case Bind.ELEMENT:
1334                    streamFeature = Bind.Feature.INSTANCE;
1335                    break;
1336                case Session.ELEMENT:
1337                    streamFeature = PacketParserUtils.parseSessionFeature(parser);
1338                    break;
1339                case Compress.Feature.ELEMENT:
1340                    streamFeature = PacketParserUtils.parseCompressionFeature(parser);
1341                    break;
1342                default:
1343                    ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
1344                    if (provider != null) {
1345                        streamFeature = provider.parse(parser);
1346                    }
1347                    break;
1348                }
1349                if (streamFeature != null) {
1350                    addStreamFeature(streamFeature);
1351                }
1352            }
1353            else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) {
1354                break;
1355            }
1356        }
1357
1358        if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
1359            // Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
1360            if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
1361                            || config.getSecurityMode() == SecurityMode.disabled) {
1362                saslFeatureReceived.reportSuccess();
1363            }
1364        }
1365
1366        // If the server reported the bind feature then we are that that we did SASL and maybe
1367        // STARTTLS. We can then report that the last 'stream:features' have been parsed
1368        if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
1369            if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
1370                            || !config.isCompressionEnabled()) {
1371                // This was was last features from the server is either it did not contain
1372                // compression or if we disabled it
1373                lastFeaturesReceived.reportSuccess();
1374            }
1375        }
1376        afterFeaturesReceived();
1377    }
1378
1379    protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {
1380        // Default implementation does nothing
1381    }
1382
1383    @SuppressWarnings("unchecked")
1384    @Override
1385    public <F extends ExtensionElement> F getFeature(String element, String namespace) {
1386        return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace));
1387    }
1388
1389    @Override
1390    public boolean hasFeature(String element, String namespace) {
1391        return getFeature(element, namespace) != null;
1392    }
1393
1394    private void addStreamFeature(ExtensionElement feature) {
1395        String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace());
1396        streamFeatures.put(key, feature);
1397    }
1398
1399    @Override
1400    public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
1401                    StanzaListener callback) throws NotConnectedException {
1402        sendStanzaWithResponseCallback(stanza, replyFilter, callback, null);
1403    }
1404
1405    @Override
1406    public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
1407                    StanzaListener callback, ExceptionCallback exceptionCallback)
1408                    throws NotConnectedException {
1409        sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback,
1410                        getPacketReplyTimeout());
1411    }
1412
1413    @Override
1414    public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
1415                    final StanzaListener callback, final ExceptionCallback exceptionCallback,
1416                    long timeout) throws NotConnectedException {
1417        Objects.requireNonNull(stanza, "stanza must not be null");
1418        // While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
1419        // disallow it here in the async API as it makes no sense
1420        Objects.requireNonNull(replyFilter, "replyFilter must not be null");
1421        Objects.requireNonNull(callback, "callback must not be null");
1422
1423        final StanzaListener packetListener = new StanzaListener() {
1424            @Override
1425            public void processPacket(Stanza packet) throws NotConnectedException {
1426                try {
1427                    XMPPErrorException.ifHasErrorThenThrow(packet);
1428                    callback.processPacket(packet);
1429                }
1430                catch (XMPPErrorException e) {
1431                    if (exceptionCallback != null) {
1432                        exceptionCallback.processException(e);
1433                    }
1434                }
1435                finally {
1436                    removeAsyncStanzaListener(this);
1437                }
1438            }
1439        };
1440        removeCallbacksService.schedule(new Runnable() {
1441            @Override
1442            public void run() {
1443                boolean removed = removeAsyncStanzaListener(packetListener);
1444                // If the packetListener got removed, then it was never run and
1445                // we never received a response, inform the exception callback
1446                if (removed && exceptionCallback != null) {
1447                    exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter));
1448                }
1449            }
1450        }, timeout, TimeUnit.MILLISECONDS);
1451        addAsyncStanzaListener(packetListener, replyFilter);
1452        sendStanza(stanza);
1453    }
1454
1455    @Override
1456    public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback)
1457                    throws NotConnectedException {
1458        sendIqWithResponseCallback(iqRequest, callback, null);
1459    }
1460
1461    @Override
1462    public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback,
1463                    ExceptionCallback exceptionCallback) throws NotConnectedException {
1464        sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout());
1465    }
1466
1467    @Override
1468    public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback,
1469                    final ExceptionCallback exceptionCallback, long timeout)
1470                    throws NotConnectedException {
1471        StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this);
1472        sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout);
1473    }
1474
1475    @Override
1476    public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
1477        final StanzaListener packetListener = new StanzaListener() {
1478            @Override
1479            public void processPacket(Stanza packet) throws NotConnectedException {
1480                try {
1481                    callback.processPacket(packet);
1482                } finally {
1483                    removeSyncStanzaListener(this);
1484                }
1485            }
1486        };
1487        addSyncStanzaListener(packetListener, packetFilter);
1488        removeCallbacksService.schedule(new Runnable() {
1489            @Override
1490            public void run() {
1491                removeSyncStanzaListener(packetListener);
1492            }
1493        }, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
1494    }
1495
1496    @Override
1497    public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
1498        final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace());
1499        switch (iqRequestHandler.getType()) {
1500        case set:
1501            synchronized (setIqRequestHandler) {
1502                return setIqRequestHandler.put(key, iqRequestHandler);
1503            }
1504        case get:
1505            synchronized (getIqRequestHandler) {
1506                return getIqRequestHandler.put(key, iqRequestHandler);
1507            }
1508        default:
1509            throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
1510        }
1511    }
1512
1513    @Override
1514    public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
1515        return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
1516                        iqRequestHandler.getType());
1517    }
1518
1519    @Override
1520    public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
1521        final String key = XmppStringUtils.generateKey(element, namespace);
1522        switch (type) {
1523        case set:
1524            synchronized (setIqRequestHandler) {
1525                return setIqRequestHandler.remove(key);
1526            }
1527        case get:
1528            synchronized (getIqRequestHandler) {
1529                return getIqRequestHandler.remove(key);
1530            }
1531        default:
1532            throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
1533        }
1534    }
1535
1536    private long lastStanzaReceived;
1537
1538    public long getLastStanzaReceived() {
1539        return lastStanzaReceived;
1540    }
1541
1542    /**
1543     * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
1544     * stanza
1545     * 
1546     * @param callback the callback to install
1547     */
1548    public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
1549        parsingExceptionCallback = callback;
1550    }
1551
1552    /**
1553     * Get the current active parsing exception callback.
1554     *  
1555     * @return the active exception callback or null if there is none
1556     */
1557    public ParsingExceptionCallback getParsingExceptionCallback() {
1558        return parsingExceptionCallback;
1559    }
1560
1561    protected final void asyncGo(Runnable runnable) {
1562        cachedExecutorService.execute(runnable);
1563    }
1564
1565    protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
1566        return removeCallbacksService.schedule(runnable, delay, unit);
1567    }
1568}