XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.content.Context;
   4import android.graphics.Bitmap;
   5import android.graphics.BitmapFactory;
   6import android.os.SystemClock;
   7import android.security.KeyChain;
   8import android.support.annotation.NonNull;
   9import android.util.Base64;
  10import android.util.Log;
  11import android.util.Pair;
  12import android.util.SparseArray;
  13
  14import org.xmlpull.v1.XmlPullParserException;
  15
  16import java.io.ByteArrayInputStream;
  17import java.io.IOException;
  18import java.io.InputStream;
  19import java.net.ConnectException;
  20import java.net.IDN;
  21import java.net.InetAddress;
  22import java.net.InetSocketAddress;
  23import java.net.MalformedURLException;
  24import java.net.Socket;
  25import java.net.URL;
  26import java.net.UnknownHostException;
  27import java.security.KeyManagementException;
  28import java.security.NoSuchAlgorithmException;
  29import java.security.Principal;
  30import java.security.PrivateKey;
  31import java.security.cert.X509Certificate;
  32import java.util.ArrayList;
  33import java.util.Arrays;
  34import java.util.Collections;
  35import java.util.HashMap;
  36import java.util.HashSet;
  37import java.util.Hashtable;
  38import java.util.Iterator;
  39import java.util.List;
  40import java.util.Map.Entry;
  41import java.util.Set;
  42import java.util.concurrent.CountDownLatch;
  43import java.util.concurrent.TimeUnit;
  44import java.util.concurrent.atomic.AtomicBoolean;
  45import java.util.concurrent.atomic.AtomicInteger;
  46import java.util.regex.Matcher;
  47
  48import javax.net.ssl.KeyManager;
  49import javax.net.ssl.SSLContext;
  50import javax.net.ssl.SSLSocket;
  51import javax.net.ssl.SSLSocketFactory;
  52import javax.net.ssl.X509KeyManager;
  53import javax.net.ssl.X509TrustManager;
  54
  55import eu.siacs.conversations.Config;
  56import eu.siacs.conversations.R;
  57import eu.siacs.conversations.crypto.DomainHostnameVerifier;
  58import eu.siacs.conversations.crypto.XmppDomainVerifier;
  59import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  60import eu.siacs.conversations.crypto.sasl.Anonymous;
  61import eu.siacs.conversations.crypto.sasl.DigestMd5;
  62import eu.siacs.conversations.crypto.sasl.External;
  63import eu.siacs.conversations.crypto.sasl.Plain;
  64import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  65import eu.siacs.conversations.crypto.sasl.ScramSha1;
  66import eu.siacs.conversations.crypto.sasl.ScramSha256;
  67import eu.siacs.conversations.entities.Account;
  68import eu.siacs.conversations.entities.Message;
  69import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  70import eu.siacs.conversations.generator.IqGenerator;
  71import eu.siacs.conversations.persistance.FileBackend;
  72import eu.siacs.conversations.services.MemorizingTrustManager;
  73import eu.siacs.conversations.services.MessageArchiveService;
  74import eu.siacs.conversations.services.NotificationService;
  75import eu.siacs.conversations.services.XmppConnectionService;
  76import eu.siacs.conversations.utils.CryptoHelper;
  77import eu.siacs.conversations.utils.Patterns;
  78import eu.siacs.conversations.utils.Resolver;
  79import eu.siacs.conversations.utils.SSLSocketHelper;
  80import eu.siacs.conversations.utils.SocksSocketFactory;
  81import eu.siacs.conversations.xml.Element;
  82import eu.siacs.conversations.xml.Namespace;
  83import eu.siacs.conversations.xml.Tag;
  84import eu.siacs.conversations.xml.TagWriter;
  85import eu.siacs.conversations.xml.XmlReader;
  86import eu.siacs.conversations.xmpp.forms.Data;
  87import eu.siacs.conversations.xmpp.forms.Field;
  88import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  89import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  90import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  91import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  92import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  93import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  94import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  95import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  96import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  97import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
  98import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
  99import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
 100import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
 101import rocks.xmpp.addr.Jid;
 102
 103public class XmppConnection implements Runnable {
 104
 105    private static final int PACKET_IQ = 0;
 106    private static final int PACKET_MESSAGE = 1;
 107    private static final int PACKET_PRESENCE = 2;
 108    public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
 109        @Override
 110        public void onIqPacketReceived(Account account, IqPacket packet) {
 111            if (packet.getType() == IqPacket.TYPE.RESULT) {
 112                account.setOption(Account.OPTION_REGISTER, false);
 113                throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 114            } else {
 115                final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
 116                        "The password is too weak",
 117                        "Please use a longer password.");
 118                Element error = packet.findChild("error");
 119                Account.State state = Account.State.REGISTRATION_FAILED;
 120                if (error != null) {
 121                    if (error.hasChild("conflict")) {
 122                        state = Account.State.REGISTRATION_CONFLICT;
 123                    } else if (error.hasChild("resource-constraint")
 124                            && "wait".equals(error.getAttribute("type"))) {
 125                        state = Account.State.REGISTRATION_PLEASE_WAIT;
 126                    } else if (error.hasChild("not-acceptable")
 127                            && PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
 128                        state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 129                    }
 130                }
 131                throw new StateChangingError(state);
 132            }
 133        }
 134    };
 135    protected final Account account;
 136    private final Features features = new Features(this);
 137    private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 138    private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 139    private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 140    private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
 141    private final XmppConnectionService mXmppConnectionService;
 142    private Socket socket;
 143    private XmlReader tagReader;
 144    private TagWriter tagWriter = new TagWriter();
 145    private boolean shouldAuthenticate = true;
 146    private boolean inSmacksSession = false;
 147    private boolean isBound = false;
 148    private Element streamFeatures;
 149    private String streamId = null;
 150    private int smVersion = 3;
 151    private int stanzasReceived = 0;
 152    private int stanzasSent = 0;
 153    private long lastPacketReceived = 0;
 154    private long lastPingSent = 0;
 155    private long lastConnect = 0;
 156    private long lastSessionStarted = 0;
 157    private long lastDiscoStarted = 0;
 158    private boolean isMamPreferenceAlways = false;
 159    private AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
 160    private AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 161    private AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 162    private AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 163    private boolean mInteractive = false;
 164    private int attempt = 0;
 165    private OnPresencePacketReceived presenceListener = null;
 166    private OnJinglePacketReceived jingleListener = null;
 167    private OnIqPacketReceived unregisteredIqListener = null;
 168    private OnMessagePacketReceived messageListener = null;
 169    private OnStatusChanged statusListener = null;
 170    private OnBindListener bindListener = null;
 171    private OnMessageAcknowledged acknowledgedListener = null;
 172    private SaslMechanism saslMechanism;
 173    private URL redirectionUrl = null;
 174    private String verifiedHostname = null;
 175    private volatile Thread mThread;
 176    private CountDownLatch mStreamCountDownLatch;
 177
 178
 179    public XmppConnection(final Account account, final XmppConnectionService service) {
 180        this.account = account;
 181        this.mXmppConnectionService = service;
 182    }
 183
 184    private static void fixResource(Context context, Account account) {
 185        String resource = account.getResource();
 186        int fixedPartLength = context.getString(R.string.app_name).length() + 1; //include the trailing dot
 187        int randomPartLength = 4; // 3 bytes
 188        if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
 189            if (validBase64(resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
 190                account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
 191            }
 192        }
 193    }
 194
 195    private static boolean validBase64(String input) {
 196        try {
 197            return Base64.decode(input, Base64.URL_SAFE).length == 3;
 198        } catch (Throwable throwable) {
 199            return false;
 200        }
 201    }
 202
 203    private void changeStatus(final Account.State nextStatus) {
 204        synchronized (this) {
 205            if (Thread.currentThread().isInterrupted()) {
 206                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
 207                return;
 208            }
 209            if (account.getStatus() != nextStatus) {
 210                if ((nextStatus == Account.State.OFFLINE)
 211                        && (account.getStatus() != Account.State.CONNECTING)
 212                        && (account.getStatus() != Account.State.ONLINE)
 213                        && (account.getStatus() != Account.State.DISABLED)) {
 214                    return;
 215                }
 216                if (nextStatus == Account.State.ONLINE) {
 217                    this.attempt = 0;
 218                }
 219                account.setStatus(nextStatus);
 220            } else {
 221                return;
 222            }
 223        }
 224        if (statusListener != null) {
 225            statusListener.onStatusChanged(account);
 226        }
 227    }
 228
 229    public void prepareNewConnection() {
 230        this.lastConnect = SystemClock.elapsedRealtime();
 231        this.lastPingSent = SystemClock.elapsedRealtime();
 232        this.lastDiscoStarted = Long.MAX_VALUE;
 233        this.mWaitingForSmCatchup.set(false);
 234        this.changeStatus(Account.State.CONNECTING);
 235    }
 236
 237    public boolean isWaitingForSmCatchup() {
 238        return mWaitingForSmCatchup.get();
 239    }
 240
 241    public void incrementSmCatchupMessageCounter() {
 242        this.mSmCatchupMessageCounter.incrementAndGet();
 243    }
 244
 245    protected void connect() {
 246        if (mXmppConnectionService.areMessagesInitialized()) {
 247            mXmppConnectionService.resetSendingToWaiting(account);
 248        }
 249        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
 250        features.encryptionEnabled = false;
 251        inSmacksSession = false;
 252        isBound = false;
 253        this.attempt++;
 254        this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
 255        try {
 256            Socket localSocket;
 257            shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
 258            this.changeStatus(Account.State.CONNECTING);
 259            final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 260            final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
 261            if (useTor) {
 262                String destination;
 263                if (account.getHostname().isEmpty()) {
 264                    destination = account.getServer();
 265                } else {
 266                    destination = account.getHostname();
 267                    this.verifiedHostname = destination;
 268                }
 269                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor");
 270                localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort());
 271                try {
 272                    startXmpp(localSocket);
 273                } catch (InterruptedException e) {
 274                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 275                    return;
 276                } catch (Exception e) {
 277                    throw new IOException(e.getMessage());
 278                }
 279            } else {
 280                final String domain = account.getJid().getDomain();
 281                final List<Resolver.Result> results;
 282                final boolean hardcoded = extended && !account.getHostname().isEmpty();
 283                if (hardcoded) {
 284                    results = Resolver.fromHardCoded(account.getHostname(), account.getPort());
 285                } else {
 286                    results = Resolver.resolve(domain);
 287                }
 288                if (Thread.currentThread().isInterrupted()) {
 289                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 290                    return;
 291                }
 292                if (results.size() == 0) {
 293                    Log.e(Config.LOGTAG,account.getJid().asBareJid()+": Resolver results were empty");
 294                    return;
 295                }
 296                final Resolver.Result storedBackupResult;
 297                if (hardcoded) {
 298                    storedBackupResult = null;
 299                } else {
 300                    storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
 301                    if (storedBackupResult != null && !results.contains(storedBackupResult)) {
 302                        results.add(storedBackupResult);
 303                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
 304                    }
 305                }
 306                for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
 307                    final Resolver.Result result = iterator.next();
 308                    if (Thread.currentThread().isInterrupted()) {
 309                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 310                        return;
 311                    }
 312                    try {
 313                        // if tls is true, encryption is implied and must not be started
 314                        features.encryptionEnabled = result.isDirectTls();
 315                        verifiedHostname = result.isAuthenticated() ? result.getHostname().toString() : null;
 316                        Log.d(Config.LOGTAG,"verified hostname "+verifiedHostname);
 317                        final InetSocketAddress addr;
 318                        if (result.getIp() != null) {
 319                            addr = new InetSocketAddress(result.getIp(), result.getPort());
 320                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 321                                    + ": using values from resolver " + (result.getHostname() == null ? "" : result.getHostname().toString()
 322                                    + "/") + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 323                        } else {
 324                            addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
 325                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 326                                    + ": using values from resolver "
 327                                    + result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 328                        }
 329
 330                        if (!features.encryptionEnabled) {
 331                            localSocket = new Socket();
 332                            localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 333                        } else {
 334                            final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
 335                            localSocket = tlsFactoryVerifier.factory.createSocket();
 336
 337                            if (localSocket == null) {
 338                                throw new IOException("could not initialize ssl socket");
 339                            }
 340
 341                            SSLSocketHelper.setSecurity((SSLSocket) localSocket);
 342                            SSLSocketHelper.setHostname((SSLSocket) localSocket, account.getServer());
 343                            SSLSocketHelper.setApplicationProtocol((SSLSocket) localSocket, "xmpp-client");
 344
 345                            localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 346
 347                            if (!tlsFactoryVerifier.verifier.verify(account.getServer(), verifiedHostname, ((SSLSocket) localSocket).getSession())) {
 348                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 349                                if (!iterator.hasNext()) {
 350                                    throw new StateChangingException(Account.State.TLS_ERROR);
 351                                }
 352                            }
 353                        }
 354                        localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
 355                        if (startXmpp(localSocket)) {
 356                            localSocket.setSoTimeout(0); //reset to 0; once the connection is established we don’t want this
 357                            if (!hardcoded && !result.equals(storedBackupResult)) {
 358                                mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
 359                            }
 360                            break; // successfully connected to server that speaks xmpp
 361                        } else {
 362                            localSocket.close();
 363                            if (!iterator.hasNext()) {
 364                                throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 365                            }
 366                        }
 367                    } catch (final StateChangingException e) {
 368                        throw e;
 369                    } catch (InterruptedException e) {
 370                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 371                        return;
 372                    } catch (final Throwable e) {
 373                        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
 374                        if (!iterator.hasNext()) {
 375                            throw new UnknownHostException();
 376                        }
 377                    }
 378                }
 379            }
 380            processStream();
 381        } catch (final SecurityException e) {
 382            this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 383        } catch (final StateChangingException e) {
 384            this.changeStatus(e.state);
 385        } catch (final UnknownHostException | ConnectException e) {
 386            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 387        } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 388            this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 389        } catch (final IOException | XmlPullParserException  e) {
 390            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 391            this.changeStatus(Account.State.OFFLINE);
 392            this.attempt = Math.max(0, this.attempt - 1);
 393        } finally {
 394            if (!Thread.currentThread().isInterrupted()) {
 395                forceCloseSocket();
 396            } else {
 397                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
 398            }
 399        }
 400    }
 401
 402    /**
 403     * Starts xmpp protocol, call after connecting to socket
 404     *
 405     * @return true if server returns with valid xmpp, false otherwise
 406     */
 407    private boolean startXmpp(Socket socket) throws Exception {
 408        if (Thread.currentThread().isInterrupted()) {
 409            throw new InterruptedException();
 410        }
 411        this.socket = socket;
 412        tagReader = new XmlReader();
 413        if (tagWriter != null) {
 414            tagWriter.forceClose();
 415        }
 416        tagWriter = new TagWriter();
 417        tagWriter.setOutputStream(socket.getOutputStream());
 418        tagReader.setInputStream(socket.getInputStream());
 419        tagWriter.beginDocument();
 420        sendStartStream();
 421        final Tag tag = tagReader.readTag();
 422        if (Thread.currentThread().isInterrupted()) {
 423            throw new InterruptedException();
 424        }
 425        if (socket instanceof SSLSocket) {
 426            SSLSocketHelper.log(account, (SSLSocket) socket);
 427        }
 428        return tag != null && tag.isStart("stream");
 429    }
 430
 431    private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
 432        final SSLContext sc = SSLSocketHelper.getSSLContext();
 433        MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
 434        KeyManager[] keyManager;
 435        if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
 436            keyManager = new KeyManager[]{new MyKeyManager()};
 437        } else {
 438            keyManager = null;
 439        }
 440        String domain = account.getJid().getDomain();
 441        sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
 442        final SSLSocketFactory factory = sc.getSocketFactory();
 443        final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
 444        return new TlsFactoryVerifier(factory, verifier);
 445    }
 446
 447    @Override
 448    public void run() {
 449        synchronized (this) {
 450            this.mThread = Thread.currentThread();
 451            if (this.mThread.isInterrupted()) {
 452                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
 453                return;
 454            }
 455            forceCloseSocket();
 456        }
 457        connect();
 458    }
 459
 460    private void processStream() throws XmlPullParserException, IOException {
 461        final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 462        this.mStreamCountDownLatch = streamCountDownLatch;
 463        Tag nextTag = tagReader.readTag();
 464        while (nextTag != null && !nextTag.isEnd("stream")) {
 465            if (nextTag.isStart("error")) {
 466                processStreamError(nextTag);
 467            } else if (nextTag.isStart("features")) {
 468                processStreamFeatures(nextTag);
 469            } else if (nextTag.isStart("proceed")) {
 470                switchOverToTls();
 471            } else if (nextTag.isStart("success")) {
 472                final String challenge = tagReader.readElement(nextTag).getContent();
 473                try {
 474                    saslMechanism.getResponse(challenge);
 475                } catch (final SaslMechanism.AuthenticationException e) {
 476                    Log.e(Config.LOGTAG, String.valueOf(e));
 477                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 478                }
 479                Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
 480                account.setKey(Account.PINNED_MECHANISM_KEY,
 481                        String.valueOf(saslMechanism.getPriority()));
 482                tagReader.reset();
 483                sendStartStream();
 484                final Tag tag = tagReader.readTag();
 485                if (tag != null && tag.isStart("stream")) {
 486                    processStream();
 487                } else {
 488                    throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 489                }
 490                break;
 491            } else if (nextTag.isStart("failure")) {
 492                final Element failure = tagReader.readElement(nextTag);
 493                if (Namespace.SASL.equals(failure.getNamespace())) {
 494                    final String text = failure.findChildContent("text");
 495                    if (failure.hasChild("account-disabled") && text != null) {
 496                        Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 497                        if (matcher.find()) {
 498                            try {
 499                                URL url = new URL(text.substring(matcher.start(), matcher.end()));
 500                                if (url.getProtocol().equals("https")) {
 501                                    this.redirectionUrl = url;
 502                                    throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 503                                }
 504                            } catch (MalformedURLException e) {
 505                                throw new StateChangingException(Account.State.UNAUTHORIZED);
 506                            }
 507                        }
 508                    }
 509                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 510                } else if (Namespace.TLS.equals(failure.getNamespace())) {
 511                    throw new StateChangingException(Account.State.TLS_ERROR);
 512                } else {
 513                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 514                }
 515            } else if (nextTag.isStart("challenge")) {
 516                final String challenge = tagReader.readElement(nextTag).getContent();
 517                final Element response = new Element("response", Namespace.SASL);
 518                try {
 519                    response.setContent(saslMechanism.getResponse(challenge));
 520                } catch (final SaslMechanism.AuthenticationException e) {
 521                    // TODO: Send auth abort tag.
 522                    Log.e(Config.LOGTAG, e.toString());
 523                }
 524                tagWriter.writeElement(response);
 525            } else if (nextTag.isStart("enabled")) {
 526                final Element enabled = tagReader.readElement(nextTag);
 527                if ("true".equals(enabled.getAttribute("resume"))) {
 528                    this.streamId = enabled.getAttribute("id");
 529                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 530                            + ": stream management(" + smVersion
 531                            + ") enabled (resumable)");
 532                } else {
 533                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 534                            + ": stream management(" + smVersion + ") enabled");
 535                }
 536                this.stanzasReceived = 0;
 537                this.inSmacksSession = true;
 538                final RequestPacket r = new RequestPacket(smVersion);
 539                tagWriter.writeStanzaAsync(r);
 540            } else if (nextTag.isStart("resumed")) {
 541                this.inSmacksSession = true;
 542                this.isBound = true;
 543                this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 544                lastPacketReceived = SystemClock.elapsedRealtime();
 545                final Element resumed = tagReader.readElement(nextTag);
 546                final String h = resumed.getAttribute("h");
 547                try {
 548                    ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 549                    final boolean acknowledgedMessages;
 550                    synchronized (this.mStanzaQueue) {
 551                        final int serverCount = Integer.parseInt(h);
 552                        if (serverCount < stanzasSent) {
 553                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 554                                    + ": session resumed with lost packages");
 555                            stanzasSent = serverCount;
 556                        } else {
 557                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
 558                        }
 559                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 560                        for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 561                            failedStanzas.add(mStanzaQueue.valueAt(i));
 562                        }
 563                        mStanzaQueue.clear();
 564                    }
 565                    if (acknowledgedMessages) {
 566                        mXmppConnectionService.updateConversationUi();
 567                    }
 568                    Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
 569                    for (AbstractAcknowledgeableStanza packet : failedStanzas) {
 570                        if (packet instanceof MessagePacket) {
 571                            MessagePacket message = (MessagePacket) packet;
 572                            mXmppConnectionService.markMessage(account,
 573                                    message.getTo().asBareJid(),
 574                                    message.getId(),
 575                                    Message.STATUS_UNSEND);
 576                        }
 577                        sendPacket(packet);
 578                    }
 579                } catch (final NumberFormatException ignored) {
 580                }
 581                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
 582                changeStatus(Account.State.ONLINE);
 583            } else if (nextTag.isStart("r")) {
 584                tagReader.readElement(nextTag);
 585                if (Config.EXTENDED_SM_LOGGING) {
 586                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 587                }
 588                final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 589                tagWriter.writeStanzaAsync(ack);
 590            } else if (nextTag.isStart("a")) {
 591                boolean accountUiNeedsRefresh = false;
 592                synchronized (NotificationService.CATCHUP_LOCK) {
 593                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 594                        final int messageCount = mSmCatchupMessageCounter.get();
 595                        final int pendingIQs = packetCallbacks.size();
 596                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (messages=" + messageCount + ", pending IQs="+pendingIQs+")");
 597                        accountUiNeedsRefresh = true;
 598                        if (messageCount > 0) {
 599                            mXmppConnectionService.getNotificationService().finishBacklog(true, account);
 600                        }
 601                    }
 602                }
 603                if (accountUiNeedsRefresh) {
 604                    mXmppConnectionService.updateAccountUi();
 605                }
 606                final Element ack = tagReader.readElement(nextTag);
 607                lastPacketReceived = SystemClock.elapsedRealtime();
 608                try {
 609                    final boolean acknowledgedMessages;
 610                    synchronized (this.mStanzaQueue) {
 611                        final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 612                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
 613                    }
 614                    if (acknowledgedMessages) {
 615                        mXmppConnectionService.updateConversationUi();
 616                    }
 617                } catch (NumberFormatException | NullPointerException e) {
 618                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
 619                }
 620            } else if (nextTag.isStart("failed")) {
 621                Element failed = tagReader.readElement(nextTag);
 622                try {
 623                    final int serverCount = Integer.parseInt(failed.getAttribute("h"));
 624                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
 625                    final boolean acknowledgedMessages;
 626                    synchronized (this.mStanzaQueue) {
 627                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 628                    }
 629                    if (acknowledgedMessages) {
 630                        mXmppConnectionService.updateConversationUi();
 631                    }
 632                } catch (NumberFormatException | NullPointerException e) {
 633                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
 634                }
 635                resetStreamId();
 636                sendBindRequest();
 637            } else if (nextTag.isStart("iq")) {
 638                processIq(nextTag);
 639            } else if (nextTag.isStart("message")) {
 640                processMessage(nextTag);
 641            } else if (nextTag.isStart("presence")) {
 642                processPresence(nextTag);
 643            }
 644            nextTag = tagReader.readTag();
 645        }
 646        if (nextTag != null && nextTag.isEnd("stream")) {
 647            streamCountDownLatch.countDown();
 648        }
 649    }
 650
 651    private boolean acknowledgeStanzaUpTo(int serverCount) {
 652        if (serverCount > stanzasSent) {
 653            Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
 654        }
 655        boolean acknowledgedMessages = false;
 656        for (int i = 0; i < mStanzaQueue.size(); ++i) {
 657            if (serverCount >= mStanzaQueue.keyAt(i)) {
 658                if (Config.EXTENDED_SM_LOGGING) {
 659                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 660                }
 661                AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 662                if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 663                    MessagePacket packet = (MessagePacket) stanza;
 664                    acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, packet.getId());
 665                }
 666                mStanzaQueue.removeAt(i);
 667                i--;
 668            }
 669        }
 670        return acknowledgedMessages;
 671    }
 672
 673    private @NonNull
 674    Element processPacket(final Tag currentTag, final int packetType) throws XmlPullParserException, IOException {
 675        Element element;
 676        switch (packetType) {
 677            case PACKET_IQ:
 678                element = new IqPacket();
 679                break;
 680            case PACKET_MESSAGE:
 681                element = new MessagePacket();
 682                break;
 683            case PACKET_PRESENCE:
 684                element = new PresencePacket();
 685                break;
 686            default:
 687                throw new AssertionError("Should never encounter invalid type");
 688        }
 689        element.setAttributes(currentTag.getAttributes());
 690        Tag nextTag = tagReader.readTag();
 691        if (nextTag == null) {
 692            throw new IOException("interrupted mid tag");
 693        }
 694        while (!nextTag.isEnd(element.getName())) {
 695            if (!nextTag.isNo()) {
 696                final Element child = tagReader.readElement(nextTag);
 697                final String type = currentTag.getAttribute("type");
 698                if (packetType == PACKET_IQ
 699                        && "jingle".equals(child.getName())
 700                        && ("set".equalsIgnoreCase(type) || "get"
 701                        .equalsIgnoreCase(type))) {
 702                    element = new JinglePacket();
 703                    element.setAttributes(currentTag.getAttributes());
 704                }
 705                element.addChild(child);
 706            }
 707            nextTag = tagReader.readTag();
 708            if (nextTag == null) {
 709                throw new IOException("interrupted mid tag");
 710            }
 711        }
 712        if (stanzasReceived == Integer.MAX_VALUE) {
 713            resetStreamId();
 714            throw new IOException("time to restart the session. cant handle >2 billion pcks");
 715        }
 716        if (inSmacksSession) {
 717            ++stanzasReceived;
 718        } else if (features.sm()) {
 719            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
 720        }
 721        lastPacketReceived = SystemClock.elapsedRealtime();
 722        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 723            Log.d(Config.LOGTAG, "[background stanza] " + element);
 724        }
 725        return element;
 726    }
 727
 728    private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
 729        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 730        if (!packet.valid()) {
 731            Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 732            return;
 733        }
 734        if (packet instanceof JinglePacket) {
 735            if (this.jingleListener != null) {
 736                this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
 737            }
 738        } else {
 739            OnIqPacketReceived callback = null;
 740            synchronized (this.packetCallbacks) {
 741                if (packetCallbacks.containsKey(packet.getId())) {
 742                    final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 743                    // Packets to the server should have responses from the server
 744                    if (packetCallbackDuple.first.toServer(account)) {
 745                        if (packet.fromServer(account)) {
 746                            callback = packetCallbackDuple.second;
 747                            packetCallbacks.remove(packet.getId());
 748                        } else {
 749                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 750                        }
 751                    } else {
 752                        if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 753                            callback = packetCallbackDuple.second;
 754                            packetCallbacks.remove(packet.getId());
 755                        } else {
 756                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 757                        }
 758                    }
 759                } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 760                    callback = this.unregisteredIqListener;
 761                }
 762            }
 763            if (callback != null) {
 764                try {
 765                    callback.onIqPacketReceived(account, packet);
 766                } catch (StateChangingError error) {
 767                    throw new StateChangingException(error.state);
 768                }
 769            }
 770        }
 771    }
 772
 773    private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 774        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
 775        if (!packet.valid()) {
 776            Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 777            return;
 778        }
 779        this.messageListener.onMessagePacketReceived(account, packet);
 780    }
 781
 782    private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 783        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 784        if (!packet.valid()) {
 785            Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 786            return;
 787        }
 788        this.presenceListener.onPresencePacketReceived(account, packet);
 789    }
 790
 791    private void sendStartTLS() throws IOException {
 792        final Tag startTLS = Tag.empty("starttls");
 793        startTLS.setAttribute("xmlns", Namespace.TLS);
 794        tagWriter.writeTag(startTLS);
 795    }
 796
 797    private void switchOverToTls() throws XmlPullParserException, IOException {
 798        tagReader.readTag();
 799        try {
 800            final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
 801            final InetAddress address = socket == null ? null : socket.getInetAddress();
 802
 803            if (address == null) {
 804                throw new IOException("could not setup ssl");
 805            }
 806
 807            final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 808
 809
 810            if (sslSocket == null) {
 811                throw new IOException("could not initialize ssl socket");
 812            }
 813
 814            SSLSocketHelper.setSecurity(sslSocket);
 815            SSLSocketHelper.setHostname(sslSocket, account.getServer());
 816            SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
 817
 818            if (!tlsFactoryVerifier.verifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 819                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 820                throw new StateChangingException(Account.State.TLS_ERROR);
 821            }
 822            tagReader.setInputStream(sslSocket.getInputStream());
 823            tagWriter.setOutputStream(sslSocket.getOutputStream());
 824            sendStartStream();
 825            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
 826            features.encryptionEnabled = true;
 827            final Tag tag = tagReader.readTag();
 828            if (tag != null && tag.isStart("stream")) {
 829                SSLSocketHelper.log(account, sslSocket);
 830                processStream();
 831            } else {
 832                throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 833            }
 834            sslSocket.close();
 835        } catch (final NoSuchAlgorithmException | KeyManagementException e1) {
 836            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 837            throw new StateChangingException(Account.State.TLS_ERROR);
 838        }
 839    }
 840
 841    private void processStreamFeatures(final Tag currentTag) throws XmlPullParserException, IOException {
 842        this.streamFeatures = tagReader.readElement(currentTag);
 843        final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS;
 844        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 845        if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 846            sendStartTLS();
 847        } else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 848            if (isSecure) {
 849                sendRegistryRequest();
 850            } else {
 851                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 852            }
 853        } else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 854            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 855        } else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
 856            authenticate();
 857        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 858            if (Config.EXTENDED_SM_LOGGING) {
 859                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
 860            }
 861            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 862            this.mSmCatchupMessageCounter.set(0);
 863            this.mWaitingForSmCatchup.set(true);
 864            this.tagWriter.writeStanzaAsync(resume);
 865        } else if (needsBinding) {
 866            if (this.streamFeatures.hasChild("bind") && isSecure) {
 867                sendBindRequest();
 868            } else {
 869                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 870            }
 871        }
 872    }
 873
 874    private void authenticate() throws IOException {
 875        final List<String> mechanisms = extractMechanisms(streamFeatures
 876                .findChild("mechanisms"));
 877        final Element auth = new Element("auth", Namespace.SASL);
 878        if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
 879            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 880        } else if (mechanisms.contains("SCRAM-SHA-256")) {
 881            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 882        } else if (mechanisms.contains("SCRAM-SHA-1")) {
 883            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 884        } else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().equals("nimbuzz.com")) {
 885            saslMechanism = new Plain(tagWriter, account);
 886        } else if (mechanisms.contains("DIGEST-MD5")) {
 887            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 888        } else if (mechanisms.contains("ANONYMOUS")) {
 889            saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
 890        }
 891        if (saslMechanism != null) {
 892            final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
 893            if (pinnedMechanism > saslMechanism.getPriority()) {
 894                Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 895                        " has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 896                        ") than pinned priority (" + pinnedMechanism +
 897                        "). Possible downgrade attack?");
 898                throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
 899            }
 900            Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 901            auth.setAttribute("mechanism", saslMechanism.getMechanism());
 902            if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 903                auth.setContent(saslMechanism.getClientFirstMessage());
 904            }
 905            tagWriter.writeElement(auth);
 906        } else {
 907            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 908        }
 909    }
 910
 911    private List<String> extractMechanisms(final Element stream) {
 912        final ArrayList<String> mechanisms = new ArrayList<>(stream
 913                .getChildren().size());
 914        for (final Element child : stream.getChildren()) {
 915            mechanisms.add(child.getContent());
 916        }
 917        return mechanisms;
 918    }
 919
 920    private void sendRegistryRequest() {
 921        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 922        register.query("jabber:iq:register");
 923        register.setTo(Jid.of(account.getServer()));
 924        sendUnmodifiedIqPacket(register, (account, packet) -> {
 925            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 926                return;
 927            }
 928            if (packet.getType() == IqPacket.TYPE.ERROR) {
 929                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 930            }
 931            final Element query = packet.query("jabber:iq:register");
 932            if (query.hasChild("username") && (query.hasChild("password"))) {
 933                final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
 934                final Element username = new Element("username").setContent(account.getUsername());
 935                final Element password = new Element("password").setContent(account.getPassword());
 936                register1.query("jabber:iq:register").addChild(username);
 937                register1.query().addChild(password);
 938                register1.setFrom(account.getJid().asBareJid());
 939                sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
 940            } else if (query.hasChild("x", Namespace.DATA)) {
 941                final Data data = Data.parse(query.findChild("x", Namespace.DATA));
 942                final Element blob = query.findChild("data", "urn:xmpp:bob");
 943                final String id = packet.getId();
 944                InputStream is;
 945                if (blob != null) {
 946                    try {
 947                        final String base64Blob = blob.getContent();
 948                        final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 949                        is = new ByteArrayInputStream(strBlob);
 950                    } catch (Exception e) {
 951                        is = null;
 952                    }
 953                } else {
 954                    try {
 955                        Field field = data.getFieldByName("url");
 956                        URL url = field != null && field.getValue() != null ? new URL(field.getValue()) : null;
 957                        is = url != null ? url.openStream() : null;
 958                    } catch (IOException e) {
 959                        is = null;
 960                    }
 961                }
 962
 963                if (is != null) {
 964                    Bitmap captcha = BitmapFactory.decodeStream(is);
 965                    try {
 966                        if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
 967                            return;
 968                        }
 969                    } catch (Exception e) {
 970                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 971                    }
 972                }
 973                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 974            } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
 975                final String instructions = query.findChildContent("instructions");
 976                final Element oob = query.findChild("x", Namespace.OOB);
 977                final String url = oob == null ? null : oob.findChildContent("url");
 978                if (url != null) {
 979                    setAccountCreationFailed(url);
 980                } else if (instructions != null) {
 981                    Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
 982                    if (matcher.find()) {
 983                        setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
 984                    }
 985                }
 986                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 987            }
 988        }, true);
 989    }
 990
 991    private void setAccountCreationFailed(String url) {
 992        if (url != null) {
 993            try {
 994                this.redirectionUrl = new URL(url);
 995                if (this.redirectionUrl.getProtocol().equals("https")) {
 996                    throw new StateChangingError(Account.State.REGISTRATION_WEB);
 997                }
 998            } catch (MalformedURLException e) {
 999                //fall through
1000            }
1001        }
1002        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1003    }
1004
1005    public URL getRedirectionUrl() {
1006        return this.redirectionUrl;
1007    }
1008
1009    public void resetEverything() {
1010        resetAttemptCount(true);
1011        resetStreamId();
1012        clearIqCallbacks();
1013        this.stanzasSent = 0;
1014        mStanzaQueue.clear();
1015        this.redirectionUrl = null;
1016        synchronized (this.disco) {
1017            disco.clear();
1018        }
1019    }
1020
1021    private void sendBindRequest() {
1022        try {
1023            mXmppConnectionService.restoredFromDatabaseLatch.await();
1024        } catch (InterruptedException e) {
1025            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1026            return;
1027        }
1028        clearIqCallbacks();
1029        if (account.getJid().isBareJid()) {
1030            account.setResource(this.createNewResource());
1031        } else {
1032            fixResource(mXmppConnectionService, account);
1033        }
1034        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1035        final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1036        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1037        this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1038            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1039                return;
1040            }
1041            final Element bind = packet.findChild("bind");
1042            if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1043                isBound = true;
1044                final Element jid = bind.findChild("jid");
1045                if (jid != null && jid.getContent() != null) {
1046                    try {
1047                        Jid assignedJid = Jid.ofEscaped(jid.getContent());
1048                        if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1049                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1050                            throw new StateChangingError(Account.State.BIND_FAILURE);
1051                        }
1052                        if (account.setJid(assignedJid)) {
1053                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1054                            mXmppConnectionService.databaseBackend.updateAccount(account);
1055                        }
1056                        if (streamFeatures.hasChild("session")
1057                                && !streamFeatures.findChild("session").hasChild("optional")) {
1058                            sendStartSession();
1059                        } else {
1060                            sendPostBindInitialization();
1061                        }
1062                        return;
1063                    } catch (final IllegalArgumentException e) {
1064                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1065                    }
1066                } else {
1067                    Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1068                }
1069            } else {
1070                Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1071            }
1072            final Element error = packet.findChild("error");
1073            if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1074                account.setResource(createNewResource());
1075            }
1076            throw new StateChangingError(Account.State.BIND_FAILURE);
1077        }, true);
1078    }
1079
1080    private void clearIqCallbacks() {
1081        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1082        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1083        synchronized (this.packetCallbacks) {
1084            if (this.packetCallbacks.size() == 0) {
1085                return;
1086            }
1087            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1088            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1089            while (iterator.hasNext()) {
1090                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1091                callbacks.add(entry.second);
1092                iterator.remove();
1093            }
1094        }
1095        for (OnIqPacketReceived callback : callbacks) {
1096            try {
1097                callback.onIqPacketReceived(account, failurePacket);
1098            } catch (StateChangingError error) {
1099                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1100                //ignore
1101            }
1102        }
1103        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1104    }
1105
1106    public void sendDiscoTimeout() {
1107        if (mWaitForDisco.compareAndSet(true, false)) {
1108            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1109            finalizeBind();
1110        }
1111    }
1112
1113    private void sendStartSession() {
1114        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1115        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1116        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1117        this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1118            if (packet.getType() == IqPacket.TYPE.RESULT) {
1119                sendPostBindInitialization();
1120            } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1121                throw new StateChangingError(Account.State.SESSION_FAILURE);
1122            }
1123        }, true);
1124    }
1125
1126    private void sendPostBindInitialization() {
1127        smVersion = 0;
1128        if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1129            smVersion = 3;
1130        } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1131            smVersion = 2;
1132        }
1133        if (smVersion != 0) {
1134            synchronized (this.mStanzaQueue) {
1135                final EnablePacket enable = new EnablePacket(smVersion);
1136                tagWriter.writeStanzaAsync(enable);
1137                stanzasSent = 0;
1138                mStanzaQueue.clear();
1139            }
1140        }
1141        features.carbonsEnabled = false;
1142        features.blockListRequested = false;
1143        synchronized (this.disco) {
1144            this.disco.clear();
1145        }
1146        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1147        mPendingServiceDiscoveries.set(0);
1148        if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain())) {
1149            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1150            mWaitForDisco.set(false);
1151        } else {
1152            mWaitForDisco.set(true);
1153        }
1154        lastDiscoStarted = SystemClock.elapsedRealtime();
1155        mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1156        Element caps = streamFeatures.findChild("c");
1157        final String hash = caps == null ? null : caps.getAttribute("hash");
1158        final String ver = caps == null ? null : caps.getAttribute("ver");
1159        ServiceDiscoveryResult discoveryResult = null;
1160        if (hash != null && ver != null) {
1161            discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1162        }
1163        final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1164        if (requestDiscoItemsFirst) {
1165            sendServiceDiscoveryItems(Jid.of(account.getServer()));
1166        }
1167        if (discoveryResult == null) {
1168            sendServiceDiscoveryInfo(Jid.of(account.getServer()));
1169        } else {
1170            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1171            disco.put(Jid.of(account.getServer()), discoveryResult);
1172        }
1173        discoverMamPreferences();
1174        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1175        if (!requestDiscoItemsFirst) {
1176            sendServiceDiscoveryItems(Jid.of(account.getServer()));
1177        }
1178
1179        if (!mWaitForDisco.get()) {
1180            finalizeBind();
1181        }
1182        this.lastSessionStarted = SystemClock.elapsedRealtime();
1183    }
1184
1185    private void sendServiceDiscoveryInfo(final Jid jid) {
1186        mPendingServiceDiscoveries.incrementAndGet();
1187        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1188        iq.setTo(jid);
1189        iq.query("http://jabber.org/protocol/disco#info");
1190        this.sendIqPacket(iq, (account, packet) -> {
1191            if (packet.getType() == IqPacket.TYPE.RESULT) {
1192                boolean advancedStreamFeaturesLoaded;
1193                synchronized (XmppConnection.this.disco) {
1194                    ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1195                    if (jid.equals(Jid.of(account.getServer()))) {
1196                        mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1197                    }
1198                    disco.put(jid, result);
1199                    advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer()))
1200                            && disco.containsKey(account.getJid().asBareJid());
1201                }
1202                if (advancedStreamFeaturesLoaded && (jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid()))) {
1203                    enableAdvancedStreamFeatures();
1204                }
1205            } else {
1206                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1207            }
1208            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1209                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1210                        && mWaitForDisco.compareAndSet(true, false)) {
1211                    finalizeBind();
1212                }
1213            }
1214        });
1215    }
1216
1217    private void discoverMamPreferences() {
1218        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1219        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1220        sendIqPacket(request, (account, response) -> {
1221           if (response.getType() == IqPacket.TYPE.RESULT) {
1222               Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1223               isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1224           }
1225        });
1226    }
1227
1228    public boolean isMamPreferenceAlways() {
1229        return isMamPreferenceAlways;
1230    }
1231
1232    private void finalizeBind() {
1233        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1234        if (bindListener != null) {
1235            bindListener.onBind(account);
1236        }
1237        changeStatus(Account.State.ONLINE);
1238    }
1239
1240    private void enableAdvancedStreamFeatures() {
1241        if (getFeatures().carbons() && !features.carbonsEnabled) {
1242            sendEnableCarbons();
1243        }
1244        if (getFeatures().blocking() && !features.blockListRequested) {
1245            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1246            this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1247        }
1248        for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1249            listener.onAdvancedStreamFeaturesAvailable(account);
1250        }
1251    }
1252
1253    private void sendServiceDiscoveryItems(final Jid server) {
1254        mPendingServiceDiscoveries.incrementAndGet();
1255        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1256        iq.setTo(Jid.ofDomain(server.getDomain()));
1257        iq.query("http://jabber.org/protocol/disco#items");
1258        this.sendIqPacket(iq, (account, packet) -> {
1259            if (packet.getType() == IqPacket.TYPE.RESULT) {
1260                HashSet<Jid> items = new HashSet<Jid>();
1261                final List<Element> elements = packet.query().getChildren();
1262                for (final Element element : elements) {
1263                    if (element.getName().equals("item")) {
1264                        final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1265                        if (jid != null && !jid.equals(Jid.of(account.getServer()))) {
1266                            items.add(jid);
1267                        }
1268                    }
1269                }
1270                for (Jid jid : items) {
1271                    sendServiceDiscoveryInfo(jid);
1272                }
1273            } else {
1274                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1275            }
1276            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1277                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1278                        && mWaitForDisco.compareAndSet(true, false)) {
1279                    finalizeBind();
1280                }
1281            }
1282        });
1283    }
1284
1285    private void sendEnableCarbons() {
1286        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1287        iq.addChild("enable", "urn:xmpp:carbons:2");
1288        this.sendIqPacket(iq, new OnIqPacketReceived() {
1289
1290            @Override
1291            public void onIqPacketReceived(final Account account, final IqPacket packet) {
1292                if (!packet.hasChild("error")) {
1293                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1294                            + ": successfully enabled carbons");
1295                    features.carbonsEnabled = true;
1296                } else {
1297                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1298                            + ": error enableing carbons " + packet.toString());
1299                }
1300            }
1301        });
1302    }
1303
1304    private void processStreamError(final Tag currentTag) throws XmlPullParserException, IOException {
1305        final Element streamError = tagReader.readElement(currentTag);
1306        if (streamError == null) {
1307            return;
1308        }
1309        if (streamError.hasChild("conflict")) {
1310            account.setResource(createNewResource());
1311            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1312            throw new IOException();
1313        } else if (streamError.hasChild("host-unknown")) {
1314            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1315        } else if (streamError.hasChild("policy-violation")) { ;
1316            final String text = streamError.findChildContent("text");
1317            if (text != null) {
1318                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": policy violation. "+text);
1319            }
1320            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1321        } else {
1322            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1323            throw new StateChangingException(Account.State.STREAM_ERROR);
1324        }
1325    }
1326
1327    private void sendStartStream() throws IOException {
1328        final Tag stream = Tag.start("stream:stream");
1329        stream.setAttribute("to", account.getServer());
1330        stream.setAttribute("version", "1.0");
1331        stream.setAttribute("xml:lang", "en");
1332        stream.setAttribute("xmlns", "jabber:client");
1333        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1334        tagWriter.writeTag(stream);
1335    }
1336
1337    private String createNewResource() {
1338        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1339    }
1340
1341    private String nextRandomId() {
1342        return nextRandomId(false);
1343    }
1344
1345    private String nextRandomId(boolean s) {
1346        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1347    }
1348
1349    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1350        packet.setFrom(account.getJid());
1351        return this.sendUnmodifiedIqPacket(packet, callback, false);
1352    }
1353
1354    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1355        if (packet.getId() == null) {
1356            packet.setAttribute("id", nextRandomId());
1357        }
1358        if (callback != null) {
1359            synchronized (this.packetCallbacks) {
1360                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1361            }
1362        }
1363        this.sendPacket(packet, force);
1364        return packet.getId();
1365    }
1366
1367    public void sendMessagePacket(final MessagePacket packet) {
1368        this.sendPacket(packet);
1369    }
1370
1371    public void sendPresencePacket(final PresencePacket packet) {
1372        this.sendPacket(packet);
1373    }
1374
1375    private synchronized void sendPacket(final AbstractStanza packet) {
1376        sendPacket(packet, false);
1377    }
1378
1379    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1380        if (stanzasSent == Integer.MAX_VALUE) {
1381            resetStreamId();
1382            disconnect(true);
1383            return;
1384        }
1385        synchronized (this.mStanzaQueue) {
1386            if (force || isBound) {
1387                tagWriter.writeStanzaAsync(packet);
1388            } else {
1389                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1390            }
1391            if (packet instanceof AbstractAcknowledgeableStanza) {
1392                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1393
1394                if (this.mStanzaQueue.size() != 0) {
1395                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1396                    if (currentHighestKey != stanzasSent) {
1397                        throw new AssertionError("Stanza count messed up");
1398                    }
1399                }
1400
1401                ++stanzasSent;
1402                this.mStanzaQueue.append(stanzasSent, stanza);
1403                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1404                    if (Config.EXTENDED_SM_LOGGING) {
1405                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1406                    }
1407                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1408                }
1409            }
1410        }
1411    }
1412
1413    public void sendPing() {
1414        if (!r()) {
1415            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1416            iq.setFrom(account.getJid());
1417            iq.addChild("ping", "urn:xmpp:ping");
1418            this.sendIqPacket(iq, null);
1419        }
1420        this.lastPingSent = SystemClock.elapsedRealtime();
1421    }
1422
1423    public void setOnMessagePacketReceivedListener(
1424            final OnMessagePacketReceived listener) {
1425        this.messageListener = listener;
1426    }
1427
1428    public void setOnUnregisteredIqPacketReceivedListener(
1429            final OnIqPacketReceived listener) {
1430        this.unregisteredIqListener = listener;
1431    }
1432
1433    public void setOnPresencePacketReceivedListener(
1434            final OnPresencePacketReceived listener) {
1435        this.presenceListener = listener;
1436    }
1437
1438    public void setOnJinglePacketReceivedListener(
1439            final OnJinglePacketReceived listener) {
1440        this.jingleListener = listener;
1441    }
1442
1443    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1444        this.statusListener = listener;
1445    }
1446
1447    public void setOnBindListener(final OnBindListener listener) {
1448        this.bindListener = listener;
1449    }
1450
1451    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1452        this.acknowledgedListener = listener;
1453    }
1454
1455    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1456        this.advancedStreamFeaturesLoadedListeners.add(listener);
1457    }
1458
1459    private void forceCloseSocket() {
1460        if (socket != null) {
1461            try {
1462                socket.close();
1463            } catch (IOException e) {
1464                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception " + e.getMessage() + " during force close");
1465            }
1466        } else {
1467            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": socket was null during force close");
1468        }
1469    }
1470
1471    public void interrupt() {
1472        if (this.mThread != null) {
1473            this.mThread.interrupt();
1474        }
1475    }
1476
1477    public void disconnect(final boolean force) {
1478        interrupt();
1479        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + Boolean.toString(force));
1480        if (force) {
1481            forceCloseSocket();
1482        } else {
1483            final TagWriter currentTagWriter = this.tagWriter;
1484            if (currentTagWriter.isActive()) {
1485                currentTagWriter.finish();
1486                final Socket currentSocket = this.socket;
1487                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1488                try {
1489                    currentTagWriter.await(1, TimeUnit.SECONDS);
1490                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1491                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1492                    if (streamCountDownLatch != null) {
1493                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1494                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1495                        } else {
1496                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1497                        }
1498                    }
1499                } catch (InterruptedException e) {
1500                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1501                } catch (final IOException e) {
1502                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1503                } finally {
1504                    FileBackend.close(currentSocket);
1505                }
1506            } else {
1507                forceCloseSocket();
1508            }
1509        }
1510    }
1511
1512    private void resetStreamId() {
1513        this.streamId = null;
1514    }
1515
1516    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1517        synchronized (this.disco) {
1518            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1519            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1520                if (cursor.getValue().getFeatures().contains(feature)) {
1521                    items.add(cursor);
1522                }
1523            }
1524            return items;
1525        }
1526    }
1527
1528    public Jid findDiscoItemByFeature(final String feature) {
1529        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1530        if (items.size() >= 1) {
1531            return items.get(0).getKey();
1532        }
1533        return null;
1534    }
1535
1536    public boolean r() {
1537        if (getFeatures().sm()) {
1538            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1539            return true;
1540        } else {
1541            return false;
1542        }
1543    }
1544
1545    public List<String> getMucServersWithholdAccount() {
1546        List<String> servers = getMucServers();
1547        servers.remove(account.getServer());
1548        return servers;
1549    }
1550
1551    public List<String> getMucServers() {
1552        List<String> servers = new ArrayList<>();
1553        synchronized (this.disco) {
1554            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1555                final ServiceDiscoveryResult value = cursor.getValue();
1556                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1557                        && value.hasIdentity("conference", "text")
1558                        && !value.getFeatures().contains("jabber:iq:gateway")
1559                        && !value.hasIdentity("conference", "irc")) {
1560                    servers.add(cursor.getKey().toString());
1561                }
1562            }
1563        }
1564        return servers;
1565    }
1566
1567    public String getMucServer() {
1568        List<String> servers = getMucServers();
1569        return servers.size() > 0 ? servers.get(0) : null;
1570    }
1571
1572    public int getTimeToNextAttempt() {
1573        final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1574        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1575        return interval - secondsSinceLast;
1576    }
1577
1578    public int getAttempt() {
1579        return this.attempt;
1580    }
1581
1582    public Features getFeatures() {
1583        return this.features;
1584    }
1585
1586    public long getLastSessionEstablished() {
1587        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1588        return System.currentTimeMillis() - diff;
1589    }
1590
1591    public long getLastConnect() {
1592        return this.lastConnect;
1593    }
1594
1595    public long getLastPingSent() {
1596        return this.lastPingSent;
1597    }
1598
1599    public long getLastDiscoStarted() {
1600        return this.lastDiscoStarted;
1601    }
1602
1603    public long getLastPacketReceived() {
1604        return this.lastPacketReceived;
1605    }
1606
1607    public void sendActive() {
1608        this.sendPacket(new ActivePacket());
1609    }
1610
1611    public void sendInactive() {
1612        this.sendPacket(new InactivePacket());
1613    }
1614
1615    public void resetAttemptCount(boolean resetConnectTime) {
1616        this.attempt = 0;
1617        if (resetConnectTime) {
1618            this.lastConnect = 0;
1619        }
1620    }
1621
1622    public void setInteractive(boolean interactive) {
1623        this.mInteractive = interactive;
1624    }
1625
1626    public Identity getServerIdentity() {
1627        synchronized (this.disco) {
1628            ServiceDiscoveryResult result = disco.get(Jid.ofDomain(account.getJid().getDomain()));
1629            if (result == null) {
1630                return Identity.UNKNOWN;
1631            }
1632            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1633                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1634                    switch (id.getName()) {
1635                        case "Prosody":
1636                            return Identity.PROSODY;
1637                        case "ejabberd":
1638                            return Identity.EJABBERD;
1639                        case "Slack-XMPP":
1640                            return Identity.SLACK;
1641                    }
1642                }
1643            }
1644        }
1645        return Identity.UNKNOWN;
1646    }
1647
1648    private IqGenerator getIqGenerator() {
1649        return mXmppConnectionService.getIqGenerator();
1650    }
1651
1652    public enum Identity {
1653        FACEBOOK,
1654        SLACK,
1655        EJABBERD,
1656        PROSODY,
1657        NIMBUZZ,
1658        UNKNOWN
1659    }
1660
1661    private static class TlsFactoryVerifier {
1662        private final SSLSocketFactory factory;
1663        private final DomainHostnameVerifier verifier;
1664
1665        TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
1666            this.factory = factory;
1667            this.verifier = verifier;
1668            if (factory == null || verifier == null) {
1669                throw new IOException("could not setup ssl");
1670            }
1671        }
1672    }
1673
1674    private class MyKeyManager implements X509KeyManager {
1675        @Override
1676        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1677            return account.getPrivateKeyAlias();
1678        }
1679
1680        @Override
1681        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1682            return null;
1683        }
1684
1685        @Override
1686        public X509Certificate[] getCertificateChain(String alias) {
1687            Log.d(Config.LOGTAG, "getting certificate chain");
1688            try {
1689                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1690            } catch (Exception e) {
1691                Log.d(Config.LOGTAG, e.getMessage());
1692                return new X509Certificate[0];
1693            }
1694        }
1695
1696        @Override
1697        public String[] getClientAliases(String s, Principal[] principals) {
1698            final String alias = account.getPrivateKeyAlias();
1699            return alias != null ? new String[]{alias} : new String[0];
1700        }
1701
1702        @Override
1703        public String[] getServerAliases(String s, Principal[] principals) {
1704            return new String[0];
1705        }
1706
1707        @Override
1708        public PrivateKey getPrivateKey(String alias) {
1709            try {
1710                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1711            } catch (Exception e) {
1712                return null;
1713            }
1714        }
1715    }
1716
1717    private class StateChangingError extends Error {
1718        private final Account.State state;
1719
1720        public StateChangingError(Account.State state) {
1721            this.state = state;
1722        }
1723    }
1724
1725    private class StateChangingException extends IOException {
1726        private final Account.State state;
1727
1728        public StateChangingException(Account.State state) {
1729            this.state = state;
1730        }
1731    }
1732
1733    public class Features {
1734        XmppConnection connection;
1735        private boolean carbonsEnabled = false;
1736        private boolean encryptionEnabled = false;
1737        private boolean blockListRequested = false;
1738
1739        public Features(final XmppConnection connection) {
1740            this.connection = connection;
1741        }
1742
1743        private boolean hasDiscoFeature(final Jid server, final String feature) {
1744            synchronized (XmppConnection.this.disco) {
1745                return connection.disco.containsKey(server) &&
1746                        connection.disco.get(server).getFeatures().contains(feature);
1747            }
1748        }
1749
1750        public boolean carbons() {
1751            return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:carbons:2");
1752        }
1753
1754        public boolean bookmarksConversion() {
1755            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1756        }
1757
1758        public boolean blocking() {
1759            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.BLOCKING);
1760        }
1761
1762        public boolean spamReporting() {
1763            return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:reporting:reason:spam:0");
1764        }
1765
1766        public boolean flexibleOfflineMessageRetrieval() {
1767            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1768        }
1769
1770        public boolean register() {
1771            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.REGISTER);
1772        }
1773
1774        public boolean sm() {
1775            return streamId != null
1776                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1777        }
1778
1779        public boolean csi() {
1780            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1781        }
1782
1783        public boolean pep() {
1784            synchronized (XmppConnection.this.disco) {
1785                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1786                return info != null && info.hasIdentity("pubsub", "pep");
1787            }
1788        }
1789
1790        public boolean pepPersistent() {
1791            synchronized (XmppConnection.this.disco) {
1792                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1793                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1794            }
1795        }
1796
1797        public boolean pepPublishOptions() {
1798            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1799        }
1800
1801        public boolean pepOmemoWhitelisted() {
1802            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1803        }
1804
1805        public boolean mam() {
1806            return MessageArchiveService.Version.has(getAccountFeatures());
1807        }
1808
1809        public List<String> getAccountFeatures() {
1810            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1811            return result == null ? Collections.emptyList() : result.getFeatures();
1812        }
1813
1814        public boolean push() {
1815            return hasDiscoFeature(account.getJid().asBareJid(), "urn:xmpp:push:0")
1816                    || hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:push:0");
1817        }
1818
1819        public boolean rosterVersioning() {
1820            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1821        }
1822
1823        public void setBlockListRequested(boolean value) {
1824            this.blockListRequested = value;
1825        }
1826
1827        public boolean p1S3FileTransfer() {
1828            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.P1_S3_FILE_TRANSFER);
1829        }
1830
1831        public boolean httpUpload(long filesize) {
1832            if (Config.DISABLE_HTTP_UPLOAD) {
1833                return false;
1834            } else {
1835                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1836                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1837                    if (items.size() > 0) {
1838                        try {
1839                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1840                            if (filesize <= maxsize) {
1841                                return true;
1842                            } else {
1843                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1844                                return false;
1845                            }
1846                        } catch (Exception e) {
1847                            return true;
1848                        }
1849                    }
1850                }
1851                return false;
1852            }
1853        }
1854
1855        public boolean useLegacyHttpUpload() {
1856            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1857        }
1858
1859        public long getMaxHttpUploadSize() {
1860            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1861                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1862                if (items.size() > 0) {
1863                    try {
1864                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1865                    } catch (Exception e) {
1866                        //ignored
1867                    }
1868                }
1869            }
1870            return -1;
1871        }
1872
1873        public boolean stanzaIds() {
1874            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1875        }
1876    }
1877}