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