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