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