001/**
002 *
003 * Copyright 2003-2007 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.tcp;
018
019import java.io.BufferedReader;
020import java.io.ByteArrayInputStream;
021import java.io.FileInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.InputStreamReader;
025import java.io.OutputStream;
026import java.io.OutputStreamWriter;
027import java.io.Writer;
028import java.lang.reflect.Constructor;
029import java.net.InetAddress;
030import java.net.InetSocketAddress;
031import java.net.Socket;
032import java.security.KeyManagementException;
033import java.security.KeyStore;
034import java.security.KeyStoreException;
035import java.security.NoSuchAlgorithmException;
036import java.security.NoSuchProviderException;
037import java.security.Provider;
038import java.security.SecureRandom;
039import java.security.Security;
040import java.security.UnrecoverableKeyException;
041import java.security.cert.CertificateException;
042import java.util.ArrayList;
043import java.util.Collection;
044import java.util.Iterator;
045import java.util.LinkedHashSet;
046import java.util.LinkedList;
047import java.util.List;
048import java.util.Map;
049import java.util.Set;
050import java.util.concurrent.ArrayBlockingQueue;
051import java.util.concurrent.BlockingQueue;
052import java.util.concurrent.ConcurrentHashMap;
053import java.util.concurrent.ConcurrentLinkedQueue;
054import java.util.concurrent.TimeUnit;
055import java.util.concurrent.atomic.AtomicBoolean;
056import java.util.logging.Level;
057import java.util.logging.Logger;
058
059import javax.net.SocketFactory;
060import javax.net.ssl.HostnameVerifier;
061import javax.net.ssl.KeyManager;
062import javax.net.ssl.KeyManagerFactory;
063import javax.net.ssl.SSLContext;
064import javax.net.ssl.SSLSession;
065import javax.net.ssl.SSLSocket;
066import javax.net.ssl.TrustManager;
067import javax.net.ssl.X509TrustManager;
068import javax.security.auth.callback.Callback;
069import javax.security.auth.callback.CallbackHandler;
070import javax.security.auth.callback.PasswordCallback;
071
072import org.jivesoftware.smack.AbstractConnectionListener;
073import org.jivesoftware.smack.AbstractXMPPConnection;
074import org.jivesoftware.smack.ConnectionConfiguration;
075import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode;
076import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
077import org.jivesoftware.smack.SmackConfiguration;
078import org.jivesoftware.smack.SmackException;
079import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
080import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
081import org.jivesoftware.smack.SmackException.ConnectionException;
082import org.jivesoftware.smack.SmackException.NoResponseException;
083import org.jivesoftware.smack.SmackException.NotConnectedException;
084import org.jivesoftware.smack.SmackException.NotLoggedInException;
085import org.jivesoftware.smack.SmackException.SecurityRequiredByServerException;
086import org.jivesoftware.smack.StanzaListener;
087import org.jivesoftware.smack.SynchronizationPoint;
088import org.jivesoftware.smack.XMPPConnection;
089import org.jivesoftware.smack.XMPPException;
090import org.jivesoftware.smack.XMPPException.FailedNonzaException;
091import org.jivesoftware.smack.XMPPException.StreamErrorException;
092import org.jivesoftware.smack.compress.packet.Compress;
093import org.jivesoftware.smack.compress.packet.Compressed;
094import org.jivesoftware.smack.compression.XMPPInputOutputStream;
095import org.jivesoftware.smack.filter.StanzaFilter;
096import org.jivesoftware.smack.packet.Element;
097import org.jivesoftware.smack.packet.IQ;
098import org.jivesoftware.smack.packet.Message;
099import org.jivesoftware.smack.packet.Nonza;
100import org.jivesoftware.smack.packet.Presence;
101import org.jivesoftware.smack.packet.Stanza;
102import org.jivesoftware.smack.packet.StartTls;
103import org.jivesoftware.smack.packet.StreamError;
104import org.jivesoftware.smack.packet.StreamOpen;
105import org.jivesoftware.smack.proxy.ProxyInfo;
106import org.jivesoftware.smack.sasl.packet.SaslStreamElements;
107import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Challenge;
108import org.jivesoftware.smack.sasl.packet.SaslStreamElements.SASLFailure;
109import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Success;
110import org.jivesoftware.smack.sm.SMUtils;
111import org.jivesoftware.smack.sm.StreamManagementException;
112import org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException;
113import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementCounterError;
114import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException;
115import org.jivesoftware.smack.sm.packet.StreamManagement;
116import org.jivesoftware.smack.sm.packet.StreamManagement.AckAnswer;
117import org.jivesoftware.smack.sm.packet.StreamManagement.AckRequest;
118import org.jivesoftware.smack.sm.packet.StreamManagement.Enable;
119import org.jivesoftware.smack.sm.packet.StreamManagement.Enabled;
120import org.jivesoftware.smack.sm.packet.StreamManagement.Failed;
121import org.jivesoftware.smack.sm.packet.StreamManagement.Resume;
122import org.jivesoftware.smack.sm.packet.StreamManagement.Resumed;
123import org.jivesoftware.smack.sm.packet.StreamManagement.StreamManagementFeature;
124import org.jivesoftware.smack.sm.predicates.Predicate;
125import org.jivesoftware.smack.sm.provider.ParseStreamManagement;
126import org.jivesoftware.smack.util.ArrayBlockingQueueWithShutdown;
127import org.jivesoftware.smack.util.Async;
128import org.jivesoftware.smack.util.DNSUtil;
129import org.jivesoftware.smack.util.PacketParserUtils;
130import org.jivesoftware.smack.util.StringUtils;
131import org.jivesoftware.smack.util.TLSUtils;
132import org.jivesoftware.smack.util.XmlStringBuilder;
133import org.jivesoftware.smack.util.dns.HostAddress;
134import org.jivesoftware.smack.util.dns.SmackDaneProvider;
135import org.jivesoftware.smack.util.dns.SmackDaneVerifier;
136
137import org.jxmpp.jid.impl.JidCreate;
138import org.jxmpp.jid.parts.Resourcepart;
139import org.jxmpp.stringprep.XmppStringprepException;
140import org.jxmpp.util.XmppStringUtils;
141import org.xmlpull.v1.XmlPullParser;
142import org.xmlpull.v1.XmlPullParserException;
143
144/**
145 * Creates a socket connection to an XMPP server. This is the default connection
146 * to an XMPP server and is specified in the XMPP Core (RFC 6120).
147 * 
148 * @see XMPPConnection
149 * @author Matt Tucker
150 */
151public class XMPPTCPConnection extends AbstractXMPPConnection {
152
153    private static final int QUEUE_SIZE = 500;
154    private static final Logger LOGGER = Logger.getLogger(XMPPTCPConnection.class.getName());
155
156    /**
157     * The socket which is used for this connection.
158     */
159    private Socket socket;
160
161    /**
162     * 
163     */
164    private boolean disconnectedButResumeable = false;
165
166    private SSLSocket secureSocket;
167
168    /**
169     * Protected access level because of unit test purposes
170     */
171    protected PacketWriter packetWriter;
172
173    /**
174     * Protected access level because of unit test purposes
175     */
176    protected PacketReader packetReader;
177
178    private final SynchronizationPoint<Exception> initialOpenStreamSend = new SynchronizationPoint<>(
179                    this, "initial open stream element send to server");
180
181    /**
182     * 
183     */
184    private final SynchronizationPoint<XMPPException> maybeCompressFeaturesReceived = new SynchronizationPoint<XMPPException>(
185                    this, "stream compression feature");
186
187    /**
188     * 
189     */
190    private final SynchronizationPoint<SmackException> compressSyncPoint = new SynchronizationPoint<>(
191                    this, "stream compression");
192
193    /**
194     * A synchronization point which is successful if this connection has received the closing
195     * stream element from the remote end-point, i.e. the server.
196     */
197    private final SynchronizationPoint<Exception> closingStreamReceived = new SynchronizationPoint<>(
198                    this, "stream closing element received");
199
200    /**
201     * The default bundle and defer callback, used for new connections.
202     * @see bundleAndDeferCallback
203     */
204    private static BundleAndDeferCallback defaultBundleAndDeferCallback;
205
206    /**
207     * The used bundle and defer callback.
208     * <p>
209     * Although this field may be set concurrently, the 'volatile' keyword was deliberately not added, in order to avoid
210     * having a 'volatile' read within the writer threads loop.
211     * </p>
212     */
213    private BundleAndDeferCallback bundleAndDeferCallback = defaultBundleAndDeferCallback;
214
215    private static boolean useSmDefault = true;
216
217    private static boolean useSmResumptionDefault = true;
218
219    /**
220     * The stream ID of the stream that is currently resumable, ie. the stream we hold the state
221     * for in {@link #clientHandledStanzasCount}, {@link #serverHandledStanzasCount} and
222     * {@link #unacknowledgedStanzas}.
223     */
224    private String smSessionId;
225
226    private final SynchronizationPoint<FailedNonzaException> smResumedSyncPoint = new SynchronizationPoint<>(
227                    this, "stream resumed element");
228
229    private final SynchronizationPoint<SmackException> smEnabledSyncPoint = new SynchronizationPoint<>(
230                    this, "stream enabled element");
231
232    /**
233     * The client's preferred maximum resumption time in seconds.
234     */
235    private int smClientMaxResumptionTime = -1;
236
237    /**
238     * The server's preferred maximum resumption time in seconds.
239     */
240    private int smServerMaxResumptionTime = -1;
241
242    /**
243     * Indicates whether Stream Management (XEP-198) should be used if it's supported by the server.
244     */
245    private boolean useSm = useSmDefault;
246    private boolean useSmResumption = useSmResumptionDefault;
247
248    /**
249     * The counter that the server sends the client about it's current height. For example, if the server sends
250     * {@code <a h='42'/>}, then this will be set to 42 (while also handling the {@link #unacknowledgedStanzas} queue).
251     */
252    private long serverHandledStanzasCount = 0;
253
254    /**
255     * The counter for stanzas handled ("received") by the client.
256     * <p>
257     * Note that we don't need to synchronize this counter. Although JLS 17.7 states that reads and writes to longs are
258     * not atomic, it guarantees that there are at most 2 separate writes, one to each 32-bit half. And since
259     * {@link SMUtils#incrementHeight(long)} masks the lower 32 bit, we only operate on one half of the long and
260     * therefore have no concurrency problem because the read/write operations on one half are guaranteed to be atomic.
261     * </p>
262     */
263    private long clientHandledStanzasCount = 0;
264
265    private BlockingQueue<Stanza> unacknowledgedStanzas;
266
267    /**
268     * Set to true if Stream Management was at least once enabled for this connection.
269     */
270    private boolean smWasEnabledAtLeastOnce = false;
271
272    /**
273     * This listeners are invoked for every stanza that got acknowledged.
274     * <p>
275     * We use a {@link ConccurrentLinkedQueue} here in order to allow the listeners to remove
276     * themselves after they have been invoked.
277     * </p>
278     */
279    private final Collection<StanzaListener> stanzaAcknowledgedListeners = new ConcurrentLinkedQueue<>();
280
281    /**
282     * This listeners are invoked for a acknowledged stanza that has the given stanza ID. They will
283     * only be invoked once and automatically removed after that.
284     */
285    private final Map<String, StanzaListener> stanzaIdAcknowledgedListeners = new ConcurrentHashMap<>();
286
287    /**
288     * Predicates that determine if an stream management ack should be requested from the server.
289     * <p>
290     * We use a linked hash set here, so that the order how the predicates are added matches the
291     * order in which they are invoked in order to determine if an ack request should be send or not.
292     * </p>
293     */
294    private final Set<StanzaFilter> requestAckPredicates = new LinkedHashSet<>();
295
296    private final XMPPTCPConnectionConfiguration config;
297
298    /**
299     * Creates a new XMPP connection over TCP (optionally using proxies).
300     * <p>
301     * Note that XMPPTCPConnection constructors do not establish a connection to the server
302     * and you must call {@link #connect()}.
303     * </p>
304     *
305     * @param config the connection configuration.
306     */
307    public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
308        super(config);
309        this.config = config;
310        addConnectionListener(new AbstractConnectionListener() {
311            @Override
312            public void connectionClosedOnError(Exception e) {
313                if (e instanceof XMPPException.StreamErrorException || e instanceof StreamManagementException) {
314                    dropSmState();
315                }
316            }
317        });
318    }
319
320    /**
321     * Creates a new XMPP connection over TCP.
322     * <p>
323     * Note that {@code jid} must be the bare JID, e.g. "user@example.org". More fine-grained control over the
324     * connection settings is available using the {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)}
325     * constructor.
326     * </p>
327     * 
328     * @param jid the bare JID used by the client.
329     * @param password the password or authentication token.
330     * @throws XmppStringprepException 
331     */
332    public XMPPTCPConnection(CharSequence jid, String password) throws XmppStringprepException {
333        this(XmppStringUtils.parseLocalpart(jid.toString()), password, XmppStringUtils.parseDomain(jid.toString()));
334    }
335
336    /**
337     * Creates a new XMPP connection over TCP.
338     * <p>
339     * This is the simplest constructor for connecting to an XMPP server. Alternatively,
340     * you can get fine-grained control over connection settings using the
341     * {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)} constructor.
342     * </p>
343     * @param username
344     * @param password
345     * @param serviceName
346     * @throws XmppStringprepException 
347     */
348    public XMPPTCPConnection(CharSequence username, String password, String serviceName) throws XmppStringprepException {
349        this(XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setXmppDomain(
350                                        JidCreate.domainBareFrom(serviceName)).build());
351    }
352
353    @Override
354    protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
355        if (packetWriter == null) {
356            throw new NotConnectedException();
357        }
358        packetWriter.throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
359    }
360
361    @Override
362    protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
363        if (isConnected() && !disconnectedButResumeable) {
364            throw new AlreadyConnectedException();
365        }
366    }
367
368    @Override
369    protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
370        if (isAuthenticated() && !disconnectedButResumeable) {
371            throw new AlreadyLoggedInException();
372        }
373    }
374
375    @Override
376    protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException, InterruptedException {
377        // Reset the flag in case it was set
378        disconnectedButResumeable = false;
379        super.afterSuccessfulLogin(resumed);
380    }
381
382    @Override
383    protected synchronized void loginInternal(String username, String password, Resourcepart resource) throws XMPPException,
384                    SmackException, IOException, InterruptedException {
385        // Authenticate using SASL
386        SSLSession sslSession = secureSocket != null ? secureSocket.getSession() : null;
387        saslAuthentication.authenticate(username, password, config.getAuthzid(), sslSession);
388
389        // If compression is enabled then request the server to use stream compression. XEP-170
390        // recommends to perform stream compression before resource binding.
391        maybeEnableCompression();
392
393        if (isSmResumptionPossible()) {
394            smResumedSyncPoint.sendAndWaitForResponse(new Resume(clientHandledStanzasCount, smSessionId));
395            if (smResumedSyncPoint.wasSuccessful()) {
396                // We successfully resumed the stream, be done here
397                afterSuccessfulLogin(true);
398                return;
399            }
400            // SM resumption failed, what Smack does here is to report success of
401            // lastFeaturesReceived in case of sm resumption was answered with 'failed' so that
402            // normal resource binding can be tried.
403            LOGGER.fine("Stream resumption failed, continuing with normal stream establishment process");
404        }
405
406        List<Stanza> previouslyUnackedStanzas = new LinkedList<Stanza>();
407        if (unacknowledgedStanzas != null) {
408            // There was a previous connection with SM enabled but that was either not resumable or
409            // failed to resume. Make sure that we (re-)send the unacknowledged stanzas.
410            unacknowledgedStanzas.drainTo(previouslyUnackedStanzas);
411            // Reset unacknowledged stanzas to 'null' to signal that we never send 'enable' in this
412            // XMPP session (There maybe was an enabled in a previous XMPP session of this
413            // connection instance though). This is used in writePackets to decide if stanzas should
414            // be added to the unacknowledged stanzas queue, because they have to be added right
415            // after the 'enable' stream element has been sent.
416            dropSmState();
417        }
418
419        // Now bind the resource. It is important to do this *after* we dropped an eventually
420        // existing Stream Management state. As otherwise <bind/> and <session/> may end up in
421        // unacknowledgedStanzas and become duplicated on reconnect. See SMACK-706.
422        bindResourceAndEstablishSession(resource);
423
424        if (isSmAvailable() && useSm) {
425            // Remove what is maybe left from previously stream managed sessions
426            serverHandledStanzasCount = 0;
427            // XEP-198 3. Enabling Stream Management. If the server response to 'Enable' is 'Failed'
428            // then this is a non recoverable error and we therefore throw an exception.
429            smEnabledSyncPoint.sendAndWaitForResponseOrThrow(new Enable(useSmResumption, smClientMaxResumptionTime));
430            synchronized (requestAckPredicates) {
431                if (requestAckPredicates.isEmpty()) {
432                    // Assure that we have at lest one predicate set up that so that we request acks
433                    // for the server and eventually flush some stanzas from the unacknowledged
434                    // stanza queue
435                    requestAckPredicates.add(Predicate.forMessagesOrAfter5Stanzas());
436                }
437            }
438        }
439        // (Re-)send the stanzas *after* we tried to enable SM
440        for (Stanza stanza : previouslyUnackedStanzas) {
441            sendStanzaInternal(stanza);
442        }
443
444        afterSuccessfulLogin(false);
445    }
446
447    @Override
448    public boolean isSecureConnection() {
449        return secureSocket != null;
450    }
451
452    /**
453     * Shuts the current connection down. After this method returns, the connection must be ready
454     * for re-use by connect.
455     */
456    @Override
457    protected void shutdown() {
458        if (isSmEnabled()) {
459            try {
460                // Try to send a last SM Acknowledgement. Most servers won't find this information helpful, as the SM
461                // state is dropped after a clean disconnect anyways. OTOH it doesn't hurt much either.
462                sendSmAcknowledgementInternal();
463            } catch (InterruptedException | NotConnectedException e) {
464                LOGGER.log(Level.FINE, "Can not send final SM ack as connection is not connected", e);
465            }
466        }
467        shutdown(false);
468    }
469
470    /**
471     * Performs an unclean disconnect and shutdown of the connection. Does not send a closing stream stanza.
472     */
473    public synchronized void instantShutdown() {
474        shutdown(true);
475    }
476
477    private void shutdown(boolean instant) {
478        if (disconnectedButResumeable) {
479            return;
480        }
481
482        // First shutdown the writer, this will result in a closing stream element getting send to
483        // the server
484        if (packetWriter != null) {
485            LOGGER.finer("PacketWriter shutdown()");
486            packetWriter.shutdown(instant);
487        }
488        LOGGER.finer("PacketWriter has been shut down");
489
490        if (!instant) {
491            try {
492                // After we send the closing stream element, check if there was already a
493                // closing stream element sent by the server or wait with a timeout for a
494                // closing stream element to be received from the server.
495                @SuppressWarnings("unused")
496                Exception res = closingStreamReceived.checkIfSuccessOrWait();
497            } catch (InterruptedException | NoResponseException e) {
498                LOGGER.log(Level.INFO, "Exception while waiting for closing stream element from the server " + this, e);
499            }
500        }
501
502        if (packetReader != null) {
503            LOGGER.finer("PacketReader shutdown()");
504                packetReader.shutdown();
505        }
506        LOGGER.finer("PacketReader has been shut down");
507
508        try {
509                socket.close();
510        } catch (Exception e) {
511                LOGGER.log(Level.WARNING, "shutdown", e);
512        }
513
514        setWasAuthenticated();
515        // If we are able to resume the stream, then don't set
516        // connected/authenticated/usingTLS to false since we like behave like we are still
517        // connected (e.g. sendStanza should not throw a NotConnectedException).
518        if (isSmResumptionPossible() && instant) {
519            disconnectedButResumeable = true;
520        } else {
521            disconnectedButResumeable = false;
522            // Reset the stream management session id to null, since if the stream is cleanly closed, i.e. sending a closing
523            // stream tag, there is no longer a stream to resume.
524            smSessionId = null;
525        }
526        authenticated = false;
527        connected = false;
528        secureSocket = null;
529        reader = null;
530        writer = null;
531
532        maybeCompressFeaturesReceived.init();
533        compressSyncPoint.init();
534        smResumedSyncPoint.init();
535        smEnabledSyncPoint.init();
536        initialOpenStreamSend.init();
537    }
538
539    @Override
540    public void sendNonza(Nonza element) throws NotConnectedException, InterruptedException {
541        packetWriter.sendStreamElement(element);
542    }
543
544    @Override
545    protected void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException {
546        packetWriter.sendStreamElement(packet);
547        if (isSmEnabled()) {
548            for (StanzaFilter requestAckPredicate : requestAckPredicates) {
549                if (requestAckPredicate.accept(packet)) {
550                    requestSmAcknowledgementInternal();
551                    break;
552                }
553            }
554        }
555    }
556
557    private void connectUsingConfiguration() throws ConnectionException, IOException {
558        List<HostAddress> failedAddresses = populateHostAddresses();
559        SocketFactory socketFactory = config.getSocketFactory();
560        ProxyInfo proxyInfo = config.getProxyInfo();
561        int timeout = config.getConnectTimeout();
562        if (socketFactory == null) {
563            socketFactory = SocketFactory.getDefault();
564        }
565        for (HostAddress hostAddress : hostAddresses) {
566            Iterator<InetAddress> inetAddresses;
567            String host = hostAddress.getHost();
568            int port = hostAddress.getPort();
569            if (proxyInfo == null) {
570                inetAddresses = hostAddress.getInetAddresses().iterator();
571                assert (inetAddresses.hasNext());
572
573                innerloop: while (inetAddresses.hasNext()) {
574                    // Create a *new* Socket before every connection attempt, i.e. connect() call, since Sockets are not
575                    // re-usable after a failed connection attempt. See also SMACK-724.
576                    socket = socketFactory.createSocket();
577
578                    final InetAddress inetAddress = inetAddresses.next();
579                    final String inetAddressAndPort = inetAddress + " at port " + port;
580                    LOGGER.finer("Trying to establish TCP connection to " + inetAddressAndPort);
581                    try {
582                        socket.connect(new InetSocketAddress(inetAddress, port), timeout);
583                    } catch (Exception e) {
584                        hostAddress.setException(inetAddress, e);
585                        if (inetAddresses.hasNext()) {
586                            continue innerloop;
587                        } else {
588                            break innerloop;
589                        }
590                    }
591                    LOGGER.finer("Established TCP connection to " + inetAddressAndPort);
592                    // We found a host to connect to, return here
593                    this.host = host;
594                    this.port = port;
595                    return;
596                }
597                failedAddresses.add(hostAddress);
598            } else {
599                socket = socketFactory.createSocket();
600                StringUtils.requireNotNullOrEmpty(host, "Host of HostAddress " + hostAddress + " must not be null when using a Proxy");
601                final String hostAndPort = host + " at port " + port;
602                LOGGER.finer("Trying to establish TCP connection via Proxy to " + hostAndPort);
603                try {
604                    proxyInfo.getProxySocketConnection().connect(socket, host, port, timeout);
605                } catch (IOException e) {
606                    hostAddress.setException(e);
607                    continue;
608                }
609                LOGGER.finer("Established TCP connection to " + hostAndPort);
610                // We found a host to connect to, return here
611                this.host = host;
612                this.port = port;
613                return;
614            }
615        }
616        // There are no more host addresses to try
617        // throw an exception and report all tried
618        // HostAddresses in the exception
619        throw ConnectionException.from(failedAddresses);
620    }
621
622    /**
623     * Initializes the connection by creating a stanza(/packet) reader and writer and opening a
624     * XMPP stream to the server.
625     *
626     * @throws XMPPException if establishing a connection to the server fails.
627     * @throws SmackException if the server fails to respond back or if there is anther error.
628     * @throws IOException 
629     */
630    private void initConnection() throws IOException {
631        boolean isFirstInitialization = packetReader == null || packetWriter == null;
632        compressionHandler = null;
633
634        // Set the reader and writer instance variables
635        initReaderAndWriter();
636
637        if (isFirstInitialization) {
638            packetWriter = new PacketWriter();
639            packetReader = new PacketReader();
640
641            // If debugging is enabled, we should start the thread that will listen for
642            // all packets and then log them.
643            if (config.isDebuggerEnabled()) {
644                addAsyncStanzaListener(debugger.getReaderListener(), null);
645                if (debugger.getWriterListener() != null) {
646                    addPacketSendingListener(debugger.getWriterListener(), null);
647                }
648            }
649        }
650        // Start the packet writer. This will open an XMPP stream to the server
651        packetWriter.init();
652        // Start the packet reader. The startup() method will block until we
653        // get an opening stream packet back from server
654        packetReader.init();
655    }
656
657    private void initReaderAndWriter() throws IOException {
658        InputStream is = socket.getInputStream();
659        OutputStream os = socket.getOutputStream();
660        if (compressionHandler != null) {
661            is = compressionHandler.getInputStream(is);
662            os = compressionHandler.getOutputStream(os);
663        }
664        // OutputStreamWriter is already buffered, no need to wrap it into a BufferedWriter
665        writer = new OutputStreamWriter(os, "UTF-8");
666        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
667
668        // If debugging is enabled, we open a window and write out all network traffic.
669        initDebugger();
670    }
671
672    /**
673     * The server has indicated that TLS negotiation can start. We now need to secure the
674     * existing plain connection and perform a handshake. This method won't return until the
675     * connection has finished the handshake or an error occurred while securing the connection.
676     * @throws IOException 
677     * @throws CertificateException 
678     * @throws NoSuchAlgorithmException 
679     * @throws NoSuchProviderException 
680     * @throws KeyStoreException 
681     * @throws UnrecoverableKeyException 
682     * @throws KeyManagementException 
683     * @throws SmackException 
684     * @throws Exception if an exception occurs.
685     */
686    private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
687        SmackDaneVerifier daneVerifier = null;
688
689        if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
690            SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
691            if (daneProvider == null) {
692                throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
693            }
694            daneVerifier = daneProvider.newInstance();
695            if (daneVerifier == null) {
696                throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
697            }
698        }
699
700        SSLContext context = this.config.getCustomSSLContext();
701        KeyStore ks = null;
702        PasswordCallback pcb = null;
703
704        if (context == null) {
705            final String keyStoreType = config.getKeystoreType();
706            final CallbackHandler callbackHandler = config.getCallbackHandler();
707            final String keystorePath = config.getKeystorePath();
708            if ("PKCS11".equals(keyStoreType)) {
709                try {
710                    Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
711                    String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
712                    ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8));
713                    Provider p = (Provider) c.newInstance(config);
714                    Security.addProvider(p);
715                    ks = KeyStore.getInstance("PKCS11",p);
716                    pcb = new PasswordCallback("PKCS11 Password: ",false);
717                    callbackHandler.handle(new Callback[] {pcb});
718                    ks.load(null,pcb.getPassword());
719                }
720                catch (Exception e) {
721                    LOGGER.log(Level.WARNING, "Exception", e);
722                    ks = null;
723                }
724            }
725            else if ("Apple".equals(keyStoreType)) {
726                ks = KeyStore.getInstance("KeychainStore","Apple");
727                ks.load(null,null);
728                // pcb = new PasswordCallback("Apple Keychain",false);
729                // pcb.setPassword(null);
730            }
731            else if (keyStoreType != null) {
732                ks = KeyStore.getInstance(keyStoreType);
733                if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
734                    try {
735                        pcb = new PasswordCallback("Keystore Password: ", false);
736                        callbackHandler.handle(new Callback[] { pcb });
737                        ks.load(new FileInputStream(keystorePath), pcb.getPassword());
738                    }
739                    catch (Exception e) {
740                        LOGGER.log(Level.WARNING, "Exception", e);
741                        ks = null;
742                    }
743                } else {
744                    ks.load(null, null);
745                }
746            }
747
748            KeyManager[] kms = null;
749
750            if (ks != null) {
751                String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
752                KeyManagerFactory kmf = null;
753                try {
754                    kmf = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
755                }
756                catch (NoSuchAlgorithmException e) {
757                    LOGGER.log(Level.FINE, "Could get the default KeyManagerFactory for the '"
758                                    + keyManagerFactoryAlgorithm + "' algorithm", e);
759                }
760                if (kmf != null) {
761                    try {
762                        if (pcb == null) {
763                            kmf.init(ks, null);
764                        }
765                        else {
766                            kmf.init(ks, pcb.getPassword());
767                            pcb.clearPassword();
768                        }
769                        kms = kmf.getKeyManagers();
770                    }
771                    catch (NullPointerException npe) {
772                        LOGGER.log(Level.WARNING, "NullPointerException", npe);
773                    }
774                }
775            }
776
777            // If the user didn't specify a SSLContext, use the default one
778            context = SSLContext.getInstance("TLS");
779
780            final SecureRandom secureRandom = new java.security.SecureRandom();
781            X509TrustManager customTrustManager = config.getCustomX509TrustManager();
782
783            if (daneVerifier != null) {
784                // User requested DANE verification.
785                daneVerifier.init(context, kms, customTrustManager, secureRandom);
786            } else {
787                TrustManager[] customTrustManagers = null;
788                if (customTrustManager != null) {
789                    customTrustManagers = new TrustManager[] { customTrustManager };
790                }
791                context.init(kms, customTrustManagers, secureRandom);
792            }
793        }
794
795        Socket plain = socket;
796        // Secure the plain connection
797        socket = context.getSocketFactory().createSocket(plain,
798                host, plain.getPort(), true);
799
800        final SSLSocket sslSocket = (SSLSocket) socket;
801        // Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
802        // important (at least on certain platforms) and it seems to be a good idea anyways to
803        // prevent an accidental implicit handshake.
804        TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
805
806        // Initialize the reader and writer with the new secured version
807        initReaderAndWriter();
808
809        // Proceed to do the handshake
810        sslSocket.startHandshake();
811
812        if (daneVerifier != null) {
813            daneVerifier.finish(sslSocket);
814        }
815
816        final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
817        if (verifier == null) {
818                throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
819        } else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
820            throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
821        }
822
823        // Set that TLS was successful
824        secureSocket = sslSocket;
825    }
826
827    /**
828     * Returns the compression handler that can be used for one compression methods offered by the server.
829     * 
830     * @return a instance of XMPPInputOutputStream or null if no suitable instance was found
831     * 
832     */
833    private static XMPPInputOutputStream maybeGetCompressionHandler(Compress.Feature compression) {
834        for (XMPPInputOutputStream handler : SmackConfiguration.getCompressionHandlers()) {
835                String method = handler.getCompressionMethod();
836                if (compression.getMethods().contains(method))
837                    return handler;
838        }
839        return null;
840    }
841
842    @Override
843    public boolean isUsingCompression() {
844        return compressionHandler != null && compressSyncPoint.wasSuccessful();
845    }
846
847    /**
848     * <p>
849     * Starts using stream compression that will compress network traffic. Traffic can be
850     * reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
851     * connection. However, the server and the client will need to use more CPU time in order to
852     * un/compress network data so under high load the server performance might be affected.
853     * </p>
854     * <p>
855     * Stream compression has to have been previously offered by the server. Currently only the
856     * zlib method is supported by the client. Stream compression negotiation has to be done
857     * before authentication took place.
858     * </p>
859     *
860     * @throws NotConnectedException 
861     * @throws SmackException
862     * @throws NoResponseException 
863     * @throws InterruptedException 
864     */
865    private void maybeEnableCompression() throws SmackException, InterruptedException {
866        if (!config.isCompressionEnabled()) {
867            return;
868        }
869        maybeCompressFeaturesReceived.checkIfSuccessOrWait();
870        Compress.Feature compression = getFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE);
871        if (compression == null) {
872            // Server does not support compression
873            return;
874        }
875        // If stream compression was offered by the server and we want to use
876        // compression then send compression request to the server
877        if ((compressionHandler = maybeGetCompressionHandler(compression)) != null) {
878            compressSyncPoint.sendAndWaitForResponseOrThrow(new Compress(compressionHandler.getCompressionMethod()));
879        } else {
880            LOGGER.warning("Could not enable compression because no matching handler/method pair was found");
881        }
882    }
883
884    /**
885     * Establishes a connection to the XMPP server. It basically
886     * creates and maintains a socket connection to the server.
887     * <p>
888     * Listeners will be preserved from a previous connection if the reconnection
889     * occurs after an abrupt termination.
890     * </p>
891     *
892     * @throws XMPPException if an error occurs while trying to establish the connection.
893     * @throws SmackException 
894     * @throws IOException 
895     * @throws InterruptedException 
896     */
897    @Override
898    protected void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException {
899        closingStreamReceived.init();
900        // Establishes the TCP connection to the server and does setup the reader and writer. Throws an exception if
901        // there is an error establishing the connection
902        connectUsingConfiguration();
903
904        // We connected successfully to the servers TCP port
905        initConnection();
906    }
907
908    /**
909     * Sends out a notification that there was an error with the connection
910     * and closes the connection. Also prints the stack trace of the given exception
911     *
912     * @param e the exception that causes the connection close event.
913     */
914    private synchronized void notifyConnectionError(Exception e) {
915        // Listeners were already notified of the exception, return right here.
916        if ((packetReader == null || packetReader.done) &&
917                (packetWriter == null || packetWriter.done())) return;
918
919        // Closes the connection temporary. A reconnection is possible
920        // Note that a connection listener of XMPPTCPConnection will drop the SM state in
921        // case the Exception is a StreamErrorException.
922        instantShutdown();
923
924        // Notify connection listeners of the error.
925        callConnectionClosedOnErrorListener(e);
926    }
927
928    /**
929     * For unit testing purposes
930     *
931     * @param writer
932     */
933    protected void setWriter(Writer writer) {
934        this.writer = writer;
935    }
936
937    @Override
938    protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException {
939        StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
940        if (startTlsFeature != null) {
941            if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
942                SmackException smackException = new SecurityRequiredByServerException();
943                tlsHandled.reportFailure(smackException);
944                notifyConnectionError(smackException);
945                return;
946            }
947
948            if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
949                sendNonza(new StartTls());
950            } else {
951                tlsHandled.reportSuccess();
952            }
953        } else {
954            tlsHandled.reportSuccess();
955        }
956
957        if (getSASLAuthentication().authenticationSuccessful()) {
958            // If we have received features after the SASL has been successfully completed, then we
959            // have also *maybe* received, as it is an optional feature, the compression feature
960            // from the server.
961            maybeCompressFeaturesReceived.reportSuccess();
962        }
963    }
964
965    /**
966     * Resets the parser using the latest connection's reader. Resetting the parser is necessary
967     * when the plain connection has been secured or when a new opening stream element is going
968     * to be sent by the server.
969     *
970     * @throws SmackException if the parser could not be reset.
971     * @throws InterruptedException 
972     */
973    void openStream() throws SmackException, InterruptedException {
974        // If possible, provide the receiving entity of the stream open tag, i.e. the server, as much information as
975        // possible. The 'to' attribute is *always* available. The 'from' attribute if set by the user and no external
976        // mechanism is used to determine the local entity (user). And the 'id' attribute is available after the first
977        // response from the server (see e.g. RFC 6120 ยง 9.1.1 Step 2.)
978        CharSequence to = getXMPPServiceDomain();
979        CharSequence from = null;
980        CharSequence localpart = config.getUsername();
981        if (localpart != null) {
982            from = XmppStringUtils.completeJidFrom(localpart, to);
983        }
984        String id = getStreamId();
985        sendNonza(new StreamOpen(to, from, id));
986        try {
987            packetReader.parser = PacketParserUtils.newXmppParser(reader);
988        }
989        catch (XmlPullParserException e) {
990            throw new SmackException(e);
991        }
992    }
993
994    protected class PacketReader {
995
996        XmlPullParser parser;
997
998        private volatile boolean done;
999
1000        /**
1001         * Initializes the reader in order to be used. The reader is initialized during the
1002         * first connection and when reconnecting due to an abruptly disconnection.
1003         */
1004        void init() {
1005            done = false;
1006
1007            Async.go(new Runnable() {
1008                @Override
1009                public void run() {
1010                    parsePackets();
1011                }
1012            }, "Smack Packet Reader (" + getConnectionCounter() + ")");
1013         }
1014
1015        /**
1016         * Shuts the stanza(/packet) reader down. This method simply sets the 'done' flag to true.
1017         */
1018        void shutdown() {
1019            done = true;
1020        }
1021
1022        /**
1023         * Parse top-level packets in order to process them further.
1024         */
1025        private void parsePackets() {
1026            try {
1027                initialOpenStreamSend.checkIfSuccessOrWait();
1028                int eventType = parser.getEventType();
1029                while (!done) {
1030                    switch (eventType) {
1031                    case XmlPullParser.START_TAG:
1032                        final String name = parser.getName();
1033                        switch (name) {
1034                        case Message.ELEMENT:
1035                        case IQ.IQ_ELEMENT:
1036                        case Presence.ELEMENT:
1037                            try {
1038                                parseAndProcessStanza(parser);
1039                            } finally {
1040                                clientHandledStanzasCount = SMUtils.incrementHeight(clientHandledStanzasCount);
1041                            }
1042                            break;
1043                        case "stream":
1044                            // We found an opening stream.
1045                            if ("jabber:client".equals(parser.getNamespace(null))) {
1046                                streamId = parser.getAttributeValue("", "id");
1047                                String reportedServerDomain = parser.getAttributeValue("", "from");
1048                                assert (config.getXMPPServiceDomain().equals(reportedServerDomain));
1049                            }
1050                            break;
1051                        case "error":
1052                            StreamError streamError = PacketParserUtils.parseStreamError(parser);
1053                            saslFeatureReceived.reportFailure(new StreamErrorException(streamError));
1054                            // Mark the tlsHandled sync point as success, we will use the saslFeatureReceived sync
1055                            // point to report the error, which is checked immediately after tlsHandled in
1056                            // connectInternal().
1057                            tlsHandled.reportSuccess();
1058                            throw new StreamErrorException(streamError);
1059                        case "features":
1060                            parseFeatures(parser);
1061                            break;
1062                        case "proceed":
1063                            try {
1064                                // Secure the connection by negotiating TLS
1065                                proceedTLSReceived();
1066                                // Send a new opening stream to the server
1067                                openStream();
1068                            }
1069                            catch (Exception e) {
1070                                SmackException smackException = new SmackException(e);
1071                                tlsHandled.reportFailure(smackException);
1072                                throw e;
1073                            }
1074                            break;
1075                        case "failure":
1076                            String namespace = parser.getNamespace(null);
1077                            switch (namespace) {
1078                            case "urn:ietf:params:xml:ns:xmpp-tls":
1079                                // TLS negotiation has failed. The server will close the connection
1080                                // TODO Parse failure stanza
1081                                throw new SmackException("TLS negotiation has failed");
1082                            case "http://jabber.org/protocol/compress":
1083                                // Stream compression has been denied. This is a recoverable
1084                                // situation. It is still possible to authenticate and
1085                                // use the connection but using an uncompressed connection
1086                                // TODO Parse failure stanza
1087                                compressSyncPoint.reportFailure(new SmackException(
1088                                                "Could not establish compression"));
1089                                break;
1090                            case SaslStreamElements.NAMESPACE:
1091                                // SASL authentication has failed. The server may close the connection
1092                                // depending on the number of retries
1093                                final SASLFailure failure = PacketParserUtils.parseSASLFailure(parser);
1094                                getSASLAuthentication().authenticationFailed(failure);
1095                                break;
1096                            }
1097                            break;
1098                        case Challenge.ELEMENT:
1099                            // The server is challenging the SASL authentication made by the client
1100                            String challengeData = parser.nextText();
1101                            getSASLAuthentication().challengeReceived(challengeData);
1102                            break;
1103                        case Success.ELEMENT:
1104                            Success success = new Success(parser.nextText());
1105                            // We now need to bind a resource for the connection
1106                            // Open a new stream and wait for the response
1107                            openStream();
1108                            // The SASL authentication with the server was successful. The next step
1109                            // will be to bind the resource
1110                            getSASLAuthentication().authenticated(success);
1111                            break;
1112                        case Compressed.ELEMENT:
1113                            // Server confirmed that it's possible to use stream compression. Start
1114                            // stream compression
1115                            // Initialize the reader and writer with the new compressed version
1116                            initReaderAndWriter();
1117                            // Send a new opening stream to the server
1118                            openStream();
1119                            // Notify that compression is being used
1120                            compressSyncPoint.reportSuccess();
1121                            break;
1122                        case Enabled.ELEMENT:
1123                            Enabled enabled = ParseStreamManagement.enabled(parser);
1124                            if (enabled.isResumeSet()) {
1125                                smSessionId = enabled.getId();
1126                                if (StringUtils.isNullOrEmpty(smSessionId)) {
1127                                    SmackException xmppException = new SmackException("Stream Management 'enabled' element with resume attribute but without session id received");
1128                                    smEnabledSyncPoint.reportFailure(xmppException);
1129                                    throw xmppException;
1130                                }
1131                                smServerMaxResumptionTime = enabled.getMaxResumptionTime();
1132                            } else {
1133                                // Mark this a non-resumable stream by setting smSessionId to null
1134                                smSessionId = null;
1135                            }
1136                            clientHandledStanzasCount = 0;
1137                            smWasEnabledAtLeastOnce = true;
1138                            smEnabledSyncPoint.reportSuccess();
1139                            LOGGER.fine("Stream Management (XEP-198): successfully enabled");
1140                            break;
1141                        case Failed.ELEMENT:
1142                            Failed failed = ParseStreamManagement.failed(parser);
1143                            FailedNonzaException xmppException = new FailedNonzaException(failed, failed.getXMPPErrorCondition());
1144                            // If only XEP-198 would specify different failure elements for the SM
1145                            // enable and SM resume failure case. But this is not the case, so we
1146                            // need to determine if this is a 'Failed' response for either 'Enable'
1147                            // or 'Resume'.
1148                            if (smResumedSyncPoint.requestSent()) {
1149                                smResumedSyncPoint.reportFailure(xmppException);
1150                            }
1151                            else {
1152                                if (!smEnabledSyncPoint.requestSent()) {
1153                                    throw new IllegalStateException("Failed element received but SM was not previously enabled");
1154                                }
1155                                smEnabledSyncPoint.reportFailure(new SmackException(xmppException));
1156                                // Report success for last lastFeaturesReceived so that in case a
1157                                // failed resumption, we can continue with normal resource binding.
1158                                // See text of XEP-198 5. below Example 11.
1159                                lastFeaturesReceived.reportSuccess();
1160                            }
1161                            break;
1162                        case Resumed.ELEMENT:
1163                            Resumed resumed = ParseStreamManagement.resumed(parser);
1164                            if (!smSessionId.equals(resumed.getPrevId())) {
1165                                throw new StreamIdDoesNotMatchException(smSessionId, resumed.getPrevId());
1166                            }
1167                            // Mark SM as enabled
1168                            smEnabledSyncPoint.reportSuccess();
1169                            // First, drop the stanzas already handled by the server
1170                            processHandledCount(resumed.getHandledCount());
1171                            // Then re-send what is left in the unacknowledged queue
1172                            List<Stanza> stanzasToResend = new ArrayList<>(unacknowledgedStanzas.size());
1173                            unacknowledgedStanzas.drainTo(stanzasToResend);
1174                            for (Stanza stanza : stanzasToResend) {
1175                                sendStanzaInternal(stanza);
1176                            }
1177                            // If there where stanzas resent, then request a SM ack for them.
1178                            // Writer's sendStreamElement() won't do it automatically based on
1179                            // predicates.
1180                            if (!stanzasToResend.isEmpty()) {
1181                                requestSmAcknowledgementInternal();
1182                            }
1183                            // Mark SM resumption as successful
1184                            smResumedSyncPoint.reportSuccess();
1185                            LOGGER.fine("Stream Management (XEP-198): Stream resumed");
1186                            break;
1187                        case AckAnswer.ELEMENT:
1188                            AckAnswer ackAnswer = ParseStreamManagement.ackAnswer(parser);
1189                            processHandledCount(ackAnswer.getHandledCount());
1190                            break;
1191                        case AckRequest.ELEMENT:
1192                            ParseStreamManagement.ackRequest(parser);
1193                            if (smEnabledSyncPoint.wasSuccessful()) {
1194                                sendSmAcknowledgementInternal();
1195                            } else {
1196                                LOGGER.warning("SM Ack Request received while SM is not enabled");
1197                            }
1198                            break;
1199                         default:
1200                             LOGGER.warning("Unknown top level stream element: " + name);
1201                             break;
1202                        }
1203                        break;
1204                    case XmlPullParser.END_TAG:
1205                        final String endTagName = parser.getName();
1206                        if ("stream".equals(endTagName)) {
1207                            if (!parser.getNamespace().equals("http://etherx.jabber.org/streams")) {
1208                                LOGGER.warning(XMPPTCPConnection.this +  " </stream> but different namespace " + parser.getNamespace());
1209                                break;
1210                            }
1211
1212                            // Check if the queue was already shut down before reporting success on closing stream tag
1213                            // received. This avoids a race if there is a disconnect(), followed by a connect(), which
1214                            // did re-start the queue again, causing this writer to assume that the queue is not
1215                            // shutdown, which results in a call to disconnect().
1216                            final boolean queueWasShutdown = packetWriter.queue.isShutdown();
1217                            closingStreamReceived.reportSuccess();
1218
1219                            if (queueWasShutdown) {
1220                                // We received a closing stream element *after* we initiated the
1221                                // termination of the session by sending a closing stream element to
1222                                // the server first
1223                                return;
1224                            } else {
1225                                // We received a closing stream element from the server without us
1226                                // sending a closing stream element first. This means that the
1227                                // server wants to terminate the session, therefore disconnect
1228                                // the connection
1229                                LOGGER.info(XMPPTCPConnection.this
1230                                                + " received closing </stream> element."
1231                                                + " Server wants to terminate the connection, calling disconnect()");
1232                                disconnect();
1233                            }
1234                        }
1235                        break;
1236                    case XmlPullParser.END_DOCUMENT:
1237                        // END_DOCUMENT only happens in an error case, as otherwise we would see a
1238                        // closing stream element before.
1239                        throw new SmackException(
1240                                        "Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element");
1241                    }
1242                    eventType = parser.next();
1243                }
1244            }
1245            catch (Exception e) {
1246                closingStreamReceived.reportFailure(e);
1247                // The exception can be ignored if the the connection is 'done'
1248                // or if the it was caused because the socket got closed
1249                if (!(done || packetWriter.queue.isShutdown())) {
1250                    // Close the connection and notify connection listeners of the
1251                    // error.
1252                    notifyConnectionError(e);
1253                }
1254            }
1255        }
1256    }
1257
1258    protected class PacketWriter {
1259        public static final int QUEUE_SIZE = XMPPTCPConnection.QUEUE_SIZE;
1260
1261        private final ArrayBlockingQueueWithShutdown<Element> queue = new ArrayBlockingQueueWithShutdown<>(
1262                        QUEUE_SIZE, true);
1263
1264        /**
1265         * Needs to be protected for unit testing purposes.
1266         */
1267        protected SynchronizationPoint<NoResponseException> shutdownDone = new SynchronizationPoint<>(
1268                        XMPPTCPConnection.this, "shutdown completed");
1269
1270        /**
1271         * If set, the stanza(/packet) writer is shut down
1272         */
1273        protected volatile Long shutdownTimestamp = null;
1274
1275        private volatile boolean instantShutdown;
1276
1277        /**
1278         * True if some preconditions are given to start the bundle and defer mechanism.
1279         * <p>
1280         * This will likely get set to true right after the start of the writer thread, because
1281         * {@link #nextStreamElement()} will check if {@link queue} is empty, which is probably the case, and then set
1282         * this field to true.
1283         * </p>
1284         */
1285        private boolean shouldBundleAndDefer;
1286
1287        /** 
1288        * Initializes the writer in order to be used. It is called at the first connection and also 
1289        * is invoked if the connection is disconnected by an error.
1290        */ 
1291        void init() {
1292            shutdownDone.init();
1293            shutdownTimestamp = null;
1294
1295            if (unacknowledgedStanzas != null) {
1296                // It's possible that there are new stanzas in the writer queue that
1297                // came in while we were disconnected but resumable, drain those into
1298                // the unacknowledged queue so that they get resent now
1299                drainWriterQueueToUnacknowledgedStanzas();
1300            }
1301
1302            queue.start();
1303            Async.go(new Runnable() {
1304                @Override
1305                public void run() {
1306                    writePackets();
1307                }
1308            }, "Smack Packet Writer (" + getConnectionCounter() + ")");
1309        }
1310
1311        private boolean done() {
1312            return shutdownTimestamp != null;
1313        }
1314
1315        protected void throwNotConnectedExceptionIfDoneAndResumptionNotPossible() throws NotConnectedException {
1316            final boolean done = done();
1317            if (done) {
1318                final boolean smResumptionPossible = isSmResumptionPossible();
1319                // Don't throw a NotConnectedException is there is an resumable stream available
1320                if (!smResumptionPossible) {
1321                    throw new NotConnectedException(XMPPTCPConnection.this, "done=" + done
1322                                    + " smResumptionPossible=" + smResumptionPossible);
1323                }
1324            }
1325        }
1326
1327        /**
1328         * Sends the specified element to the server.
1329         *
1330         * @param element the element to send.
1331         * @throws NotConnectedException 
1332         * @throws InterruptedException 
1333         */
1334        protected void sendStreamElement(Element element) throws NotConnectedException, InterruptedException {
1335            throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
1336            try {
1337                queue.put(element);
1338            }
1339            catch (InterruptedException e) {
1340                // put() may throw an InterruptedException for two reasons:
1341                // 1. If the queue was shut down
1342                // 2. If the thread was interrupted
1343                // so we have to check which is the case
1344                throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
1345                // If the method above did not throw, then the sending thread was interrupted
1346                throw e;
1347            }
1348        }
1349
1350        /**
1351         * Shuts down the stanza(/packet) writer. Once this method has been called, no further
1352         * packets will be written to the server.
1353         * @throws InterruptedException 
1354         */
1355        void shutdown(boolean instant) {
1356            instantShutdown = instant;
1357            queue.shutdown();
1358            shutdownTimestamp = System.currentTimeMillis();
1359            try {
1360                shutdownDone.checkIfSuccessOrWait();
1361            }
1362            catch (NoResponseException | InterruptedException e) {
1363                LOGGER.log(Level.WARNING, "shutdownDone was not marked as successful by the writer thread", e);
1364            }
1365        }
1366
1367        /**
1368         * Maybe return the next available element from the queue for writing. If the queue is shut down <b>or</b> a
1369         * spurious interrupt occurs, <code>null</code> is returned. So it is important to check the 'done' condition in
1370         * that case.
1371         *
1372         * @return the next element for writing or null.
1373         */
1374        private Element nextStreamElement() {
1375            // It is important the we check if the queue is empty before removing an element from it
1376            if (queue.isEmpty()) {
1377                shouldBundleAndDefer = true;
1378            }
1379            Element packet = null;
1380            try {
1381                packet = queue.take();
1382            }
1383            catch (InterruptedException e) {
1384                if (!queue.isShutdown()) {
1385                    // Users shouldn't try to interrupt the packet writer thread
1386                    LOGGER.log(Level.WARNING, "Packet writer thread was interrupted. Don't do that. Use disconnect() instead.", e);
1387                }
1388            }
1389            return packet;
1390        }
1391
1392        private void writePackets() {
1393            Exception writerException = null;
1394            try {
1395                openStream();
1396                initialOpenStreamSend.reportSuccess();
1397                // Write out packets from the queue.
1398                while (!done()) {
1399                    Element element = nextStreamElement();
1400                    if (element == null) {
1401                        continue;
1402                    }
1403
1404                    // Get a local version of the bundle and defer callback, in case it's unset
1405                    // between the null check and the method invocation
1406                    final BundleAndDeferCallback localBundleAndDeferCallback = bundleAndDeferCallback;
1407                    // If the preconditions are given (e.g. bundleAndDefer callback is set, queue is
1408                    // empty), then we could wait a bit for further stanzas attempting to decrease
1409                    // our energy consumption
1410                    if (localBundleAndDeferCallback != null && isAuthenticated() && shouldBundleAndDefer) {
1411                        // Reset shouldBundleAndDefer to false, nextStreamElement() will set it to true once the
1412                        // queue is empty again.
1413                        shouldBundleAndDefer = false;
1414                        final AtomicBoolean bundlingAndDeferringStopped = new AtomicBoolean();
1415                        final int bundleAndDeferMillis = localBundleAndDeferCallback.getBundleAndDeferMillis(new BundleAndDefer(
1416                                        bundlingAndDeferringStopped));
1417                        if (bundleAndDeferMillis > 0) {
1418                            long remainingWait = bundleAndDeferMillis;
1419                            final long waitStart = System.currentTimeMillis();
1420                            synchronized (bundlingAndDeferringStopped) {
1421                                while (!bundlingAndDeferringStopped.get() && remainingWait > 0) {
1422                                    bundlingAndDeferringStopped.wait(remainingWait);
1423                                    remainingWait = bundleAndDeferMillis
1424                                                    - (System.currentTimeMillis() - waitStart);
1425                                }
1426                            }
1427                        }
1428                    }
1429
1430                    Stanza packet = null;
1431                    if (element instanceof Stanza) {
1432                        packet = (Stanza) element;
1433                    }
1434                    else if (element instanceof Enable) {
1435                        // The client needs to add messages to the unacknowledged stanzas queue
1436                        // right after it sent 'enabled'. Stanza will be added once
1437                        // unacknowledgedStanzas is not null.
1438                        unacknowledgedStanzas = new ArrayBlockingQueue<>(QUEUE_SIZE);
1439                    }
1440                    maybeAddToUnacknowledgedStanzas(packet);
1441
1442                    CharSequence elementXml = element.toXML();
1443                    if (elementXml instanceof XmlStringBuilder) {
1444                        ((XmlStringBuilder) elementXml).write(writer);
1445                    }
1446                    else {
1447                        writer.write(elementXml.toString());
1448                    }
1449
1450                    if (queue.isEmpty()) {
1451                        writer.flush();
1452                    }
1453                    if (packet != null) {
1454                        firePacketSendingListeners(packet);
1455                    }
1456                }
1457                if (!instantShutdown) {
1458                    // Flush out the rest of the queue.
1459                    try {
1460                        while (!queue.isEmpty()) {
1461                            Element packet = queue.remove();
1462                            if (packet instanceof Stanza) {
1463                                Stanza stanza = (Stanza) packet;
1464                                maybeAddToUnacknowledgedStanzas(stanza);
1465                            }
1466                            writer.write(packet.toXML().toString());
1467                        }
1468                        writer.flush();
1469                    }
1470                    catch (Exception e) {
1471                        LOGGER.log(Level.WARNING,
1472                                        "Exception flushing queue during shutdown, ignore and continue",
1473                                        e);
1474                    }
1475
1476                    // Close the stream.
1477                    try {
1478                        writer.write("</stream:stream>");
1479                        writer.flush();
1480                    }
1481                    catch (Exception e) {
1482                        LOGGER.log(Level.WARNING, "Exception writing closing stream element", e);
1483                    }
1484
1485                    // Delete the queue contents (hopefully nothing is left).
1486                    queue.clear();
1487                } else if (instantShutdown && isSmEnabled()) {
1488                    // This was an instantShutdown and SM is enabled, drain all remaining stanzas
1489                    // into the unacknowledgedStanzas queue
1490                    drainWriterQueueToUnacknowledgedStanzas();
1491                }
1492                // Do *not* close the writer here, as it will cause the socket
1493                // to get closed. But we may want to receive further stanzas
1494                // until the closing stream tag is received. The socket will be
1495                // closed in shutdown().
1496            }
1497            catch (Exception e) {
1498                // The exception can be ignored if the the connection is 'done'
1499                // or if the it was caused because the socket got closed
1500                if (!(done() || queue.isShutdown())) {
1501                    writerException = e;
1502                } else {
1503                    LOGGER.log(Level.FINE, "Ignoring Exception in writePackets()", e);
1504                }
1505            } finally {
1506                LOGGER.fine("Reporting shutdownDone success in writer thread");
1507                shutdownDone.reportSuccess();
1508            }
1509            // Delay notifyConnectionError after shutdownDone has been reported in the finally block.
1510            if (writerException != null) {
1511                notifyConnectionError(writerException);
1512            }
1513        }
1514
1515        private void drainWriterQueueToUnacknowledgedStanzas() {
1516            List<Element> elements = new ArrayList<>(queue.size());
1517            queue.drainTo(elements);
1518            for (Element element : elements) {
1519                if (element instanceof Stanza) {
1520                    unacknowledgedStanzas.add((Stanza) element);
1521                }
1522            }
1523        }
1524
1525        private void maybeAddToUnacknowledgedStanzas(Stanza stanza) throws IOException {
1526            // Check if the stream element should be put to the unacknowledgedStanza
1527            // queue. Note that we can not do the put() in sendStanzaInternal() and the
1528            // packet order is not stable at this point (sendStanzaInternal() can be
1529            // called concurrently).
1530            if (unacknowledgedStanzas != null && stanza != null) {
1531                // If the unacknowledgedStanza queue is nearly full, request an new ack
1532                // from the server in order to drain it
1533                if (unacknowledgedStanzas.size() == 0.8 * XMPPTCPConnection.QUEUE_SIZE) {
1534                    writer.write(AckRequest.INSTANCE.toXML().toString());
1535                    writer.flush();
1536                }
1537                try {
1538                    // It is important the we put the stanza in the unacknowledged stanza
1539                    // queue before we put it on the wire
1540                    unacknowledgedStanzas.put(stanza);
1541                }
1542                catch (InterruptedException e) {
1543                    throw new IllegalStateException(e);
1544                }
1545            }
1546        }
1547    }
1548
1549    /**
1550     * Set if Stream Management should be used by default for new connections.
1551     * 
1552     * @param useSmDefault true to use Stream Management for new connections.
1553     */
1554    public static void setUseStreamManagementDefault(boolean useSmDefault) {
1555        XMPPTCPConnection.useSmDefault = useSmDefault;
1556    }
1557
1558    /**
1559     * Set if Stream Management resumption should be used by default for new connections.
1560     * 
1561     * @param useSmResumptionDefault true to use Stream Management resumption for new connections.
1562     * @deprecated use {@link #setUseStreamManagementResumptionDefault(boolean)} instead.
1563     */
1564    @Deprecated
1565    public static void setUseStreamManagementResumptiodDefault(boolean useSmResumptionDefault) {
1566        setUseStreamManagementResumptionDefault(useSmResumptionDefault);
1567    }
1568
1569    /**
1570     * Set if Stream Management resumption should be used by default for new connections.
1571     *
1572     * @param useSmResumptionDefault true to use Stream Management resumption for new connections.
1573     */
1574    public static void setUseStreamManagementResumptionDefault(boolean useSmResumptionDefault) {
1575        if (useSmResumptionDefault) {
1576            // Also enable SM is resumption is enabled
1577            setUseStreamManagementDefault(useSmResumptionDefault);
1578        }
1579        XMPPTCPConnection.useSmResumptionDefault = useSmResumptionDefault;
1580    }
1581
1582    /**
1583     * Set if Stream Management should be used if supported by the server.
1584     * 
1585     * @param useSm true to use Stream Management.
1586     */
1587    public void setUseStreamManagement(boolean useSm) {
1588        this.useSm = useSm;
1589    }
1590
1591    /**
1592     * Set if Stream Management resumption should be used if supported by the server.
1593     *
1594     * @param useSmResumption true to use Stream Management resumption.
1595     */
1596    public void setUseStreamManagementResumption(boolean useSmResumption) {
1597        if (useSmResumption) {
1598            // Also enable SM is resumption is enabled
1599            setUseStreamManagement(useSmResumption);
1600        }
1601        this.useSmResumption = useSmResumption;
1602    }
1603
1604    /**
1605     * Set the preferred resumption time in seconds.
1606     * @param resumptionTime the preferred resumption time in seconds
1607     */
1608    public void setPreferredResumptionTime(int resumptionTime) {
1609        smClientMaxResumptionTime = resumptionTime;
1610    }
1611
1612    /**
1613     * Add a predicate for Stream Management acknowledgment requests.
1614     * <p>
1615     * Those predicates are used to determine when a Stream Management acknowledgement request is send to the server.
1616     * Some pre-defined predicates are found in the <code>org.jivesoftware.smack.sm.predicates</code> package.
1617     * </p>
1618     * <p>
1619     * If not predicate is configured, the {@link Predicate#forMessagesOrAfter5Stanzas()} will be used.
1620     * </p>
1621     * 
1622     * @param predicate the predicate to add.
1623     * @return if the predicate was not already active.
1624     */
1625    public boolean addRequestAckPredicate(StanzaFilter predicate) {
1626        synchronized (requestAckPredicates) {
1627            return requestAckPredicates.add(predicate);
1628        }
1629    }
1630
1631    /**
1632     * Remove the given predicate for Stream Management acknowledgment request.
1633     * @param predicate the predicate to remove.
1634     * @return true if the predicate was removed.
1635     */
1636    public boolean removeRequestAckPredicate(StanzaFilter predicate) {
1637        synchronized (requestAckPredicates) {
1638            return requestAckPredicates.remove(predicate);
1639        }
1640    }
1641
1642    /**
1643     * Remove all predicates for Stream Management acknowledgment requests.
1644     */
1645    public void removeAllRequestAckPredicates() {
1646        synchronized (requestAckPredicates) {
1647            requestAckPredicates.clear();
1648        }
1649    }
1650
1651    /**
1652     * Send an unconditional Stream Management acknowledgement request to the server.
1653     *
1654     * @throws StreamManagementNotEnabledException if Stream Management is not enabled.
1655     * @throws NotConnectedException if the connection is not connected.
1656     * @throws InterruptedException 
1657     */
1658    public void requestSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException, InterruptedException {
1659        if (!isSmEnabled()) {
1660            throw new StreamManagementException.StreamManagementNotEnabledException();
1661        }
1662        requestSmAcknowledgementInternal();
1663    }
1664
1665    private void requestSmAcknowledgementInternal() throws NotConnectedException, InterruptedException {
1666        packetWriter.sendStreamElement(AckRequest.INSTANCE);
1667    }
1668
1669    /**
1670     * Send a unconditional Stream Management acknowledgment to the server.
1671     * <p>
1672     * See <a href="http://xmpp.org/extensions/xep-0198.html#acking">XEP-198: Stream Management ยง 4. Acks</a>:
1673     * "Either party MAY send an &lt;a/&gt; element at any time (e.g., after it has received a certain number of stanzas,
1674     * or after a certain period of time), even if it has not received an &lt;r/&gt; element from the other party."
1675     * </p>
1676     * 
1677     * @throws StreamManagementNotEnabledException if Stream Management is not enabled.
1678     * @throws NotConnectedException if the connection is not connected.
1679     * @throws InterruptedException 
1680     */
1681    public void sendSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException, InterruptedException {
1682        if (!isSmEnabled()) {
1683            throw new StreamManagementException.StreamManagementNotEnabledException();
1684        }
1685        sendSmAcknowledgementInternal();
1686    }
1687
1688    private void sendSmAcknowledgementInternal() throws NotConnectedException, InterruptedException {
1689        packetWriter.sendStreamElement(new AckAnswer(clientHandledStanzasCount));
1690    }
1691
1692    /**
1693     * Add a Stanza acknowledged listener.
1694     * <p>
1695     * Those listeners will be invoked every time a Stanza has been acknowledged by the server. The will not get
1696     * automatically removed. Consider using {@link #addStanzaIdAcknowledgedListener(String, StanzaListener)} when
1697     * possible.
1698     * </p>
1699     * 
1700     * @param listener the listener to add.
1701     */
1702    public void addStanzaAcknowledgedListener(StanzaListener listener) {
1703        stanzaAcknowledgedListeners.add(listener);
1704    }
1705
1706    /**
1707     * Remove the given Stanza acknowledged listener.
1708     *
1709     * @param listener the listener.
1710     * @return true if the listener was removed.
1711     */
1712    public boolean removeStanzaAcknowledgedListener(StanzaListener listener) {
1713        return stanzaAcknowledgedListeners.remove(listener);
1714    }
1715
1716    /**
1717     * Remove all stanza acknowledged listeners.
1718     */
1719    public void removeAllStanzaAcknowledgedListeners() {
1720        stanzaAcknowledgedListeners.clear();
1721    }
1722
1723    /**
1724     * Add a new Stanza ID acknowledged listener for the given ID.
1725     * <p>
1726     * The listener will be invoked if the stanza with the given ID was acknowledged by the server. It will
1727     * automatically be removed after the listener was run.
1728     * </p>
1729     * 
1730     * @param id the stanza ID.
1731     * @param listener the listener to invoke.
1732     * @return the previous listener for this stanza ID or null.
1733     * @throws StreamManagementNotEnabledException if Stream Management is not enabled.
1734     */
1735    public StanzaListener addStanzaIdAcknowledgedListener(final String id, StanzaListener listener) throws StreamManagementNotEnabledException {
1736        // Prevent users from adding callbacks that will never get removed
1737        if (!smWasEnabledAtLeastOnce) {
1738            throw new StreamManagementException.StreamManagementNotEnabledException();
1739        }
1740        // Remove the listener after max. 12 hours
1741        final int removeAfterSeconds = Math.min(getMaxSmResumptionTime(), 12 * 60 * 60);
1742        schedule(new Runnable() {
1743            @Override
1744            public void run() {
1745                stanzaIdAcknowledgedListeners.remove(id);
1746            }
1747        }, removeAfterSeconds, TimeUnit.SECONDS);
1748        return stanzaIdAcknowledgedListeners.put(id, listener);
1749    }
1750
1751    /**
1752     * Remove the Stanza ID acknowledged listener for the given ID.
1753     * 
1754     * @param id the stanza ID.
1755     * @return true if the listener was found and removed, false otherwise.
1756     */
1757    public StanzaListener removeStanzaIdAcknowledgedListener(String id) {
1758        return stanzaIdAcknowledgedListeners.remove(id);
1759    }
1760
1761    /**
1762     * Removes all Stanza ID acknowledged listeners.
1763     */
1764    public void removeAllStanzaIdAcknowledgedListeners() {
1765        stanzaIdAcknowledgedListeners.clear();
1766    }
1767
1768    /**
1769     * Returns true if Stream Management is supported by the server.
1770     *
1771     * @return true if Stream Management is supported by the server.
1772     */
1773    public boolean isSmAvailable() {
1774        return hasFeature(StreamManagementFeature.ELEMENT, StreamManagement.NAMESPACE);
1775    }
1776
1777    /**
1778     * Returns true if Stream Management was successfully negotiated with the server.
1779     *
1780     * @return true if Stream Management was negotiated.
1781     */
1782    public boolean isSmEnabled() {
1783        return smEnabledSyncPoint.wasSuccessful();
1784    }
1785
1786    /**
1787     * Returns true if the stream was successfully resumed with help of Stream Management.
1788     * 
1789     * @return true if the stream was resumed.
1790     */
1791    public boolean streamWasResumed() {
1792        return smResumedSyncPoint.wasSuccessful();
1793    }
1794
1795    /**
1796     * Returns true if the connection is disconnected by a Stream resumption via Stream Management is possible.
1797     * 
1798     * @return true if disconnected but resumption possible.
1799     */
1800    public boolean isDisconnectedButSmResumptionPossible() {
1801        return disconnectedButResumeable && isSmResumptionPossible();
1802    }
1803
1804    /**
1805     * Returns true if the stream is resumable.
1806     *
1807     * @return true if the stream is resumable.
1808     */
1809    public boolean isSmResumptionPossible() {
1810        // There is no resumable stream available
1811        if (smSessionId == null)
1812            return false;
1813
1814        final Long shutdownTimestamp = packetWriter.shutdownTimestamp;
1815        // Seems like we are already reconnected, report true
1816        if (shutdownTimestamp == null) {
1817            return true;
1818        }
1819
1820        // See if resumption time is over
1821        long current = System.currentTimeMillis();
1822        long maxResumptionMillies = ((long) getMaxSmResumptionTime()) * 1000;
1823        if (current > shutdownTimestamp + maxResumptionMillies) {
1824            // Stream resumption is *not* possible if the current timestamp is greater then the greatest timestamp where
1825            // resumption is possible
1826            return false;
1827        } else {
1828            return true;
1829        }
1830    }
1831
1832    /**
1833     * Drop the stream management state. Sets {@link #smSessionId} and
1834     * {@link #unacknowledgedStanzas} to <code>null</code>.
1835     */
1836    private void dropSmState() {
1837        // clientHandledCount and serverHandledCount will be reset on <enable/> and <enabled/>
1838        // respective. No need to reset them here.
1839        smSessionId = null;
1840        unacknowledgedStanzas = null;
1841    }
1842
1843    /**
1844     * Get the maximum resumption time in seconds after which a managed stream can be resumed.
1845     * <p>
1846     * This method will return {@link Integer#MAX_VALUE} if neither the client nor the server specify a maximum
1847     * resumption time. Be aware of integer overflows when using this value, e.g. do not add arbitrary values to it
1848     * without checking for overflows before.
1849     * </p>
1850     *
1851     * @return the maximum resumption time in seconds or {@link Integer#MAX_VALUE} if none set.
1852     */
1853    public int getMaxSmResumptionTime() {
1854        int clientResumptionTime = smClientMaxResumptionTime > 0 ? smClientMaxResumptionTime : Integer.MAX_VALUE;
1855        int serverResumptionTime = smServerMaxResumptionTime > 0 ? smServerMaxResumptionTime : Integer.MAX_VALUE;
1856        return Math.min(clientResumptionTime, serverResumptionTime);
1857    }
1858
1859    private void processHandledCount(long handledCount) throws StreamManagementCounterError {
1860        long ackedStanzasCount = SMUtils.calculateDelta(handledCount, serverHandledStanzasCount);
1861        final List<Stanza> ackedStanzas = new ArrayList<>(
1862                        ackedStanzasCount <= Integer.MAX_VALUE ? (int) ackedStanzasCount
1863                                        : Integer.MAX_VALUE);
1864        for (long i = 0; i < ackedStanzasCount; i++) {
1865            Stanza ackedStanza = unacknowledgedStanzas.poll();
1866            // If the server ack'ed a stanza, then it must be in the
1867            // unacknowledged stanza queue. There can be no exception.
1868            if (ackedStanza == null) {
1869                throw new StreamManagementCounterError(handledCount, serverHandledStanzasCount,
1870                                ackedStanzasCount, ackedStanzas);
1871            }
1872            ackedStanzas.add(ackedStanza);
1873        }
1874
1875        boolean atLeastOneStanzaAcknowledgedListener = false;
1876        if (!stanzaAcknowledgedListeners.isEmpty()) {
1877            // If stanzaAcknowledgedListeners is not empty, the we have at least one
1878            atLeastOneStanzaAcknowledgedListener = true;
1879        }
1880        else {
1881            // Otherwise we look for a matching id in the stanza *id* acknowledged listeners
1882            for (Stanza ackedStanza : ackedStanzas) {
1883                String id = ackedStanza.getStanzaId();
1884                if (id != null && stanzaIdAcknowledgedListeners.containsKey(id)) {
1885                    atLeastOneStanzaAcknowledgedListener = true;
1886                    break;
1887                }
1888            }
1889        }
1890
1891        // Only spawn a new thread if there is a chance that some listener is invoked
1892        if (atLeastOneStanzaAcknowledgedListener) {
1893            asyncGo(new Runnable() {
1894                @Override
1895                public void run() {
1896                    for (Stanza ackedStanza : ackedStanzas) {
1897                        for (StanzaListener listener : stanzaAcknowledgedListeners) {
1898                            try {
1899                                listener.processStanza(ackedStanza);
1900                            }
1901                            catch (InterruptedException | NotConnectedException | NotLoggedInException e) {
1902                                LOGGER.log(Level.FINER, "Received exception", e);
1903                            }
1904                        }
1905                        String id = ackedStanza.getStanzaId();
1906                        if (StringUtils.isNullOrEmpty(id)) {
1907                            continue;
1908                        }
1909                        StanzaListener listener = stanzaIdAcknowledgedListeners.remove(id);
1910                        if (listener != null) {
1911                            try {
1912                                listener.processStanza(ackedStanza);
1913                            }
1914                            catch (InterruptedException | NotConnectedException | NotLoggedInException e) {
1915                                LOGGER.log(Level.FINER, "Received exception", e);
1916                            }
1917                        }
1918                    }
1919                }
1920            });
1921        }
1922
1923        serverHandledStanzasCount = handledCount;
1924    }
1925
1926    /**
1927     * Set the default bundle and defer callback used for new connections.
1928     *
1929     * @param defaultBundleAndDeferCallback
1930     * @see BundleAndDeferCallback
1931     * @since 4.1
1932     */
1933    public static void setDefaultBundleAndDeferCallback(BundleAndDeferCallback defaultBundleAndDeferCallback) {
1934        XMPPTCPConnection.defaultBundleAndDeferCallback = defaultBundleAndDeferCallback;
1935    }
1936
1937    /**
1938     * Set the bundle and defer callback used for this connection.
1939     * <p>
1940     * You can use <code>null</code> as argument to reset the callback. Outgoing stanzas will then
1941     * no longer get deferred.
1942     * </p>
1943     *
1944     * @param bundleAndDeferCallback the callback or <code>null</code>.
1945     * @see BundleAndDeferCallback
1946     * @since 4.1
1947     */
1948    public void setBundleandDeferCallback(BundleAndDeferCallback bundleAndDeferCallback) {
1949        this.bundleAndDeferCallback = bundleAndDeferCallback;
1950    }
1951
1952}