XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
   4
   5import android.content.Context;
   6import android.graphics.Bitmap;
   7import android.graphics.BitmapFactory;
   8import android.os.Build;
   9import android.os.SystemClock;
  10import android.security.KeyChain;
  11import android.util.Base64;
  12import android.util.Log;
  13import android.util.Pair;
  14import android.util.SparseArray;
  15
  16import androidx.annotation.NonNull;
  17import androidx.annotation.Nullable;
  18
  19import com.google.common.base.Strings;
  20
  21import org.xmlpull.v1.XmlPullParserException;
  22
  23import java.io.ByteArrayInputStream;
  24import java.io.IOException;
  25import java.io.InputStream;
  26import java.net.ConnectException;
  27import java.net.IDN;
  28import java.net.InetAddress;
  29import java.net.InetSocketAddress;
  30import java.net.Socket;
  31import java.net.UnknownHostException;
  32import java.security.KeyManagementException;
  33import java.security.NoSuchAlgorithmException;
  34import java.security.Principal;
  35import java.security.PrivateKey;
  36import java.security.cert.X509Certificate;
  37import java.util.ArrayList;
  38import java.util.Arrays;
  39import java.util.Collection;
  40import java.util.Collections;
  41import java.util.HashMap;
  42import java.util.HashSet;
  43import java.util.Hashtable;
  44import java.util.Iterator;
  45import java.util.List;
  46import java.util.Map.Entry;
  47import java.util.Set;
  48import java.util.concurrent.CountDownLatch;
  49import java.util.concurrent.TimeUnit;
  50import java.util.concurrent.atomic.AtomicBoolean;
  51import java.util.concurrent.atomic.AtomicInteger;
  52import java.util.regex.Matcher;
  53
  54import javax.net.ssl.KeyManager;
  55import javax.net.ssl.SSLContext;
  56import javax.net.ssl.SSLPeerUnverifiedException;
  57import javax.net.ssl.SSLSocket;
  58import javax.net.ssl.SSLSocketFactory;
  59import javax.net.ssl.X509KeyManager;
  60import javax.net.ssl.X509TrustManager;
  61
  62import eu.siacs.conversations.Config;
  63import eu.siacs.conversations.R;
  64import eu.siacs.conversations.crypto.XmppDomainVerifier;
  65import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  66import eu.siacs.conversations.crypto.sasl.ChannelBinding;
  67import eu.siacs.conversations.crypto.sasl.HashedToken;
  68import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  69import eu.siacs.conversations.entities.Account;
  70import eu.siacs.conversations.entities.Message;
  71import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  72import eu.siacs.conversations.generator.IqGenerator;
  73import eu.siacs.conversations.http.HttpConnectionManager;
  74import eu.siacs.conversations.persistance.FileBackend;
  75import eu.siacs.conversations.services.MemorizingTrustManager;
  76import eu.siacs.conversations.services.MessageArchiveService;
  77import eu.siacs.conversations.services.NotificationService;
  78import eu.siacs.conversations.services.XmppConnectionService;
  79import eu.siacs.conversations.utils.CryptoHelper;
  80import eu.siacs.conversations.utils.Patterns;
  81import eu.siacs.conversations.utils.PhoneHelper;
  82import eu.siacs.conversations.utils.Resolver;
  83import eu.siacs.conversations.utils.SSLSockets;
  84import eu.siacs.conversations.utils.SocksSocketFactory;
  85import eu.siacs.conversations.utils.XmlHelper;
  86import eu.siacs.conversations.xml.Element;
  87import eu.siacs.conversations.xml.LocalizedContent;
  88import eu.siacs.conversations.xml.Namespace;
  89import eu.siacs.conversations.xml.Tag;
  90import eu.siacs.conversations.xml.TagWriter;
  91import eu.siacs.conversations.xml.XmlReader;
  92import eu.siacs.conversations.xmpp.bind.Bind2;
  93import eu.siacs.conversations.xmpp.forms.Data;
  94import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  95import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  96import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  97import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  98import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  99import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 100import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 101import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
 102import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
 103import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
 104import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
 105import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
 106import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
 107import okhttp3.HttpUrl;
 108
 109public class XmppConnection implements Runnable {
 110
 111    private static final int PACKET_IQ = 0;
 112    private static final int PACKET_MESSAGE = 1;
 113    private static final int PACKET_PRESENCE = 2;
 114    public final OnIqPacketReceived registrationResponseListener =
 115            (account, packet) -> {
 116                if (packet.getType() == IqPacket.TYPE.RESULT) {
 117                    account.setOption(Account.OPTION_REGISTER, false);
 118                    Log.d(
 119                            Config.LOGTAG,
 120                            account.getJid().asBareJid()
 121                                    + ": successfully registered new account on server");
 122                    throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 123                } else {
 124                    final List<String> PASSWORD_TOO_WEAK_MSGS =
 125                            Arrays.asList(
 126                                    "The password is too weak", "Please use a longer password.");
 127                    Element error = packet.findChild("error");
 128                    Account.State state = Account.State.REGISTRATION_FAILED;
 129                    if (error != null) {
 130                        if (error.hasChild("conflict")) {
 131                            state = Account.State.REGISTRATION_CONFLICT;
 132                        } else if (error.hasChild("resource-constraint")
 133                                && "wait".equals(error.getAttribute("type"))) {
 134                            state = Account.State.REGISTRATION_PLEASE_WAIT;
 135                        } else if (error.hasChild("not-acceptable")
 136                                && PASSWORD_TOO_WEAK_MSGS.contains(
 137                                        error.findChildContent("text"))) {
 138                            state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 139                        }
 140                    }
 141                    throw new StateChangingError(state);
 142                }
 143            };
 144    protected final Account account;
 145    private final Features features = new Features(this);
 146    private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 147    private final HashMap<String, Jid> commands = new HashMap<>();
 148    private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 149    private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks =
 150            new Hashtable<>();
 151    private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners =
 152            new HashSet<>();
 153    private final XmppConnectionService mXmppConnectionService;
 154    private Socket socket;
 155    private XmlReader tagReader;
 156    private TagWriter tagWriter = new TagWriter();
 157    private boolean shouldAuthenticate = true;
 158    private boolean inSmacksSession = false;
 159    private boolean quickStartInProgress = false;
 160    private boolean isBound = false;
 161    private Element streamFeatures;
 162    private String streamId = null;
 163    private int stanzasReceived = 0;
 164    private int stanzasSent = 0;
 165    private long lastPacketReceived = 0;
 166    private long lastPingSent = 0;
 167    private long lastConnect = 0;
 168    private long lastSessionStarted = 0;
 169    private long lastDiscoStarted = 0;
 170    private boolean isMamPreferenceAlways = false;
 171    private final AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
 172    private final AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 173    private final AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 174    private final AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 175    private boolean mInteractive = false;
 176    private int attempt = 0;
 177    private OnPresencePacketReceived presenceListener = null;
 178    private OnJinglePacketReceived jingleListener = null;
 179    private OnIqPacketReceived unregisteredIqListener = null;
 180    private OnMessagePacketReceived messageListener = null;
 181    private OnStatusChanged statusListener = null;
 182    private OnBindListener bindListener = null;
 183    private OnMessageAcknowledged acknowledgedListener = null;
 184    private SaslMechanism saslMechanism;
 185    private HashedToken.Mechanism hashTokenRequest;
 186    private HttpUrl redirectionUrl = null;
 187    private String verifiedHostname = null;
 188    private volatile Thread mThread;
 189    private CountDownLatch mStreamCountDownLatch;
 190
 191    public XmppConnection(final Account account, final XmppConnectionService service) {
 192        this.account = account;
 193        this.mXmppConnectionService = service;
 194    }
 195
 196    private static void fixResource(Context context, Account account) {
 197        String resource = account.getResource();
 198        int fixedPartLength =
 199                context.getString(R.string.app_name).length() + 1; // include the trailing dot
 200        int randomPartLength = 4; // 3 bytes
 201        if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
 202            if (validBase64(
 203                    resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
 204                account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
 205            }
 206        }
 207    }
 208
 209    private static boolean validBase64(String input) {
 210        try {
 211            return Base64.decode(input, Base64.URL_SAFE).length == 3;
 212        } catch (Throwable throwable) {
 213            return false;
 214        }
 215    }
 216
 217    private void changeStatus(final Account.State nextStatus) {
 218        synchronized (this) {
 219            if (Thread.currentThread().isInterrupted()) {
 220                Log.d(
 221                        Config.LOGTAG,
 222                        account.getJid().asBareJid()
 223                                + ": not changing status to "
 224                                + nextStatus
 225                                + " because thread was interrupted");
 226                return;
 227            }
 228            if (account.getStatus() != nextStatus) {
 229                if ((nextStatus == Account.State.OFFLINE)
 230                        && (account.getStatus() != Account.State.CONNECTING)
 231                        && (account.getStatus() != Account.State.ONLINE)
 232                        && (account.getStatus() != Account.State.DISABLED)) {
 233                    return;
 234                }
 235                if (nextStatus == Account.State.ONLINE) {
 236                    this.attempt = 0;
 237                }
 238                account.setStatus(nextStatus);
 239            } else {
 240                return;
 241            }
 242        }
 243        if (statusListener != null) {
 244            statusListener.onStatusChanged(account);
 245        }
 246    }
 247
 248    public Jid getJidForCommand(final String node) {
 249        synchronized (this.commands) {
 250            return this.commands.get(node);
 251        }
 252    }
 253
 254    public void prepareNewConnection() {
 255        this.lastConnect = SystemClock.elapsedRealtime();
 256        this.lastPingSent = SystemClock.elapsedRealtime();
 257        this.lastDiscoStarted = Long.MAX_VALUE;
 258        this.mWaitingForSmCatchup.set(false);
 259        this.changeStatus(Account.State.CONNECTING);
 260    }
 261
 262    public boolean isWaitingForSmCatchup() {
 263        return mWaitingForSmCatchup.get();
 264    }
 265
 266    public void incrementSmCatchupMessageCounter() {
 267        this.mSmCatchupMessageCounter.incrementAndGet();
 268    }
 269
 270    protected void connect() {
 271        if (mXmppConnectionService.areMessagesInitialized()) {
 272            mXmppConnectionService.resetSendingToWaiting(account);
 273        }
 274        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
 275        features.encryptionEnabled = false;
 276        this.inSmacksSession = false;
 277        this.quickStartInProgress = false;
 278        this.isBound = false;
 279        this.attempt++;
 280        this.verifiedHostname = null; // will be set if user entered hostname is being used or hostname was verified
 281        // with dnssec
 282        try {
 283            Socket localSocket;
 284            shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
 285            this.changeStatus(Account.State.CONNECTING);
 286            final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 287            final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
 288            if (useTor) {
 289                String destination;
 290                if (account.getHostname().isEmpty() || account.isOnion()) {
 291                    destination = account.getServer();
 292                } else {
 293                    destination = account.getHostname();
 294                    this.verifiedHostname = destination;
 295                }
 296
 297                final int port = account.getPort();
 298                final boolean directTls = Resolver.useDirectTls(port);
 299
 300                Log.d(
 301                        Config.LOGTAG,
 302                        account.getJid().asBareJid()
 303                                + ": connect to "
 304                                + destination
 305                                + " via Tor. directTls="
 306                                + directTls);
 307                localSocket = SocksSocketFactory.createSocketOverTor(destination, port);
 308
 309                if (directTls) {
 310                    localSocket = upgradeSocketToTls(localSocket);
 311                    features.encryptionEnabled = true;
 312                }
 313
 314                try {
 315                    startXmpp(localSocket);
 316                } catch (final InterruptedException e) {
 317                    Log.d(
 318                            Config.LOGTAG,
 319                            account.getJid().asBareJid()
 320                                    + ": thread was interrupted before beginning stream");
 321                    return;
 322                } catch (final Exception e) {
 323                    throw new IOException("Could not start stream", e);
 324                }
 325            } else {
 326                final String domain = account.getServer();
 327                final List<Resolver.Result> results;
 328                final boolean hardcoded = extended && !account.getHostname().isEmpty();
 329                if (hardcoded) {
 330                    results = Resolver.fromHardCoded(account.getHostname(), account.getPort());
 331                } else {
 332                    results = Resolver.resolve(domain);
 333                }
 334                if (Thread.currentThread().isInterrupted()) {
 335                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 336                    return;
 337                }
 338                if (results.size() == 0) {
 339                    Log.e(
 340                            Config.LOGTAG,
 341                            account.getJid().asBareJid() + ": Resolver results were empty");
 342                    return;
 343                }
 344                final Resolver.Result storedBackupResult;
 345                if (hardcoded) {
 346                    storedBackupResult = null;
 347                } else {
 348                    storedBackupResult =
 349                            mXmppConnectionService.databaseBackend.findResolverResult(domain);
 350                    if (storedBackupResult != null && !results.contains(storedBackupResult)) {
 351                        results.add(storedBackupResult);
 352                        Log.d(
 353                                Config.LOGTAG,
 354                                account.getJid().asBareJid()
 355                                        + ": loaded backup resolver result from db: "
 356                                        + storedBackupResult);
 357                    }
 358                }
 359                for (Iterator<Resolver.Result> iterator = results.iterator();
 360                        iterator.hasNext(); ) {
 361                    final Resolver.Result result = iterator.next();
 362                    if (Thread.currentThread().isInterrupted()) {
 363                        Log.d(
 364                                Config.LOGTAG,
 365                                account.getJid().asBareJid() + ": Thread was interrupted");
 366                        return;
 367                    }
 368                    try {
 369                        // if tls is true, encryption is implied and must not be started
 370                        features.encryptionEnabled = result.isDirectTls();
 371                        verifiedHostname =
 372                                result.isAuthenticated() ? result.getHostname().toString() : null;
 373                        Log.d(Config.LOGTAG, "verified hostname " + verifiedHostname);
 374                        final InetSocketAddress addr;
 375                        if (result.getIp() != null) {
 376                            addr = new InetSocketAddress(result.getIp(), result.getPort());
 377                            Log.d(
 378                                    Config.LOGTAG,
 379                                    account.getJid().asBareJid().toString()
 380                                            + ": using values from resolver "
 381                                            + (result.getHostname() == null
 382                                                    ? ""
 383                                                    : result.getHostname().toString() + "/")
 384                                            + result.getIp().getHostAddress()
 385                                            + ":"
 386                                            + result.getPort()
 387                                            + " tls: "
 388                                            + features.encryptionEnabled);
 389                        } else {
 390                            addr =
 391                                    new InetSocketAddress(
 392                                            IDN.toASCII(result.getHostname().toString()),
 393                                            result.getPort());
 394                            Log.d(
 395                                    Config.LOGTAG,
 396                                    account.getJid().asBareJid().toString()
 397                                            + ": using values from resolver "
 398                                            + result.getHostname().toString()
 399                                            + ":"
 400                                            + result.getPort()
 401                                            + " tls: "
 402                                            + features.encryptionEnabled);
 403                        }
 404
 405                        localSocket = new Socket();
 406                        localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 407
 408                        if (features.encryptionEnabled) {
 409                            localSocket = upgradeSocketToTls(localSocket);
 410                        }
 411
 412                        localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
 413                        if (startXmpp(localSocket)) {
 414                            localSocket.setSoTimeout(
 415                                    0); // reset to 0; once the connection is established we don’t
 416                            // want this
 417                            if (!hardcoded && !result.equals(storedBackupResult)) {
 418                                mXmppConnectionService.databaseBackend.saveResolverResult(
 419                                        domain, result);
 420                            }
 421                            break; // successfully connected to server that speaks xmpp
 422                        } else {
 423                            FileBackend.close(localSocket);
 424                            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 425                        }
 426                    } catch (final StateChangingException e) {
 427                        if (!iterator.hasNext()) {
 428                            throw e;
 429                        }
 430                    } catch (InterruptedException e) {
 431                        Log.d(
 432                                Config.LOGTAG,
 433                                account.getJid().asBareJid()
 434                                        + ": thread was interrupted before beginning stream");
 435                        return;
 436                    } catch (final Throwable e) {
 437                        Log.d(
 438                                Config.LOGTAG,
 439                                account.getJid().asBareJid().toString()
 440                                        + ": "
 441                                        + e.getMessage()
 442                                        + "("
 443                                        + e.getClass().getName()
 444                                        + ")");
 445                        if (!iterator.hasNext()) {
 446                            throw new UnknownHostException();
 447                        }
 448                    }
 449                }
 450            }
 451            processStream();
 452        } catch (final SecurityException e) {
 453            this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 454        } catch (final StateChangingException e) {
 455            this.changeStatus(e.state);
 456        } catch (final UnknownHostException
 457                | ConnectException
 458                | SocksSocketFactory.HostNotFoundException e) {
 459            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 460        } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 461            this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 462        } catch (final IOException | XmlPullParserException e) {
 463            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 464            this.changeStatus(Account.State.OFFLINE);
 465            this.attempt = Math.max(0, this.attempt - 1);
 466        } finally {
 467            if (!Thread.currentThread().isInterrupted()) {
 468                forceCloseSocket();
 469            } else {
 470                Log.d(
 471                        Config.LOGTAG,
 472                        account.getJid().asBareJid()
 473                                + ": not force closing socket because thread was interrupted");
 474            }
 475        }
 476    }
 477
 478    /**
 479     * Starts xmpp protocol, call after connecting to socket
 480     *
 481     * @return true if server returns with valid xmpp, false otherwise
 482     */
 483    private boolean startXmpp(final Socket socket) throws Exception {
 484        if (Thread.currentThread().isInterrupted()) {
 485            throw new InterruptedException();
 486        }
 487        this.socket = socket;
 488        tagReader = new XmlReader();
 489        if (tagWriter != null) {
 490            tagWriter.forceClose();
 491        }
 492        tagWriter = new TagWriter();
 493        tagWriter.setOutputStream(socket.getOutputStream());
 494        tagReader.setInputStream(socket.getInputStream());
 495        tagWriter.beginDocument();
 496        final boolean quickStart;
 497        if (socket instanceof SSLSocket) {
 498            final SSLSocket sslSocket = (SSLSocket) socket;
 499            SSLSockets.log(account, sslSocket);
 500            quickStart = establishStream(SSLSockets.version(sslSocket));
 501        } else {
 502            quickStart = establishStream(SSLSockets.Version.NONE);
 503        }
 504        final Tag tag = tagReader.readTag();
 505        if (Thread.currentThread().isInterrupted()) {
 506            throw new InterruptedException();
 507        }
 508        final boolean success = tag != null && tag.isStart("stream", Namespace.STREAMS);
 509        if (success && quickStart) {
 510            this.quickStartInProgress = true;
 511        }
 512        return success;
 513    }
 514
 515    private SSLSocketFactory getSSLSocketFactory()
 516            throws NoSuchAlgorithmException, KeyManagementException {
 517        final SSLContext sc = SSLSockets.getSSLContext();
 518        final MemorizingTrustManager trustManager =
 519                this.mXmppConnectionService.getMemorizingTrustManager();
 520        final KeyManager[] keyManager;
 521        if (account.getPrivateKeyAlias() != null) {
 522            keyManager = new KeyManager[] {new MyKeyManager()};
 523        } else {
 524            keyManager = null;
 525        }
 526        final String domain = account.getServer();
 527        sc.init(
 528                keyManager,
 529                new X509TrustManager[] {
 530                    mInteractive
 531                            ? trustManager.getInteractive(domain)
 532                            : trustManager.getNonInteractive(domain)
 533                },
 534                SECURE_RANDOM);
 535        return sc.getSocketFactory();
 536    }
 537
 538    @Override
 539    public void run() {
 540        synchronized (this) {
 541            this.mThread = Thread.currentThread();
 542            if (this.mThread.isInterrupted()) {
 543                Log.d(
 544                        Config.LOGTAG,
 545                        account.getJid().asBareJid()
 546                                + ": aborting connect because thread was interrupted");
 547                return;
 548            }
 549            forceCloseSocket();
 550        }
 551        connect();
 552    }
 553
 554    private void processStream() throws XmlPullParserException, IOException {
 555        final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 556        this.mStreamCountDownLatch = streamCountDownLatch;
 557        Tag nextTag = tagReader.readTag();
 558        while (nextTag != null && !nextTag.isEnd("stream")) {
 559            if (nextTag.isStart("error")) {
 560                processStreamError(nextTag);
 561            } else if (nextTag.isStart("features", Namespace.STREAMS)) {
 562                processStreamFeatures(nextTag);
 563            } else if (nextTag.isStart("proceed", Namespace.TLS)) {
 564                switchOverToTls();
 565            } else if (nextTag.isStart("success")) {
 566                final Element success = tagReader.readElement(nextTag);
 567                if (processSuccess(success)) {
 568                    break;
 569                }
 570
 571            } else if (nextTag.isStart("failure", Namespace.TLS)) {
 572                throw new StateChangingException(Account.State.TLS_ERROR);
 573            } else if (nextTag.isStart("failure")) {
 574                final Element failure = tagReader.readElement(nextTag);
 575                processFailure(failure);
 576            } else if (nextTag.isStart("continue", Namespace.SASL_2)) {
 577                // two step sasl2 - we don’t support this yet
 578                throw new StateChangingException(Account.State.INCOMPATIBLE_CLIENT);
 579            } else if (nextTag.isStart("challenge")) {
 580                final Element challenge = tagReader.readElement(nextTag);
 581                processChallenge(challenge);
 582            } else if (nextTag.isStart("enabled", Namespace.STREAM_MANAGEMENT)) {
 583                final Element enabled = tagReader.readElement(nextTag);
 584                processEnabled(enabled);
 585            } else if (nextTag.isStart("resumed")) {
 586                final Element resumed = tagReader.readElement(nextTag);
 587                processResumed(resumed);
 588            } else if (nextTag.isStart("r")) {
 589                tagReader.readElement(nextTag);
 590                if (Config.EXTENDED_SM_LOGGING) {
 591                    Log.d(
 592                            Config.LOGTAG,
 593                            account.getJid().asBareJid()
 594                                    + ": acknowledging stanza #"
 595                                    + this.stanzasReceived);
 596                }
 597                final AckPacket ack = new AckPacket(this.stanzasReceived);
 598                tagWriter.writeStanzaAsync(ack);
 599            } else if (nextTag.isStart("a")) {
 600                boolean accountUiNeedsRefresh = false;
 601                synchronized (NotificationService.CATCHUP_LOCK) {
 602                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 603                        final int messageCount = mSmCatchupMessageCounter.get();
 604                        final int pendingIQs = packetCallbacks.size();
 605                        Log.d(
 606                                Config.LOGTAG,
 607                                account.getJid().asBareJid()
 608                                        + ": SM catchup complete (messages="
 609                                        + messageCount
 610                                        + ", pending IQs="
 611                                        + pendingIQs
 612                                        + ")");
 613                        accountUiNeedsRefresh = true;
 614                        if (messageCount > 0) {
 615                            mXmppConnectionService
 616                                    .getNotificationService()
 617                                    .finishBacklog(true, account);
 618                        }
 619                    }
 620                }
 621                if (accountUiNeedsRefresh) {
 622                    mXmppConnectionService.updateAccountUi();
 623                }
 624                final Element ack = tagReader.readElement(nextTag);
 625                lastPacketReceived = SystemClock.elapsedRealtime();
 626                try {
 627                    final boolean acknowledgedMessages;
 628                    synchronized (this.mStanzaQueue) {
 629                        final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 630                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
 631                    }
 632                    if (acknowledgedMessages) {
 633                        mXmppConnectionService.updateConversationUi();
 634                    }
 635                } catch (NumberFormatException | NullPointerException e) {
 636                    Log.d(
 637                            Config.LOGTAG,
 638                            account.getJid().asBareJid()
 639                                    + ": server send ack without sequence number");
 640                }
 641            } else if (nextTag.isStart("failed")) {
 642                final Element failed = tagReader.readElement(nextTag);
 643                processFailed(failed, true);
 644            } else if (nextTag.isStart("iq")) {
 645                processIq(nextTag);
 646            } else if (nextTag.isStart("message")) {
 647                processMessage(nextTag);
 648            } else if (nextTag.isStart("presence")) {
 649                processPresence(nextTag);
 650            }
 651            nextTag = tagReader.readTag();
 652        }
 653        if (nextTag != null && nextTag.isEnd("stream")) {
 654            streamCountDownLatch.countDown();
 655        }
 656    }
 657
 658    private void processChallenge(Element challenge) throws IOException {
 659        final SaslMechanism.Version version;
 660        try {
 661            version = SaslMechanism.Version.of(challenge);
 662        } catch (final IllegalArgumentException e) {
 663            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 664        }
 665        final Element response;
 666        if (version == SaslMechanism.Version.SASL) {
 667            response = new Element("response", Namespace.SASL);
 668        } else if (version == SaslMechanism.Version.SASL_2) {
 669            response = new Element("response", Namespace.SASL_2);
 670        } else {
 671            throw new AssertionError("Missing implementation for " + version);
 672        }
 673        try {
 674            response.setContent(saslMechanism.getResponse(challenge.getContent(), sslSocketOrNull(socket)));
 675        } catch (final SaslMechanism.AuthenticationException e) {
 676            // TODO: Send auth abort tag.
 677            Log.e(Config.LOGTAG, e.toString());
 678            throw new StateChangingException(Account.State.UNAUTHORIZED);
 679        }
 680        tagWriter.writeElement(response);
 681    }
 682
 683    private boolean processSuccess(final Element success)
 684            throws IOException, XmlPullParserException {
 685        final SaslMechanism.Version version;
 686        try {
 687            version = SaslMechanism.Version.of(success);
 688        } catch (final IllegalArgumentException e) {
 689            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 690        }
 691        final String challenge;
 692        if (version == SaslMechanism.Version.SASL) {
 693            challenge = success.getContent();
 694        } else if (version == SaslMechanism.Version.SASL_2) {
 695            challenge = success.findChildContent("additional-data");
 696        } else {
 697            throw new AssertionError("Missing implementation for " + version);
 698        }
 699        try {
 700            saslMechanism.getResponse(challenge, sslSocketOrNull(socket));
 701        } catch (final SaslMechanism.AuthenticationException e) {
 702            Log.e(Config.LOGTAG, String.valueOf(e));
 703            throw new StateChangingException(Account.State.UNAUTHORIZED);
 704        }
 705        Log.d(
 706                Config.LOGTAG,
 707                account.getJid().asBareJid().toString() + ": logged in (using " + version + ")");
 708        if (SaslMechanism.pin(this.saslMechanism)) {
 709            account.setPinnedMechanism(this.saslMechanism);
 710        }
 711        if (version == SaslMechanism.Version.SASL_2) {
 712            final Tag tag = tagReader.readTag();
 713            if (tag != null && tag.isStart("features", Namespace.STREAMS)) {
 714                this.streamFeatures = tagReader.readElement(tag);
 715                Log.d(
 716                        Config.LOGTAG,
 717                        account.getJid().asBareJid()
 718                                + ": processed NOP stream features after success "
 719                                + XmlHelper.printElementNames(this.streamFeatures));
 720            } else {
 721                Log.d(
 722                        Config.LOGTAG,
 723                        account.getJid().asBareJid()
 724                                + ": server did not send stream features after SASL2 success");
 725                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 726            }
 727            final String authorizationIdentifier =
 728                    success.findChildContent("authorization-identifier");
 729            final Jid authorizationJid;
 730            try {
 731                authorizationJid =
 732                        Strings.isNullOrEmpty(authorizationIdentifier)
 733                                ? null
 734                                : Jid.ofEscaped(authorizationIdentifier);
 735            } catch (final IllegalArgumentException e) {
 736                Log.d(
 737                        Config.LOGTAG,
 738                        account.getJid().asBareJid()
 739                                + ": SASL 2.0 authorization identifier was not a valid jid");
 740                throw new StateChangingException(Account.State.BIND_FAILURE);
 741            }
 742            if (authorizationJid == null) {
 743                throw new StateChangingException(Account.State.BIND_FAILURE);
 744            }
 745            Log.d(
 746                    Config.LOGTAG,
 747                    account.getJid().asBareJid()
 748                            + ": SASL 2.0 authorization identifier was "
 749                            + authorizationJid);
 750            if (!account.getJid().getDomain().equals(authorizationJid.getDomain())) {
 751                Log.d(
 752                        Config.LOGTAG,
 753                        account.getJid().asBareJid()
 754                                + ": server tried to re-assign domain to "
 755                                + authorizationJid.getDomain());
 756                throw new StateChangingError(Account.State.BIND_FAILURE);
 757            }
 758            if (authorizationJid.isFullJid() && account.setJid(authorizationJid)) {
 759                Log.d(
 760                        Config.LOGTAG,
 761                        account.getJid().asBareJid()
 762                                + ": jid changed during SASL 2.0. updating database");
 763            }
 764            final Element bound = success.findChild("bound", Namespace.BIND2);
 765            final Element resumed = success.findChild("resumed", "urn:xmpp:sm:3");
 766            final Element failed = success.findChild("failed", "urn:xmpp:sm:3");
 767            final Element tokenWrapper = success.findChild("token", Namespace.FAST);
 768            final String token = tokenWrapper == null ? null : tokenWrapper.getAttribute("token");
 769            if (bound != null && resumed != null) {
 770                Log.d(
 771                        Config.LOGTAG,
 772                        account.getJid().asBareJid()
 773                                + ": server sent bound and resumed in SASL2 success");
 774                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 775            }
 776            if (resumed != null && streamId != null) {
 777                processResumed(resumed);
 778            } else if (failed != null) {
 779                processFailed(failed, false); // wait for new stream features
 780            }
 781            if (bound != null) {
 782                clearIqCallbacks();
 783                this.isBound = true;
 784                final Element streamManagementEnabled =
 785                        bound.findChild("enabled", Namespace.STREAM_MANAGEMENT);
 786                final Element carbonsEnabled = bound.findChild("enabled", Namespace.CARBONS);
 787                final boolean waitForDisco;
 788                if (streamManagementEnabled != null) {
 789                    processEnabled(streamManagementEnabled);
 790                    waitForDisco = true;
 791                } else {
 792                    //if we did not enable stream management in bind do it now
 793                    waitForDisco = enableStreamManagement();
 794                }
 795                if (carbonsEnabled != null) {
 796                    Log.d(
 797                            Config.LOGTAG,
 798                            account.getJid().asBareJid() + ": successfully enabled carbons");
 799                    features.carbonsEnabled = true;
 800                }
 801                sendPostBindInitialization(waitForDisco, carbonsEnabled != null);
 802            }
 803            final HashedToken.Mechanism tokenMechanism;
 804            final SaslMechanism currentMechanism = this.saslMechanism;
 805            if (currentMechanism instanceof HashedToken) {
 806                tokenMechanism = ((HashedToken) currentMechanism).getTokenMechanism();
 807            } else if (this.hashTokenRequest != null) {
 808                tokenMechanism = this.hashTokenRequest;
 809            } else {
 810                tokenMechanism = null;
 811            }
 812            if (tokenMechanism != null && !Strings.isNullOrEmpty(token)) {
 813                this.account.setFastToken(tokenMechanism,token);
 814                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": storing hashed token "+tokenMechanism);
 815            }
 816        }
 817        mXmppConnectionService.databaseBackend.updateAccount(account);
 818        this.quickStartInProgress = false;
 819        if (version == SaslMechanism.Version.SASL) {
 820            tagReader.reset();
 821            sendStartStream(false, true);
 822            final Tag tag = tagReader.readTag();
 823            if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
 824                processStream();
 825                return true;
 826            } else {
 827                throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 828            }
 829        } else {
 830            return false;
 831        }
 832    }
 833
 834    private void processFailure(final Element failure) throws StateChangingException {
 835        final SaslMechanism.Version version;
 836        try {
 837            version = SaslMechanism.Version.of(failure);
 838        } catch (final IllegalArgumentException e) {
 839            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 840        }
 841        Log.d(Config.LOGTAG,failure.toString());
 842        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": login failure " + version);
 843        if (this.saslMechanism instanceof HashedToken) {
 844            Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": resetting token");
 845            account.resetFastToken();
 846            mXmppConnectionService.databaseBackend.updateAccount(account);
 847        }
 848        if (failure.hasChild("temporary-auth-failure")) {
 849            throw new StateChangingException(Account.State.TEMPORARY_AUTH_FAILURE);
 850        } else if (failure.hasChild("account-disabled")) {
 851            final String text = failure.findChildContent("text");
 852            if (Strings.isNullOrEmpty(text)) {
 853                throw new StateChangingException(Account.State.UNAUTHORIZED);
 854            }
 855            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 856            if (matcher.find()) {
 857                final HttpUrl url;
 858                try {
 859                    url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
 860                } catch (final IllegalArgumentException e) {
 861                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 862                }
 863                if (url.isHttps()) {
 864                    this.redirectionUrl = url;
 865                    throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 866                }
 867            }
 868        }
 869        throw new StateChangingException(Account.State.UNAUTHORIZED);
 870    }
 871
 872    private static SSLSocket sslSocketOrNull(final Socket socket) {
 873        if (socket instanceof SSLSocket) {
 874            return (SSLSocket) socket;
 875        } else {
 876            return null;
 877        }
 878    }
 879
 880    private void processEnabled(final Element enabled) {
 881        final String streamId;
 882        if (enabled.getAttributeAsBoolean("resume")) {
 883            streamId = enabled.getAttribute("id");
 884            Log.d(
 885                    Config.LOGTAG,
 886                    account.getJid().asBareJid().toString()
 887                            + ": stream management enabled (resumable)");
 888        } else {
 889            Log.d(
 890                    Config.LOGTAG,
 891                    account.getJid().asBareJid().toString() + ": stream management enabled");
 892            streamId = null;
 893        }
 894        this.streamId = streamId;
 895        this.stanzasReceived = 0;
 896        this.inSmacksSession = true;
 897        final RequestPacket r = new RequestPacket();
 898        tagWriter.writeStanzaAsync(r);
 899    }
 900
 901    private void processResumed(final Element resumed) throws StateChangingException {
 902        this.inSmacksSession = true;
 903        this.isBound = true;
 904        this.tagWriter.writeStanzaAsync(new RequestPacket());
 905        lastPacketReceived = SystemClock.elapsedRealtime();
 906        final String h = resumed.getAttribute("h");
 907        if (h == null) {
 908            resetStreamId();
 909            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 910        }
 911        final int serverCount;
 912        try {
 913            serverCount = Integer.parseInt(h);
 914        } catch (final NumberFormatException e) {
 915            resetStreamId();
 916            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 917        }
 918        final ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 919        final boolean acknowledgedMessages;
 920        synchronized (this.mStanzaQueue) {
 921            if (serverCount < stanzasSent) {
 922                Log.d(
 923                        Config.LOGTAG,
 924                        account.getJid().asBareJid() + ": session resumed with lost packages");
 925                stanzasSent = serverCount;
 926            } else {
 927                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": session resumed");
 928            }
 929            acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 930            for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 931                failedStanzas.add(mStanzaQueue.valueAt(i));
 932            }
 933            mStanzaQueue.clear();
 934        }
 935        if (acknowledgedMessages) {
 936            mXmppConnectionService.updateConversationUi();
 937        }
 938        Log.d(
 939                Config.LOGTAG,
 940                account.getJid().asBareJid() + ": resending " + failedStanzas.size() + " stanzas");
 941        for (final AbstractAcknowledgeableStanza packet : failedStanzas) {
 942            if (packet instanceof MessagePacket) {
 943                MessagePacket message = (MessagePacket) packet;
 944                mXmppConnectionService.markMessage(
 945                        account,
 946                        message.getTo().asBareJid(),
 947                        message.getId(),
 948                        Message.STATUS_UNSEND);
 949            }
 950            sendPacket(packet);
 951        }
 952        changeStatusToOnline();
 953    }
 954
 955    private void changeStatusToOnline() {
 956        Log.d(
 957                Config.LOGTAG,
 958                account.getJid().asBareJid() + ": online with resource " + account.getResource());
 959        changeStatus(Account.State.ONLINE);
 960    }
 961
 962    private void processFailed(final Element failed, final boolean sendBindRequest) {
 963        final int serverCount;
 964        try {
 965            serverCount = Integer.parseInt(failed.getAttribute("h"));
 966        } catch (final NumberFormatException | NullPointerException e) {
 967            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
 968            resetStreamId();
 969            if (sendBindRequest) {
 970                sendBindRequest();
 971            }
 972            return;
 973        }
 974        Log.d(
 975                Config.LOGTAG,
 976                account.getJid().asBareJid()
 977                        + ": resumption failed but server acknowledged stanza #"
 978                        + serverCount);
 979        final boolean acknowledgedMessages;
 980        synchronized (this.mStanzaQueue) {
 981            acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 982        }
 983        if (acknowledgedMessages) {
 984            mXmppConnectionService.updateConversationUi();
 985        }
 986        resetStreamId();
 987        if (sendBindRequest) {
 988            sendBindRequest();
 989        }
 990    }
 991
 992    private boolean acknowledgeStanzaUpTo(int serverCount) {
 993        if (serverCount > stanzasSent) {
 994            Log.e(
 995                    Config.LOGTAG,
 996                    "server acknowledged more stanzas than we sent. serverCount="
 997                            + serverCount
 998                            + ", ourCount="
 999                            + stanzasSent);
1000        }
1001        boolean acknowledgedMessages = false;
1002        for (int i = 0; i < mStanzaQueue.size(); ++i) {
1003            if (serverCount >= mStanzaQueue.keyAt(i)) {
1004                if (Config.EXTENDED_SM_LOGGING) {
1005                    Log.d(
1006                            Config.LOGTAG,
1007                            account.getJid().asBareJid()
1008                                    + ": server acknowledged stanza #"
1009                                    + mStanzaQueue.keyAt(i));
1010                }
1011                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1012                if (stanza instanceof MessagePacket && acknowledgedListener != null) {
1013                    final MessagePacket packet = (MessagePacket) stanza;
1014                    final String id = packet.getId();
1015                    final Jid to = packet.getTo();
1016                    if (id != null && to != null) {
1017                        acknowledgedMessages |=
1018                                acknowledgedListener.onMessageAcknowledged(account, to, id);
1019                    }
1020                }
1021                mStanzaQueue.removeAt(i);
1022                i--;
1023            }
1024        }
1025        return acknowledgedMessages;
1026    }
1027
1028    private @NonNull Element processPacket(final Tag currentTag, final int packetType)
1029            throws IOException {
1030        final Element element;
1031        switch (packetType) {
1032            case PACKET_IQ:
1033                element = new IqPacket();
1034                break;
1035            case PACKET_MESSAGE:
1036                element = new MessagePacket();
1037                break;
1038            case PACKET_PRESENCE:
1039                element = new PresencePacket();
1040                break;
1041            default:
1042                throw new AssertionError("Should never encounter invalid type");
1043        }
1044        element.setAttributes(currentTag.getAttributes());
1045        Tag nextTag = tagReader.readTag();
1046        if (nextTag == null) {
1047            throw new IOException("interrupted mid tag");
1048        }
1049        while (!nextTag.isEnd(element.getName())) {
1050            if (!nextTag.isNo()) {
1051                element.addChild(tagReader.readElement(nextTag));
1052            }
1053            nextTag = tagReader.readTag();
1054            if (nextTag == null) {
1055                throw new IOException("interrupted mid tag");
1056            }
1057        }
1058        if (stanzasReceived == Integer.MAX_VALUE) {
1059            resetStreamId();
1060            throw new IOException("time to restart the session. cant handle >2 billion pcks");
1061        }
1062        if (inSmacksSession) {
1063            ++stanzasReceived;
1064        } else if (features.sm()) {
1065            Log.d(
1066                    Config.LOGTAG,
1067                    account.getJid().asBareJid()
1068                            + ": not counting stanza("
1069                            + element.getClass().getSimpleName()
1070                            + "). Not in smacks session.");
1071        }
1072        lastPacketReceived = SystemClock.elapsedRealtime();
1073        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
1074            Log.d(Config.LOGTAG, "[background stanza] " + element);
1075        }
1076        if (element instanceof IqPacket
1077                && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
1078                && element.hasChild("jingle", Namespace.JINGLE)) {
1079            return JinglePacket.upgrade((IqPacket) element);
1080        } else {
1081            return element;
1082        }
1083    }
1084
1085    private void processIq(final Tag currentTag) throws IOException {
1086        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
1087        if (!packet.valid()) {
1088            Log.e(
1089                    Config.LOGTAG,
1090                    "encountered invalid iq from='"
1091                            + packet.getFrom()
1092                            + "' to='"
1093                            + packet.getTo()
1094                            + "'");
1095            return;
1096        }
1097        if (packet instanceof JinglePacket) {
1098            if (this.jingleListener != null) {
1099                this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
1100            }
1101        } else {
1102            OnIqPacketReceived callback = null;
1103            synchronized (this.packetCallbacks) {
1104                final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple =
1105                        packetCallbacks.get(packet.getId());
1106                if (packetCallbackDuple != null) {
1107                    // Packets to the server should have responses from the server
1108                    if (packetCallbackDuple.first.toServer(account)) {
1109                        if (packet.fromServer(account)) {
1110                            callback = packetCallbackDuple.second;
1111                            packetCallbacks.remove(packet.getId());
1112                        } else {
1113                            Log.e(
1114                                    Config.LOGTAG,
1115                                    account.getJid().asBareJid().toString()
1116                                            + ": ignoring spoofed iq packet");
1117                        }
1118                    } else {
1119                        if (packet.getFrom() != null
1120                                && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
1121                            callback = packetCallbackDuple.second;
1122                            packetCallbacks.remove(packet.getId());
1123                        } else {
1124                            Log.e(
1125                                    Config.LOGTAG,
1126                                    account.getJid().asBareJid().toString()
1127                                            + ": ignoring spoofed iq packet");
1128                        }
1129                    }
1130                } else if (packet.getType() == IqPacket.TYPE.GET
1131                        || packet.getType() == IqPacket.TYPE.SET) {
1132                    callback = this.unregisteredIqListener;
1133                }
1134            }
1135            if (callback != null) {
1136                try {
1137                    callback.onIqPacketReceived(account, packet);
1138                } catch (StateChangingError error) {
1139                    throw new StateChangingException(error.state);
1140                }
1141            }
1142        }
1143    }
1144
1145    private void processMessage(final Tag currentTag) throws IOException {
1146        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
1147        if (!packet.valid()) {
1148            Log.e(
1149                    Config.LOGTAG,
1150                    "encountered invalid message from='"
1151                            + packet.getFrom()
1152                            + "' to='"
1153                            + packet.getTo()
1154                            + "'");
1155            return;
1156        }
1157        this.messageListener.onMessagePacketReceived(account, packet);
1158    }
1159
1160    private void processPresence(final Tag currentTag) throws IOException {
1161        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
1162        if (!packet.valid()) {
1163            Log.e(
1164                    Config.LOGTAG,
1165                    "encountered invalid presence from='"
1166                            + packet.getFrom()
1167                            + "' to='"
1168                            + packet.getTo()
1169                            + "'");
1170            return;
1171        }
1172        this.presenceListener.onPresencePacketReceived(account, packet);
1173    }
1174
1175    private void sendStartTLS() throws IOException {
1176        final Tag startTLS = Tag.empty("starttls");
1177        startTLS.setAttribute("xmlns", Namespace.TLS);
1178        tagWriter.writeTag(startTLS);
1179    }
1180
1181    private void switchOverToTls() throws XmlPullParserException, IOException {
1182        tagReader.readTag();
1183        final Socket socket = this.socket;
1184        final SSLSocket sslSocket = upgradeSocketToTls(socket);
1185        tagReader.setInputStream(sslSocket.getInputStream());
1186        tagWriter.setOutputStream(sslSocket.getOutputStream());
1187        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
1188        final boolean quickStart;
1189        try {
1190            quickStart = establishStream(SSLSockets.version(sslSocket));
1191        } catch (final InterruptedException e) {
1192            return;
1193        }
1194        if (quickStart) {
1195            this.quickStartInProgress = true;
1196        }
1197        features.encryptionEnabled = true;
1198        final Tag tag = tagReader.readTag();
1199        if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
1200            SSLSockets.log(account, sslSocket);
1201            processStream();
1202        } else {
1203            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
1204        }
1205        sslSocket.close();
1206    }
1207
1208    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
1209        final SSLSocketFactory sslSocketFactory;
1210        try {
1211            sslSocketFactory = getSSLSocketFactory();
1212        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
1213            throw new StateChangingException(Account.State.TLS_ERROR);
1214        }
1215        final InetAddress address = socket.getInetAddress();
1216        final SSLSocket sslSocket =
1217                (SSLSocket)
1218                        sslSocketFactory.createSocket(
1219                                socket, address.getHostAddress(), socket.getPort(), true);
1220        SSLSockets.setSecurity(sslSocket);
1221        SSLSockets.setHostname(sslSocket, IDN.toASCII(account.getServer()));
1222        SSLSockets.setApplicationProtocol(sslSocket, "xmpp-client");
1223        final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
1224        try {
1225            if (!xmppDomainVerifier.verify(
1226                    account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
1227                Log.d(
1228                        Config.LOGTAG,
1229                        account.getJid().asBareJid()
1230                                + ": TLS certificate domain verification failed");
1231                FileBackend.close(sslSocket);
1232                throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
1233            }
1234        } catch (final SSLPeerUnverifiedException e) {
1235            FileBackend.close(sslSocket);
1236            throw new StateChangingException(Account.State.TLS_ERROR);
1237        }
1238        return sslSocket;
1239    }
1240
1241    private void processStreamFeatures(final Tag currentTag) throws IOException {
1242        this.streamFeatures = tagReader.readElement(currentTag);
1243        final boolean isSecure =
1244                features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
1245        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
1246        if (this.quickStartInProgress) {
1247            if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1248                Log.d(
1249                        Config.LOGTAG,
1250                        account.getJid().asBareJid()
1251                                + ": quick start in progress. ignoring features: "
1252                                + XmlHelper.printElementNames(this.streamFeatures));
1253                //TODO check if 'fast' is available but we are doing something else
1254                return;
1255            }
1256            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server lost support for SASL 2. quick start not possible");
1257            this.account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1258            mXmppConnectionService.updateAccount(account);
1259            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1260        }
1261        if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
1262                && !features.encryptionEnabled) {
1263            sendStartTLS();
1264        } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1265                && account.isOptionSet(Account.OPTION_REGISTER)) {
1266            if (isSecure) {
1267                register();
1268            } else {
1269                Log.d(
1270                        Config.LOGTAG,
1271                        account.getJid().asBareJid()
1272                                + ": unable to find STARTTLS for registration process "
1273                                + XmlHelper.printElementNames(this.streamFeatures));
1274                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1275            }
1276        } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1277                && account.isOptionSet(Account.OPTION_REGISTER)) {
1278            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
1279        } else if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)
1280                && shouldAuthenticate
1281                && isSecure) {
1282            authenticate(SaslMechanism.Version.SASL_2);
1283        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
1284                && shouldAuthenticate
1285                && isSecure) {
1286            authenticate(SaslMechanism.Version.SASL);
1287        } else if (this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT)
1288                && streamId != null
1289                && !inSmacksSession) {
1290            if (Config.EXTENDED_SM_LOGGING) {
1291                Log.d(
1292                        Config.LOGTAG,
1293                        account.getJid().asBareJid()
1294                                + ": resuming after stanza #"
1295                                + stanzasReceived);
1296            }
1297            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived);
1298            this.mSmCatchupMessageCounter.set(0);
1299            this.mWaitingForSmCatchup.set(true);
1300            this.tagWriter.writeStanzaAsync(resume);
1301        } else if (needsBinding) {
1302            if (this.streamFeatures.hasChild("bind", Namespace.BIND) && isSecure) {
1303                sendBindRequest();
1304            } else {
1305                Log.d(
1306                        Config.LOGTAG,
1307                        account.getJid().asBareJid()
1308                                + ": unable to find bind feature "
1309                                + XmlHelper.printElementNames(this.streamFeatures));
1310                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1311            }
1312        } else {
1313            Log.d(
1314                    Config.LOGTAG,
1315                    account.getJid().asBareJid()
1316                            + ": received NOP stream features "
1317                            + XmlHelper.printElementNames(this.streamFeatures));
1318        }
1319    }
1320
1321    private void authenticate(final SaslMechanism.Version version) throws IOException {
1322        final Element authElement;
1323        if (version == SaslMechanism.Version.SASL) {
1324            authElement = this.streamFeatures.findChild("mechanisms", Namespace.SASL);
1325        } else {
1326            authElement = this.streamFeatures.findChild("authentication", Namespace.SASL_2);
1327        }
1328        final Collection<String> mechanisms = SaslMechanism.mechanisms(authElement);
1329        final Element cbElement =
1330                this.streamFeatures.findChild("sasl-channel-binding", Namespace.CHANNEL_BINDING);
1331        final Collection<ChannelBinding> channelBindings = ChannelBinding.of(cbElement);
1332        final SaslMechanism.Factory factory = new SaslMechanism.Factory(account);
1333        final SaslMechanism saslMechanism = factory.of(mechanisms, channelBindings, version, SSLSockets.version(this.socket));
1334        this.saslMechanism = validate(saslMechanism, mechanisms);
1335        final boolean quickStartAvailable;
1336        final String firstMessage = this.saslMechanism.getClientFirstMessage(sslSocketOrNull(this.socket));
1337        final boolean usingFast = SaslMechanism.hashedToken(this.saslMechanism);
1338        final Element authenticate;
1339        if (version == SaslMechanism.Version.SASL) {
1340            authenticate = new Element("auth", Namespace.SASL);
1341            if (!Strings.isNullOrEmpty(firstMessage)) {
1342                authenticate.setContent(firstMessage);
1343            }
1344            quickStartAvailable = false;
1345        } else if (version == SaslMechanism.Version.SASL_2) {
1346            final Element inline = authElement.findChild("inline", Namespace.SASL_2);
1347            final boolean sm = inline != null && inline.hasChild("sm", "urn:xmpp:sm:3");
1348            final HashedToken.Mechanism hashTokenRequest;
1349            if (usingFast) {
1350                hashTokenRequest = null;
1351            } else {
1352                final Element fast = inline == null ? null : inline.findChild("fast", Namespace.FAST);
1353                final Collection<String> fastMechanisms = SaslMechanism.mechanisms(fast);
1354                hashTokenRequest =
1355                        HashedToken.Mechanism.best(fastMechanisms, SSLSockets.version(this.socket));
1356            }
1357            final Collection<String> bindFeatures = Bind2.features(inline);
1358            quickStartAvailable =
1359                    sm
1360                            && bindFeatures != null
1361                            && bindFeatures.containsAll(Bind2.QUICKSTART_FEATURES);
1362            if (bindFeatures != null) {
1363                try {
1364                    mXmppConnectionService.restoredFromDatabaseLatch.await();
1365                } catch (final InterruptedException e) {
1366                    Log.d(
1367                            Config.LOGTAG,
1368                            account.getJid().asBareJid()
1369                                    + ": interrupted while waiting for DB restore during SASL2 bind");
1370                    return;
1371                }
1372            }
1373            this.hashTokenRequest = hashTokenRequest;
1374            authenticate = generateAuthenticationRequest(firstMessage, usingFast, hashTokenRequest, bindFeatures, sm);
1375        } else {
1376            throw new AssertionError("Missing implementation for " + version);
1377        }
1378
1379        if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, quickStartAvailable)) {
1380            mXmppConnectionService.updateAccount(account);
1381        }
1382
1383        Log.d(
1384                Config.LOGTAG,
1385                account.getJid().toString()
1386                        + ": Authenticating with "
1387                        + version
1388                        + "/"
1389                        + this.saslMechanism.getMechanism());
1390        authenticate.setAttribute("mechanism", this.saslMechanism.getMechanism());
1391        tagWriter.writeElement(authenticate);
1392    }
1393
1394    @NonNull
1395    private SaslMechanism validate(final @Nullable SaslMechanism saslMechanism, Collection<String> mechanisms) throws StateChangingException {
1396        if (saslMechanism == null) {
1397            Log.d(
1398                    Config.LOGTAG,
1399                    account.getJid().asBareJid()
1400                            + ": unable to find supported SASL mechanism in "
1401                            + mechanisms);
1402            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1403        }
1404        if (SaslMechanism.hashedToken(saslMechanism)) {
1405            return saslMechanism;
1406        }
1407        final int pinnedMechanism = account.getPinnedMechanismPriority();
1408        if (pinnedMechanism > saslMechanism.getPriority()) {
1409            Log.e(
1410                    Config.LOGTAG,
1411                    "Auth failed. Authentication mechanism "
1412                            + saslMechanism.getMechanism()
1413                            + " has lower priority ("
1414                            + saslMechanism.getPriority()
1415                            + ") than pinned priority ("
1416                            + pinnedMechanism
1417                            + "). Possible downgrade attack?");
1418            throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1419        }
1420        return saslMechanism;
1421    }
1422
1423    private Element generateAuthenticationRequest(final String firstMessage, final boolean usingFast) {
1424        return generateAuthenticationRequest(firstMessage, usingFast, null, Bind2.QUICKSTART_FEATURES, true);
1425    }
1426
1427    private Element generateAuthenticationRequest(
1428            final String firstMessage,
1429            final boolean usingFast,
1430            final HashedToken.Mechanism hashedTokenRequest,
1431            final Collection<String> bind,
1432            final boolean inlineStreamManagement) {
1433        final Element authenticate = new Element("authenticate", Namespace.SASL_2);
1434        if (!Strings.isNullOrEmpty(firstMessage)) {
1435            authenticate.addChild("initial-response").setContent(firstMessage);
1436        }
1437        final Element userAgent = authenticate.addChild("user-agent");
1438        userAgent.setAttribute("id", account.getUuid());
1439        userAgent
1440                .addChild("software")
1441                .setContent(mXmppConnectionService.getString(R.string.app_name));
1442        if (!PhoneHelper.isEmulator()) {
1443            userAgent
1444                    .addChild("device")
1445                    .setContent(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1446        }
1447        if (bind != null) {
1448            authenticate.addChild(generateBindRequest(bind));
1449        }
1450        if (inlineStreamManagement && streamId != null) {
1451            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived);
1452            this.mSmCatchupMessageCounter.set(0);
1453            this.mWaitingForSmCatchup.set(true);
1454            authenticate.addChild(resume);
1455        }
1456        if (hashedTokenRequest != null) {
1457            authenticate
1458                    .addChild("request-token", Namespace.FAST)
1459                    .setAttribute("mechanism", hashedTokenRequest.name());
1460        }
1461        if (usingFast) {
1462            authenticate.addChild("fast", Namespace.FAST);
1463        }
1464        return authenticate;
1465    }
1466
1467    private Element generateBindRequest(final Collection<String> bindFeatures) {
1468        Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1469        final Element bind = new Element("bind", Namespace.BIND2);
1470        bind.addChild("tag").setContent(mXmppConnectionService.getString(R.string.app_name));
1471        if (bindFeatures.contains(Namespace.CARBONS)) {
1472            bind.addChild("enable", Namespace.CARBONS);
1473        }
1474        if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1475            bind.addChild(new EnablePacket());
1476        }
1477        return bind;
1478    }
1479
1480    private void register() {
1481        final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1482        if (preAuth != null && features.invite()) {
1483            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1484            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1485            sendUnmodifiedIqPacket(
1486                    preAuthRequest,
1487                    (account, response) -> {
1488                        if (response.getType() == IqPacket.TYPE.RESULT) {
1489                            sendRegistryRequest();
1490                        } else {
1491                            final String error = response.getErrorCondition();
1492                            Log.d(
1493                                    Config.LOGTAG,
1494                                    account.getJid().asBareJid()
1495                                            + ": failed to pre auth. "
1496                                            + error);
1497                            throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1498                        }
1499                    },
1500                    true);
1501        } else {
1502            sendRegistryRequest();
1503        }
1504    }
1505
1506    private void sendRegistryRequest() {
1507        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1508        register.query(Namespace.REGISTER);
1509        register.setTo(account.getDomain());
1510        sendUnmodifiedIqPacket(
1511                register,
1512                (account, packet) -> {
1513                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1514                        return;
1515                    }
1516                    if (packet.getType() == IqPacket.TYPE.ERROR) {
1517                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1518                    }
1519                    final Element query = packet.query(Namespace.REGISTER);
1520                    if (query.hasChild("username") && (query.hasChild("password"))) {
1521                        final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1522                        final Element username =
1523                                new Element("username").setContent(account.getUsername());
1524                        final Element password =
1525                                new Element("password").setContent(account.getPassword());
1526                        register1.query(Namespace.REGISTER).addChild(username);
1527                        register1.query().addChild(password);
1528                        register1.setFrom(account.getJid().asBareJid());
1529                        sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1530                    } else if (query.hasChild("x", Namespace.DATA)) {
1531                        final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1532                        final Element blob = query.findChild("data", "urn:xmpp:bob");
1533                        final String id = packet.getId();
1534                        InputStream is;
1535                        if (blob != null) {
1536                            try {
1537                                final String base64Blob = blob.getContent();
1538                                final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1539                                is = new ByteArrayInputStream(strBlob);
1540                            } catch (Exception e) {
1541                                is = null;
1542                            }
1543                        } else {
1544                            final boolean useTor =
1545                                    mXmppConnectionService.useTorToConnect() || account.isOnion();
1546                            try {
1547                                final String url = data.getValue("url");
1548                                final String fallbackUrl = data.getValue("captcha-fallback-url");
1549                                if (url != null) {
1550                                    is = HttpConnectionManager.open(url, useTor);
1551                                } else if (fallbackUrl != null) {
1552                                    is = HttpConnectionManager.open(fallbackUrl, useTor);
1553                                } else {
1554                                    is = null;
1555                                }
1556                            } catch (final IOException e) {
1557                                Log.d(
1558                                        Config.LOGTAG,
1559                                        account.getJid().asBareJid() + ": unable to fetch captcha",
1560                                        e);
1561                                is = null;
1562                            }
1563                        }
1564
1565                        if (is != null) {
1566                            Bitmap captcha = BitmapFactory.decodeStream(is);
1567                            try {
1568                                if (mXmppConnectionService.displayCaptchaRequest(
1569                                        account, id, data, captcha)) {
1570                                    return;
1571                                }
1572                            } catch (Exception e) {
1573                                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1574                            }
1575                        }
1576                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1577                    } else if (query.hasChild("instructions")
1578                            || query.hasChild("x", Namespace.OOB)) {
1579                        final String instructions = query.findChildContent("instructions");
1580                        final Element oob = query.findChild("x", Namespace.OOB);
1581                        final String url = oob == null ? null : oob.findChildContent("url");
1582                        if (url != null) {
1583                            setAccountCreationFailed(url);
1584                        } else if (instructions != null) {
1585                            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1586                            if (matcher.find()) {
1587                                setAccountCreationFailed(
1588                                        instructions.substring(matcher.start(), matcher.end()));
1589                            }
1590                        }
1591                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1592                    }
1593                },
1594                true);
1595    }
1596
1597    private void setAccountCreationFailed(final String url) {
1598        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1599        if (httpUrl != null && httpUrl.isHttps()) {
1600            this.redirectionUrl = httpUrl;
1601            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1602        }
1603        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1604    }
1605
1606    public HttpUrl getRedirectionUrl() {
1607        return this.redirectionUrl;
1608    }
1609
1610    public void resetEverything() {
1611        resetAttemptCount(true);
1612        resetStreamId();
1613        clearIqCallbacks();
1614        this.stanzasSent = 0;
1615        mStanzaQueue.clear();
1616        this.redirectionUrl = null;
1617        synchronized (this.disco) {
1618            disco.clear();
1619        }
1620        synchronized (this.commands) {
1621            this.commands.clear();
1622        }
1623    }
1624
1625    private void sendBindRequest() {
1626        try {
1627            mXmppConnectionService.restoredFromDatabaseLatch.await();
1628        } catch (InterruptedException e) {
1629            Log.d(
1630                    Config.LOGTAG,
1631                    account.getJid().asBareJid()
1632                            + ": interrupted while waiting for DB restore during bind");
1633            return;
1634        }
1635        clearIqCallbacks();
1636        if (account.getJid().isBareJid()) {
1637            account.setResource(this.createNewResource());
1638        } else {
1639            fixResource(mXmppConnectionService, account);
1640        }
1641        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1642        final String resource =
1643                Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1644        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1645        this.sendUnmodifiedIqPacket(
1646                iq,
1647                (account, packet) -> {
1648                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1649                        return;
1650                    }
1651                    final Element bind = packet.findChild("bind");
1652                    if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1653                        isBound = true;
1654                        final Element jid = bind.findChild("jid");
1655                        if (jid != null && jid.getContent() != null) {
1656                            try {
1657                                Jid assignedJid = Jid.ofEscaped(jid.getContent());
1658                                if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1659                                    Log.d(
1660                                            Config.LOGTAG,
1661                                            account.getJid().asBareJid()
1662                                                    + ": server tried to re-assign domain to "
1663                                                    + assignedJid.getDomain());
1664                                    throw new StateChangingError(Account.State.BIND_FAILURE);
1665                                }
1666                                if (account.setJid(assignedJid)) {
1667                                    Log.d(
1668                                            Config.LOGTAG,
1669                                            account.getJid().asBareJid()
1670                                                    + ": jid changed during bind. updating database");
1671                                    mXmppConnectionService.databaseBackend.updateAccount(account);
1672                                }
1673                                if (streamFeatures.hasChild("session")
1674                                        && !streamFeatures
1675                                                .findChild("session")
1676                                                .hasChild("optional")) {
1677                                    sendStartSession();
1678                                } else {
1679                                    final boolean waitForDisco = enableStreamManagement();
1680                                    sendPostBindInitialization(waitForDisco, false);
1681                                }
1682                                return;
1683                            } catch (final IllegalArgumentException e) {
1684                                Log.d(
1685                                        Config.LOGTAG,
1686                                        account.getJid().asBareJid()
1687                                                + ": server reported invalid jid ("
1688                                                + jid.getContent()
1689                                                + ") on bind");
1690                            }
1691                        } else {
1692                            Log.d(
1693                                    Config.LOGTAG,
1694                                    account.getJid()
1695                                            + ": disconnecting because of bind failure. (no jid)");
1696                        }
1697                    } else {
1698                        Log.d(
1699                                Config.LOGTAG,
1700                                account.getJid()
1701                                        + ": disconnecting because of bind failure ("
1702                                        + packet);
1703                    }
1704                    final Element error = packet.findChild("error");
1705                    if (packet.getType() == IqPacket.TYPE.ERROR
1706                            && error != null
1707                            && error.hasChild("conflict")) {
1708                        account.setResource(createNewResource());
1709                    }
1710                    throw new StateChangingError(Account.State.BIND_FAILURE);
1711                },
1712                true);
1713    }
1714
1715    private void clearIqCallbacks() {
1716        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1717        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1718        synchronized (this.packetCallbacks) {
1719            if (this.packetCallbacks.size() == 0) {
1720                return;
1721            }
1722            Log.d(
1723                    Config.LOGTAG,
1724                    account.getJid().asBareJid()
1725                            + ": clearing "
1726                            + this.packetCallbacks.size()
1727                            + " iq callbacks");
1728            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator =
1729                    this.packetCallbacks.values().iterator();
1730            while (iterator.hasNext()) {
1731                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1732                callbacks.add(entry.second);
1733                iterator.remove();
1734            }
1735        }
1736        for (OnIqPacketReceived callback : callbacks) {
1737            try {
1738                callback.onIqPacketReceived(account, failurePacket);
1739            } catch (StateChangingError error) {
1740                Log.d(
1741                        Config.LOGTAG,
1742                        account.getJid().asBareJid()
1743                                + ": caught StateChangingError("
1744                                + error.state.toString()
1745                                + ") while clearing callbacks");
1746                // ignore
1747            }
1748        }
1749        Log.d(
1750                Config.LOGTAG,
1751                account.getJid().asBareJid()
1752                        + ": done clearing iq callbacks. "
1753                        + this.packetCallbacks.size()
1754                        + " left");
1755    }
1756
1757    public void sendDiscoTimeout() {
1758        if (mWaitForDisco.compareAndSet(true, false)) {
1759            Log.d(
1760                    Config.LOGTAG,
1761                    account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1762            finalizeBind();
1763        }
1764    }
1765
1766    private void sendStartSession() {
1767        Log.d(
1768                Config.LOGTAG,
1769                account.getJid().asBareJid() + ": sending legacy session to outdated server");
1770        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1771        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1772        this.sendUnmodifiedIqPacket(
1773                startSession,
1774                (account, packet) -> {
1775                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1776                        final boolean waitForDisco = enableStreamManagement();
1777                        sendPostBindInitialization(waitForDisco, false);
1778                    } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1779                        throw new StateChangingError(Account.State.SESSION_FAILURE);
1780                    }
1781                },
1782                true);
1783    }
1784
1785    private boolean enableStreamManagement() {
1786        final boolean streamManagement =
1787                this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1788        if (streamManagement) {
1789            synchronized (this.mStanzaQueue) {
1790                final EnablePacket enable = new EnablePacket();
1791                tagWriter.writeStanzaAsync(enable);
1792                stanzasSent = 0;
1793                mStanzaQueue.clear();
1794            }
1795            return true;
1796        } else {
1797            return false;
1798        }
1799    }
1800
1801    private void sendPostBindInitialization(
1802            final boolean waitForDisco, final boolean carbonsEnabled) {
1803        features.carbonsEnabled = carbonsEnabled;
1804        features.blockListRequested = false;
1805        synchronized (this.disco) {
1806            this.disco.clear();
1807        }
1808        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1809        mPendingServiceDiscoveries.set(0);
1810        if (!waitForDisco
1811                || Patches.DISCO_EXCEPTIONS.contains(
1812                        account.getJid().getDomain().toEscapedString())) {
1813            Log.d(
1814                    Config.LOGTAG,
1815                    account.getJid().asBareJid() + ": do not wait for service discovery");
1816            mWaitForDisco.set(false);
1817        } else {
1818            mWaitForDisco.set(true);
1819        }
1820        lastDiscoStarted = SystemClock.elapsedRealtime();
1821        mXmppConnectionService.scheduleWakeUpCall(
1822                Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1823        final Element caps = streamFeatures.findChild("c");
1824        final String hash = caps == null ? null : caps.getAttribute("hash");
1825        final String ver = caps == null ? null : caps.getAttribute("ver");
1826        ServiceDiscoveryResult discoveryResult = null;
1827        if (hash != null && ver != null) {
1828            discoveryResult =
1829                    mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1830        }
1831        final boolean requestDiscoItemsFirst =
1832                !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1833        if (requestDiscoItemsFirst) {
1834            sendServiceDiscoveryItems(account.getDomain());
1835        }
1836        if (discoveryResult == null) {
1837            sendServiceDiscoveryInfo(account.getDomain());
1838        } else {
1839            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1840            disco.put(account.getDomain(), discoveryResult);
1841        }
1842        discoverMamPreferences();
1843        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1844        if (!requestDiscoItemsFirst) {
1845            sendServiceDiscoveryItems(account.getDomain());
1846        }
1847
1848        if (!mWaitForDisco.get()) {
1849            finalizeBind();
1850        }
1851        this.lastSessionStarted = SystemClock.elapsedRealtime();
1852    }
1853
1854    private void sendServiceDiscoveryInfo(final Jid jid) {
1855        mPendingServiceDiscoveries.incrementAndGet();
1856        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1857        iq.setTo(jid);
1858        iq.query("http://jabber.org/protocol/disco#info");
1859        this.sendIqPacket(
1860                iq,
1861                (account, packet) -> {
1862                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1863                        boolean advancedStreamFeaturesLoaded;
1864                        synchronized (XmppConnection.this.disco) {
1865                            ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1866                            if (jid.equals(account.getDomain())) {
1867                                mXmppConnectionService.databaseBackend.insertDiscoveryResult(
1868                                        result);
1869                            }
1870                            disco.put(jid, result);
1871                            advancedStreamFeaturesLoaded =
1872                                    disco.containsKey(account.getDomain())
1873                                            && disco.containsKey(account.getJid().asBareJid());
1874                        }
1875                        if (advancedStreamFeaturesLoaded
1876                                && (jid.equals(account.getDomain())
1877                                        || jid.equals(account.getJid().asBareJid()))) {
1878                            enableAdvancedStreamFeatures();
1879                        }
1880                    } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1881                        Log.d(
1882                                Config.LOGTAG,
1883                                account.getJid().asBareJid()
1884                                        + ": could not query disco info for "
1885                                        + jid.toString());
1886                        final boolean serverOrAccount =
1887                                jid.equals(account.getDomain())
1888                                        || jid.equals(account.getJid().asBareJid());
1889                        final boolean advancedStreamFeaturesLoaded;
1890                        if (serverOrAccount) {
1891                            synchronized (XmppConnection.this.disco) {
1892                                disco.put(jid, ServiceDiscoveryResult.empty());
1893                                advancedStreamFeaturesLoaded =
1894                                        disco.containsKey(account.getDomain())
1895                                                && disco.containsKey(account.getJid().asBareJid());
1896                            }
1897                        } else {
1898                            advancedStreamFeaturesLoaded = false;
1899                        }
1900                        if (advancedStreamFeaturesLoaded) {
1901                            enableAdvancedStreamFeatures();
1902                        }
1903                    }
1904                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1905                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
1906                                && mWaitForDisco.compareAndSet(true, false)) {
1907                            finalizeBind();
1908                        }
1909                    }
1910                });
1911    }
1912
1913    private void discoverMamPreferences() {
1914        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1915        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1916        sendIqPacket(
1917                request,
1918                (account, response) -> {
1919                    if (response.getType() == IqPacket.TYPE.RESULT) {
1920                        Element prefs =
1921                                response.findChild(
1922                                        "prefs", MessageArchiveService.Version.MAM_2.namespace);
1923                        isMamPreferenceAlways =
1924                                "always"
1925                                        .equals(
1926                                                prefs == null
1927                                                        ? null
1928                                                        : prefs.getAttribute("default"));
1929                    }
1930                });
1931    }
1932
1933    private void discoverCommands() {
1934        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1935        request.setTo(account.getDomain());
1936        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
1937        sendIqPacket(
1938                request,
1939                (account, response) -> {
1940                    if (response.getType() == IqPacket.TYPE.RESULT) {
1941                        final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
1942                        if (query == null) {
1943                            return;
1944                        }
1945                        final HashMap<String, Jid> commands = new HashMap<>();
1946                        for (final Element child : query.getChildren()) {
1947                            if ("item".equals(child.getName())) {
1948                                final String node = child.getAttribute("node");
1949                                final Jid jid = child.getAttributeAsJid("jid");
1950                                if (node != null && jid != null) {
1951                                    commands.put(node, jid);
1952                                }
1953                            }
1954                        }
1955                        synchronized (this.commands) {
1956                            this.commands.clear();
1957                            this.commands.putAll(commands);
1958                        }
1959                    }
1960                });
1961    }
1962
1963    public boolean isMamPreferenceAlways() {
1964        return isMamPreferenceAlways;
1965    }
1966
1967    private void finalizeBind() {
1968        if (bindListener != null) {
1969            bindListener.onBind(account);
1970        }
1971        changeStatusToOnline();
1972    }
1973
1974    private void enableAdvancedStreamFeatures() {
1975        if (getFeatures().blocking() && !features.blockListRequested) {
1976            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1977            this.sendIqPacket(
1978                    getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1979        }
1980        for (final OnAdvancedStreamFeaturesLoaded listener :
1981                advancedStreamFeaturesLoadedListeners) {
1982            listener.onAdvancedStreamFeaturesAvailable(account);
1983        }
1984        if (getFeatures().carbons() && !features.carbonsEnabled) {
1985            sendEnableCarbons();
1986        }
1987        if (getFeatures().commands()) {
1988            discoverCommands();
1989        }
1990    }
1991
1992    private void sendServiceDiscoveryItems(final Jid server) {
1993        mPendingServiceDiscoveries.incrementAndGet();
1994        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1995        iq.setTo(server.getDomain());
1996        iq.query("http://jabber.org/protocol/disco#items");
1997        this.sendIqPacket(
1998                iq,
1999                (account, packet) -> {
2000                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2001                        final HashSet<Jid> items = new HashSet<>();
2002                        final List<Element> elements = packet.query().getChildren();
2003                        for (final Element element : elements) {
2004                            if (element.getName().equals("item")) {
2005                                final Jid jid =
2006                                        InvalidJid.getNullForInvalid(
2007                                                element.getAttributeAsJid("jid"));
2008                                if (jid != null && !jid.equals(account.getDomain())) {
2009                                    items.add(jid);
2010                                }
2011                            }
2012                        }
2013                        for (Jid jid : items) {
2014                            sendServiceDiscoveryInfo(jid);
2015                        }
2016                    } else {
2017                        Log.d(
2018                                Config.LOGTAG,
2019                                account.getJid().asBareJid()
2020                                        + ": could not query disco items of "
2021                                        + server);
2022                    }
2023                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2024                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2025                                && mWaitForDisco.compareAndSet(true, false)) {
2026                            finalizeBind();
2027                        }
2028                    }
2029                });
2030    }
2031
2032    private void sendEnableCarbons() {
2033        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2034        iq.addChild("enable", Namespace.CARBONS);
2035        this.sendIqPacket(
2036                iq,
2037                (account, packet) -> {
2038                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2039                        Log.d(
2040                                Config.LOGTAG,
2041                                account.getJid().asBareJid() + ": successfully enabled carbons");
2042                        features.carbonsEnabled = true;
2043                    } else {
2044                        Log.d(
2045                                Config.LOGTAG,
2046                                account.getJid().asBareJid()
2047                                        + ": could not enable carbons "
2048                                        + packet);
2049                    }
2050                });
2051    }
2052
2053    private void processStreamError(final Tag currentTag) throws IOException {
2054        final Element streamError = tagReader.readElement(currentTag);
2055        if (streamError == null) {
2056            return;
2057        }
2058        if (streamError.hasChild("conflict")) {
2059            account.setResource(createNewResource());
2060            Log.d(
2061                    Config.LOGTAG,
2062                    account.getJid().asBareJid()
2063                            + ": switching resource due to conflict ("
2064                            + account.getResource()
2065                            + ")");
2066            throw new IOException();
2067        } else if (streamError.hasChild("host-unknown")) {
2068            throw new StateChangingException(Account.State.HOST_UNKNOWN);
2069        } else if (streamError.hasChild("policy-violation")) {
2070            this.lastConnect = SystemClock.elapsedRealtime();
2071            final String text = streamError.findChildContent("text");
2072            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2073            failPendingMessages(text);
2074            throw new StateChangingException(Account.State.POLICY_VIOLATION);
2075        } else {
2076            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2077            throw new StateChangingException(Account.State.STREAM_ERROR);
2078        }
2079    }
2080
2081    private void failPendingMessages(final String error) {
2082        synchronized (this.mStanzaQueue) {
2083            for (int i = 0; i < mStanzaQueue.size(); ++i) {
2084                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
2085                if (stanza instanceof MessagePacket) {
2086                    final MessagePacket packet = (MessagePacket) stanza;
2087                    final String id = packet.getId();
2088                    final Jid to = packet.getTo();
2089                    mXmppConnectionService.markMessage(
2090                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2091                }
2092            }
2093        }
2094    }
2095
2096    private boolean establishStream(final SSLSockets.Version sslVersion)
2097            throws IOException, InterruptedException {
2098        final SaslMechanism quickStartMechanism =
2099                SaslMechanism.ensureAvailable(account.getQuickStartMechanism(), sslVersion);
2100        final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2101        if (secureConnection
2102                && Config.QUICKSTART_ENABLED
2103                && quickStartMechanism != null
2104                && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2105            mXmppConnectionService.restoredFromDatabaseLatch.await();
2106            this.saslMechanism = quickStartMechanism;
2107            final boolean usingFast = quickStartMechanism instanceof HashedToken;
2108            final Element authenticate =
2109                    generateAuthenticationRequest(quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)), usingFast);
2110            authenticate.setAttribute("mechanism", quickStartMechanism.getMechanism());
2111            sendStartStream(true, false);
2112            tagWriter.writeElement(authenticate);
2113            Log.d(
2114                    Config.LOGTAG,
2115                    account.getJid().toString()
2116                            + ": quick start with "
2117                            + quickStartMechanism.getMechanism());
2118            return true;
2119        } else {
2120            sendStartStream(secureConnection, true);
2121            return false;
2122        }
2123    }
2124
2125    private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2126        final Tag stream = Tag.start("stream:stream");
2127        stream.setAttribute("to", account.getServer());
2128        if (from) {
2129            stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2130        }
2131        stream.setAttribute("version", "1.0");
2132        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2133        stream.setAttribute("xmlns", "jabber:client");
2134        stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2135        tagWriter.writeTag(stream, flush);
2136    }
2137
2138    private String createNewResource() {
2139        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
2140    }
2141
2142    private String nextRandomId() {
2143        return nextRandomId(false);
2144    }
2145
2146    private String nextRandomId(final boolean s) {
2147        return CryptoHelper.random(s ? 3 : 9);
2148    }
2149
2150    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
2151        packet.setFrom(account.getJid());
2152        return this.sendUnmodifiedIqPacket(packet, callback, false);
2153    }
2154
2155    public synchronized String sendUnmodifiedIqPacket(
2156            final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
2157        if (packet.getId() == null) {
2158            packet.setAttribute("id", nextRandomId());
2159        }
2160        if (callback != null) {
2161            synchronized (this.packetCallbacks) {
2162                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2163            }
2164        }
2165        this.sendPacket(packet, force);
2166        return packet.getId();
2167    }
2168
2169    public void sendMessagePacket(final MessagePacket packet) {
2170        this.sendPacket(packet);
2171    }
2172
2173    public void sendPresencePacket(final PresencePacket packet) {
2174        this.sendPacket(packet);
2175    }
2176
2177    private synchronized void sendPacket(final AbstractStanza packet) {
2178        sendPacket(packet, false);
2179    }
2180
2181    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
2182        if (stanzasSent == Integer.MAX_VALUE) {
2183            resetStreamId();
2184            disconnect(true);
2185            return;
2186        }
2187        synchronized (this.mStanzaQueue) {
2188            if (force || isBound) {
2189                tagWriter.writeStanzaAsync(packet);
2190            } else {
2191                Log.d(
2192                        Config.LOGTAG,
2193                        account.getJid().asBareJid()
2194                                + " do not write stanza to unbound stream "
2195                                + packet.toString());
2196            }
2197            if (packet instanceof AbstractAcknowledgeableStanza) {
2198                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
2199
2200                if (this.mStanzaQueue.size() != 0) {
2201                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2202                    if (currentHighestKey != stanzasSent) {
2203                        throw new AssertionError("Stanza count messed up");
2204                    }
2205                }
2206
2207                ++stanzasSent;
2208                this.mStanzaQueue.append(stanzasSent, stanza);
2209                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
2210                    if (Config.EXTENDED_SM_LOGGING) {
2211                        Log.d(
2212                                Config.LOGTAG,
2213                                account.getJid().asBareJid()
2214                                        + ": requesting ack for message stanza #"
2215                                        + stanzasSent);
2216                    }
2217                    tagWriter.writeStanzaAsync(new RequestPacket());
2218                }
2219            }
2220        }
2221    }
2222
2223    public void sendPing() {
2224        if (!r()) {
2225            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2226            iq.setFrom(account.getJid());
2227            iq.addChild("ping", Namespace.PING);
2228            this.sendIqPacket(iq, null);
2229        }
2230        this.lastPingSent = SystemClock.elapsedRealtime();
2231    }
2232
2233    public void setOnMessagePacketReceivedListener(final OnMessagePacketReceived listener) {
2234        this.messageListener = listener;
2235    }
2236
2237    public void setOnUnregisteredIqPacketReceivedListener(final OnIqPacketReceived listener) {
2238        this.unregisteredIqListener = listener;
2239    }
2240
2241    public void setOnPresencePacketReceivedListener(final OnPresencePacketReceived listener) {
2242        this.presenceListener = listener;
2243    }
2244
2245    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2246        this.jingleListener = listener;
2247    }
2248
2249    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2250        this.statusListener = listener;
2251    }
2252
2253    public void setOnBindListener(final OnBindListener listener) {
2254        this.bindListener = listener;
2255    }
2256
2257    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2258        this.acknowledgedListener = listener;
2259    }
2260
2261    public void addOnAdvancedStreamFeaturesAvailableListener(
2262            final OnAdvancedStreamFeaturesLoaded listener) {
2263        this.advancedStreamFeaturesLoadedListeners.add(listener);
2264    }
2265
2266    private void forceCloseSocket() {
2267        FileBackend.close(this.socket);
2268        FileBackend.close(this.tagReader);
2269    }
2270
2271    public void interrupt() {
2272        if (this.mThread != null) {
2273            this.mThread.interrupt();
2274        }
2275    }
2276
2277    public void disconnect(final boolean force) {
2278        interrupt();
2279        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2280        if (force) {
2281            forceCloseSocket();
2282        } else {
2283            final TagWriter currentTagWriter = this.tagWriter;
2284            if (currentTagWriter.isActive()) {
2285                currentTagWriter.finish();
2286                final Socket currentSocket = this.socket;
2287                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2288                try {
2289                    currentTagWriter.await(1, TimeUnit.SECONDS);
2290                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2291                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2292                    if (streamCountDownLatch != null) {
2293                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2294                            Log.d(
2295                                    Config.LOGTAG,
2296                                    account.getJid().asBareJid() + ": remote ended stream");
2297                        } else {
2298                            Log.d(
2299                                    Config.LOGTAG,
2300                                    account.getJid().asBareJid()
2301                                            + ": remote has not closed socket. force closing");
2302                        }
2303                    }
2304                } catch (InterruptedException e) {
2305                    Log.d(
2306                            Config.LOGTAG,
2307                            account.getJid().asBareJid()
2308                                    + ": interrupted while gracefully closing stream");
2309                } catch (final IOException e) {
2310                    Log.d(
2311                            Config.LOGTAG,
2312                            account.getJid().asBareJid()
2313                                    + ": io exception during disconnect ("
2314                                    + e.getMessage()
2315                                    + ")");
2316                } finally {
2317                    FileBackend.close(currentSocket);
2318                }
2319            } else {
2320                forceCloseSocket();
2321            }
2322        }
2323    }
2324
2325    private void resetStreamId() {
2326        this.streamId = null;
2327    }
2328
2329    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2330        synchronized (this.disco) {
2331            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2332            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2333                if (cursor.getValue().getFeatures().contains(feature)) {
2334                    items.add(cursor);
2335                }
2336            }
2337            return items;
2338        }
2339    }
2340
2341    public Jid findDiscoItemByFeature(final String feature) {
2342        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2343        if (items.size() >= 1) {
2344            return items.get(0).getKey();
2345        }
2346        return null;
2347    }
2348
2349    public boolean r() {
2350        if (getFeatures().sm()) {
2351            this.tagWriter.writeStanzaAsync(new RequestPacket());
2352            return true;
2353        } else {
2354            return false;
2355        }
2356    }
2357
2358    public List<String> getMucServersWithholdAccount() {
2359        final List<String> servers = getMucServers();
2360        servers.remove(account.getDomain().toEscapedString());
2361        return servers;
2362    }
2363
2364    public List<String> getMucServers() {
2365        List<String> servers = new ArrayList<>();
2366        synchronized (this.disco) {
2367            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2368                final ServiceDiscoveryResult value = cursor.getValue();
2369                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2370                        && value.hasIdentity("conference", "text")
2371                        && !value.getFeatures().contains("jabber:iq:gateway")
2372                        && !value.hasIdentity("conference", "irc")) {
2373                    servers.add(cursor.getKey().toString());
2374                }
2375            }
2376        }
2377        return servers;
2378    }
2379
2380    public String getMucServer() {
2381        List<String> servers = getMucServers();
2382        return servers.size() > 0 ? servers.get(0) : null;
2383    }
2384
2385    public int getTimeToNextAttempt() {
2386        final int additionalTime =
2387                account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2388        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2389        final int secondsSinceLast =
2390                (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2391        return interval - secondsSinceLast;
2392    }
2393
2394    public int getAttempt() {
2395        return this.attempt;
2396    }
2397
2398    public Features getFeatures() {
2399        return this.features;
2400    }
2401
2402    public long getLastSessionEstablished() {
2403        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2404        return System.currentTimeMillis() - diff;
2405    }
2406
2407    public long getLastConnect() {
2408        return this.lastConnect;
2409    }
2410
2411    public long getLastPingSent() {
2412        return this.lastPingSent;
2413    }
2414
2415    public long getLastDiscoStarted() {
2416        return this.lastDiscoStarted;
2417    }
2418
2419    public long getLastPacketReceived() {
2420        return this.lastPacketReceived;
2421    }
2422
2423    public void sendActive() {
2424        this.sendPacket(new ActivePacket());
2425    }
2426
2427    public void sendInactive() {
2428        this.sendPacket(new InactivePacket());
2429    }
2430
2431    public void resetAttemptCount(boolean resetConnectTime) {
2432        this.attempt = 0;
2433        if (resetConnectTime) {
2434            this.lastConnect = 0;
2435        }
2436    }
2437
2438    public void setInteractive(boolean interactive) {
2439        this.mInteractive = interactive;
2440    }
2441
2442    public Identity getServerIdentity() {
2443        synchronized (this.disco) {
2444            ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
2445            if (result == null) {
2446                return Identity.UNKNOWN;
2447            }
2448            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
2449                if (id.getType().equals("im")
2450                        && id.getCategory().equals("server")
2451                        && id.getName() != null) {
2452                    switch (id.getName()) {
2453                        case "Prosody":
2454                            return Identity.PROSODY;
2455                        case "ejabberd":
2456                            return Identity.EJABBERD;
2457                        case "Slack-XMPP":
2458                            return Identity.SLACK;
2459                    }
2460                }
2461            }
2462        }
2463        return Identity.UNKNOWN;
2464    }
2465
2466    private IqGenerator getIqGenerator() {
2467        return mXmppConnectionService.getIqGenerator();
2468    }
2469
2470    public enum Identity {
2471        FACEBOOK,
2472        SLACK,
2473        EJABBERD,
2474        PROSODY,
2475        NIMBUZZ,
2476        UNKNOWN
2477    }
2478
2479    private class MyKeyManager implements X509KeyManager {
2480        @Override
2481        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2482            return account.getPrivateKeyAlias();
2483        }
2484
2485        @Override
2486        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2487            return null;
2488        }
2489
2490        @Override
2491        public X509Certificate[] getCertificateChain(String alias) {
2492            Log.d(Config.LOGTAG, "getting certificate chain");
2493            try {
2494                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2495            } catch (final Exception e) {
2496                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2497                return new X509Certificate[0];
2498            }
2499        }
2500
2501        @Override
2502        public String[] getClientAliases(String s, Principal[] principals) {
2503            final String alias = account.getPrivateKeyAlias();
2504            return alias != null ? new String[] {alias} : new String[0];
2505        }
2506
2507        @Override
2508        public String[] getServerAliases(String s, Principal[] principals) {
2509            return new String[0];
2510        }
2511
2512        @Override
2513        public PrivateKey getPrivateKey(String alias) {
2514            try {
2515                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2516            } catch (Exception e) {
2517                return null;
2518            }
2519        }
2520    }
2521
2522    private static class StateChangingError extends Error {
2523        private final Account.State state;
2524
2525        public StateChangingError(Account.State state) {
2526            this.state = state;
2527        }
2528    }
2529
2530    private static class StateChangingException extends IOException {
2531        private final Account.State state;
2532
2533        public StateChangingException(Account.State state) {
2534            this.state = state;
2535        }
2536    }
2537
2538    public class Features {
2539        XmppConnection connection;
2540        private boolean carbonsEnabled = false;
2541        private boolean encryptionEnabled = false;
2542        private boolean blockListRequested = false;
2543
2544        public Features(final XmppConnection connection) {
2545            this.connection = connection;
2546        }
2547
2548        private boolean hasDiscoFeature(final Jid server, final String feature) {
2549            synchronized (XmppConnection.this.disco) {
2550                final ServiceDiscoveryResult sdr = connection.disco.get(server);
2551                return sdr != null && sdr.getFeatures().contains(feature);
2552            }
2553        }
2554
2555        public boolean carbons() {
2556            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2557        }
2558
2559        public boolean commands() {
2560            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2561        }
2562
2563        public boolean easyOnboardingInvites() {
2564            synchronized (commands) {
2565                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2566            }
2567        }
2568
2569        public boolean bookmarksConversion() {
2570            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2571                    && pepPublishOptions();
2572        }
2573
2574        public boolean avatarConversion() {
2575            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION)
2576                    && pepPublishOptions();
2577        }
2578
2579        public boolean blocking() {
2580            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2581        }
2582
2583        public boolean spamReporting() {
2584            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
2585        }
2586
2587        public boolean flexibleOfflineMessageRetrieval() {
2588            return hasDiscoFeature(
2589                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2590        }
2591
2592        public boolean register() {
2593            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2594        }
2595
2596        public boolean invite() {
2597            return connection.streamFeatures != null
2598                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2599        }
2600
2601        public boolean sm() {
2602            return streamId != null
2603                    || (connection.streamFeatures != null
2604                            && connection.streamFeatures.hasChild("sm"));
2605        }
2606
2607        public boolean csi() {
2608            return connection.streamFeatures != null
2609                    && connection.streamFeatures.hasChild("csi", Namespace.CSI);
2610        }
2611
2612        public boolean pep() {
2613            synchronized (XmppConnection.this.disco) {
2614                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2615                return info != null && info.hasIdentity("pubsub", "pep");
2616            }
2617        }
2618
2619        public boolean pepPersistent() {
2620            synchronized (XmppConnection.this.disco) {
2621                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2622                return info != null
2623                        && info.getFeatures()
2624                                .contains("http://jabber.org/protocol/pubsub#persistent-items");
2625            }
2626        }
2627
2628        public boolean pepPublishOptions() {
2629            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2630        }
2631
2632        public boolean pepOmemoWhitelisted() {
2633            return hasDiscoFeature(
2634                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2635        }
2636
2637        public boolean mam() {
2638            return MessageArchiveService.Version.has(getAccountFeatures());
2639        }
2640
2641        public List<String> getAccountFeatures() {
2642            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2643            return result == null ? Collections.emptyList() : result.getFeatures();
2644        }
2645
2646        public boolean push() {
2647            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2648                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2649        }
2650
2651        public boolean rosterVersioning() {
2652            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2653        }
2654
2655        public void setBlockListRequested(boolean value) {
2656            this.blockListRequested = value;
2657        }
2658
2659        public boolean httpUpload(long filesize) {
2660            if (Config.DISABLE_HTTP_UPLOAD) {
2661                return false;
2662            } else {
2663                for (String namespace :
2664                        new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2665                    List<Entry<Jid, ServiceDiscoveryResult>> items =
2666                            findDiscoItemsByFeature(namespace);
2667                    if (items.size() > 0) {
2668                        try {
2669                            long maxsize =
2670                                    Long.parseLong(
2671                                            items.get(0)
2672                                                    .getValue()
2673                                                    .getExtendedDiscoInformation(
2674                                                            namespace, "max-file-size"));
2675                            if (filesize <= maxsize) {
2676                                return true;
2677                            } else {
2678                                Log.d(
2679                                        Config.LOGTAG,
2680                                        account.getJid().asBareJid()
2681                                                + ": http upload is not available for files with size "
2682                                                + filesize
2683                                                + " (max is "
2684                                                + maxsize
2685                                                + ")");
2686                                return false;
2687                            }
2688                        } catch (Exception e) {
2689                            return true;
2690                        }
2691                    }
2692                }
2693                return false;
2694            }
2695        }
2696
2697        public boolean useLegacyHttpUpload() {
2698            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
2699                    && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
2700        }
2701
2702        public long getMaxHttpUploadSize() {
2703            for (String namespace :
2704                    new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2705                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2706                if (items.size() > 0) {
2707                    try {
2708                        return Long.parseLong(
2709                                items.get(0)
2710                                        .getValue()
2711                                        .getExtendedDiscoInformation(namespace, "max-file-size"));
2712                    } catch (Exception e) {
2713                        // ignored
2714                    }
2715                }
2716            }
2717            return -1;
2718        }
2719
2720        public boolean stanzaIds() {
2721            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2722        }
2723
2724        public boolean bookmarks2() {
2725            return Config
2726                    .USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
2727        }
2728
2729        public boolean externalServiceDiscovery() {
2730            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
2731        }
2732    }
2733}