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            } else {
1599                hashTokenRequest = null;
1600            }
1601            final Collection<String> bindFeatures = Bind2.features(inline);
1602            quickStartAvailable =
1603                    sm
1604                            && bindFeatures != null
1605                            && bindFeatures.containsAll(Bind2.QUICKSTART_FEATURES);
1606            if (bindFeatures != null) {
1607                try {
1608                    mXmppConnectionService.restoredFromDatabaseLatch.await();
1609                } catch (final InterruptedException e) {
1610                    Log.d(
1611                            Config.LOGTAG,
1612                            account.getJid().asBareJid()
1613                                    + ": interrupted while waiting for DB restore during SASL2"
1614                                    + " bind");
1615                    return;
1616                }
1617            }
1618            loginInfo = new LoginInfo(saslMechanism, version, bindFeatures);
1619            this.hashTokenRequest = hashTokenRequest;
1620            authenticate =
1621                    generateAuthenticationRequest(
1622                            firstMessage, usingFast, hashTokenRequest, bindFeatures, sm);
1623        } else {
1624            throw new AssertionError("Missing implementation for " + version);
1625        }
1626        this.loginInfo = loginInfo;
1627        if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, quickStartAvailable)) {
1628            mXmppConnectionService.databaseBackend.updateAccount(account);
1629        }
1630
1631        Log.d(
1632                Config.LOGTAG,
1633                account.getJid().toString()
1634                        + ": Authenticating with "
1635                        + version
1636                        + "/"
1637                        + LoginInfo.mechanism(loginInfo).getMechanism());
1638        authenticate.setMechanism(LoginInfo.mechanism(loginInfo));
1639        synchronized (this.mStanzaQueue) {
1640            this.stanzasSentBeforeAuthentication = this.stanzasSent;
1641            tagWriter.writeElement(authenticate);
1642        }
1643    }
1644
1645    private static boolean isFastTokenAvailable(final Authentication authentication) {
1646        final var inline = authentication == null ? null : authentication.getInline();
1647        return inline != null && inline.hasExtension(Fast.class);
1648    }
1649
1650    private void validate(
1651            final @Nullable SaslMechanism saslMechanism, Collection<String> mechanisms)
1652            throws StateChangingException {
1653        if (saslMechanism == null) {
1654            Log.d(
1655                    Config.LOGTAG,
1656                    account.getJid().asBareJid()
1657                            + ": unable to find supported SASL mechanism in "
1658                            + mechanisms);
1659            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1660        }
1661        checkRequireChannelBinding(saslMechanism);
1662        if (SaslMechanism.hashedToken(saslMechanism)) {
1663            return;
1664        }
1665        final int pinnedMechanism = account.getPinnedMechanismPriority();
1666        if (pinnedMechanism > saslMechanism.getPriority()) {
1667            Log.e(
1668                    Config.LOGTAG,
1669                    "Auth failed. Authentication mechanism "
1670                            + saslMechanism.getMechanism()
1671                            + " has lower priority ("
1672                            + saslMechanism.getPriority()
1673                            + ") than pinned priority ("
1674                            + pinnedMechanism
1675                            + "). Possible downgrade attack?");
1676            throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1677        }
1678    }
1679
1680    private void checkRequireChannelBinding(@NonNull final SaslMechanism mechanism)
1681            throws StateChangingException {
1682        if (appSettings.isRequireChannelBinding()) {
1683            if (mechanism instanceof ChannelBindingMechanism) {
1684                return;
1685            }
1686            Log.d(Config.LOGTAG, account.getJid() + ": server did not offer channel binding");
1687            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1688        }
1689    }
1690
1691    private void checkAssignedDomainOrThrow(final Jid jid) throws StateChangingException {
1692        if (jid == null) {
1693            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": bind response is missing jid");
1694            throw new StateChangingException(Account.State.BIND_FAILURE);
1695        }
1696        final var current = this.account.getJid().getDomain();
1697        if (jid.getDomain().equals(current)) {
1698            return;
1699        }
1700        Log.d(
1701                Config.LOGTAG,
1702                account.getJid().asBareJid()
1703                        + ": server tried to re-assign domain to "
1704                        + jid.getDomain());
1705        throw new StateChangingException(Account.State.BIND_FAILURE);
1706    }
1707
1708    private void checkAssignedDomain(final Jid jid) {
1709        try {
1710            checkAssignedDomainOrThrow(jid);
1711        } catch (final StateChangingException e) {
1712            throw new StateChangingError(e.state);
1713        }
1714    }
1715
1716    private AuthenticationRequest generateAuthenticationRequest(
1717            final String firstMessage, final boolean usingFast) {
1718        return generateAuthenticationRequest(
1719                firstMessage, usingFast, null, Bind2.QUICKSTART_FEATURES, true);
1720    }
1721
1722    private AuthenticationRequest generateAuthenticationRequest(
1723            final String firstMessage,
1724            final boolean usingFast,
1725            final HashedToken.Mechanism hashedTokenRequest,
1726            final Collection<String> bind,
1727            final boolean inlineStreamManagement) {
1728        final var authenticate = new Authenticate();
1729        if (!Strings.isNullOrEmpty(firstMessage)) {
1730            authenticate.addChild("initial-response").setContent(firstMessage);
1731        }
1732        final var userAgent =
1733                authenticate.addExtension(
1734                        new UserAgent(
1735                                AccountUtils.publicDeviceId(
1736                                        account, appSettings.getInstallationId())));
1737        userAgent.setSoftware(
1738                String.format("%s %s", BuildConfig.APP_NAME, BuildConfig.VERSION_NAME));
1739        if (!PhoneHelper.isEmulator()) {
1740            userAgent.setDevice(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1741        }
1742        // do not include bind if 'inlineStreamManagement' is missing and we have a streamId
1743        // (because we would rather just do a normal SM/resume)
1744        final boolean mayAttemptBind = streamId == null || inlineStreamManagement;
1745        if (bind != null && mayAttemptBind) {
1746            authenticate.addChild(generateBindRequest(bind));
1747        }
1748        if (inlineStreamManagement && streamId != null) {
1749            final var streamId = this.streamId.id;
1750            final var resume = new Resume(streamId, stanzasReceived);
1751            prepareForResume(streamId);
1752            authenticate.addExtension(resume);
1753        }
1754        if (hashedTokenRequest != null) {
1755            authenticate.addExtension(new RequestToken(hashedTokenRequest));
1756        }
1757        if (usingFast) {
1758            authenticate.addExtension(new Fast());
1759        }
1760        return authenticate;
1761    }
1762
1763    private void prepareForResume(final String streamId) {
1764        this.mSmCatchupMessageCounter.set(0);
1765        this.mWaitingForSmCatchup.set(true);
1766        this.pendingResumeId.push(streamId);
1767    }
1768
1769    private Bind generateBindRequest(final Collection<String> bindFeatures) {
1770        Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1771        final var bind = new Bind();
1772        bind.setTag(BuildConfig.APP_NAME);
1773        if (bindFeatures.contains(Namespace.CARBONS)) {
1774            bind.addExtension(new im.conversations.android.xmpp.model.carbons.Enable());
1775        }
1776        if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1777            bind.addExtension(new Enable());
1778        }
1779        return bind;
1780    }
1781
1782    private void register() {
1783        final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1784        if (preAuth != null && features.invite()) {
1785            final Iq preAuthRequest = new Iq(Iq.Type.SET);
1786            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1787            sendUnmodifiedIqPacket(
1788                    preAuthRequest,
1789                    (response) -> {
1790                        if (response.getType() == Iq.Type.RESULT) {
1791                            sendRegistryRequest();
1792                        } else {
1793                            final String error = response.getErrorCondition();
1794                            Log.d(
1795                                    Config.LOGTAG,
1796                                    account.getJid().asBareJid()
1797                                            + ": failed to pre auth. "
1798                                            + error);
1799                            throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1800                        }
1801                    },
1802                    true);
1803        } else {
1804            sendRegistryRequest();
1805        }
1806    }
1807
1808    private void sendRegistryRequest() {
1809        final Iq register = new Iq(Iq.Type.GET);
1810        register.query(Namespace.REGISTER);
1811        register.setTo(account.getDomain());
1812        sendUnmodifiedIqPacket(
1813                register,
1814                (packet) -> {
1815                    if (packet.getType() == Iq.Type.TIMEOUT) {
1816                        return;
1817                    }
1818                    if (packet.getType() == Iq.Type.ERROR) {
1819                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1820                    }
1821                    final Element query = packet.query(Namespace.REGISTER);
1822                    if (query.hasChild("username") && (query.hasChild("password"))) {
1823                        final Iq register1 = new Iq(Iq.Type.SET);
1824                        final Element username =
1825                                new Element("username").setContent(account.getUsername());
1826                        final Element password =
1827                                new Element("password").setContent(account.getPassword());
1828                        register1.query(Namespace.REGISTER).addChild(username);
1829                        register1.query().addChild(password);
1830                        register1.setFrom(account.getJid().asBareJid());
1831                        sendUnmodifiedIqPacket(register1, this::processRegistrationResponse, true);
1832                    } else if (query.hasChild("x", Namespace.DATA)) {
1833                        final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1834                        final Element blob = query.findChild("data", "urn:xmpp:bob");
1835                        final String id = packet.getId();
1836                        InputStream is;
1837                        if (blob != null) {
1838                            try {
1839                                final String base64Blob = blob.getContent();
1840                                final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1841                                is = new ByteArrayInputStream(strBlob);
1842                            } catch (Exception e) {
1843                                is = null;
1844                            }
1845                        } else {
1846                            final boolean useTor =
1847                                    mXmppConnectionService.useTorToConnect() || account.isOnion();
1848                            try {
1849                                final String url = data.getValue("url");
1850                                final String fallbackUrl = data.getValue("captcha-fallback-url");
1851                                if (url != null) {
1852                                    is = HttpConnectionManager.open(url, useTor);
1853                                } else if (fallbackUrl != null) {
1854                                    is = HttpConnectionManager.open(fallbackUrl, useTor);
1855                                } else {
1856                                    is = null;
1857                                }
1858                            } catch (final IOException e) {
1859                                Log.d(
1860                                        Config.LOGTAG,
1861                                        account.getJid().asBareJid() + ": unable to fetch captcha",
1862                                        e);
1863                                is = null;
1864                            }
1865                        }
1866
1867                        if (is != null) {
1868                            Bitmap captcha = BitmapFactory.decodeStream(is);
1869                            try {
1870                                if (mXmppConnectionService.displayCaptchaRequest(
1871                                        account, id, data, captcha)) {
1872                                    return;
1873                                }
1874                            } catch (Exception e) {
1875                                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1876                            }
1877                        }
1878                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1879                    } else if (query.hasChild("instructions")
1880                            || query.hasChild("x", Namespace.OOB)) {
1881                        final String instructions = query.findChildContent("instructions");
1882                        final Element oob = query.findChild("x", Namespace.OOB);
1883                        final String url = oob == null ? null : oob.findChildContent("url");
1884                        if (url != null) {
1885                            setAccountCreationFailed(url);
1886                        } else if (instructions != null) {
1887                            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1888                            if (matcher.find()) {
1889                                setAccountCreationFailed(
1890                                        instructions.substring(matcher.start(), matcher.end()));
1891                            }
1892                        }
1893                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1894                    }
1895                },
1896                true);
1897    }
1898
1899    public void sendCreateAccountWithCaptchaPacket(final String id, final Data data) {
1900        final Iq request = IqGenerator.generateCreateAccountWithCaptcha(account, id, data);
1901        this.sendUnmodifiedIqPacket(request, this::processRegistrationResponse, true);
1902    }
1903
1904    private void processRegistrationResponse(final Iq response) {
1905        if (response.getType() == Iq.Type.RESULT) {
1906            account.setOption(Account.OPTION_REGISTER, false);
1907            Log.d(
1908                    Config.LOGTAG,
1909                    account.getJid().asBareJid()
1910                            + ": successfully registered new account on server");
1911            throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
1912        } else {
1913            final Account.State state = getRegistrationFailedState(response);
1914            throw new StateChangingError(state);
1915        }
1916    }
1917
1918    @NonNull
1919    private static Account.State getRegistrationFailedState(final Iq response) {
1920        final List<String> PASSWORD_TOO_WEAK_MESSAGES =
1921                Arrays.asList("The password is too weak", "Please use a longer password.");
1922        final var error = response.getError();
1923        final var condition = error == null ? null : error.getCondition();
1924        final Account.State state;
1925        if (condition instanceof Condition.Conflict) {
1926            state = Account.State.REGISTRATION_CONFLICT;
1927        } else if (condition instanceof Condition.ResourceConstraint) {
1928            state = Account.State.REGISTRATION_PLEASE_WAIT;
1929        } else if (condition instanceof Condition.NotAcceptable
1930                && PASSWORD_TOO_WEAK_MESSAGES.contains(error.getTextAsString())) {
1931            state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
1932        } else {
1933            state = Account.State.REGISTRATION_FAILED;
1934        }
1935        return state;
1936    }
1937
1938    private void setAccountCreationFailed(final String url) {
1939        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1940        if (httpUrl != null && httpUrl.isHttps()) {
1941            this.redirectionUrl = httpUrl;
1942            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1943        }
1944        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1945    }
1946
1947    public HttpUrl getRedirectionUrl() {
1948        return this.redirectionUrl;
1949    }
1950
1951    public void resetEverything() {
1952        resetAttemptCount(true);
1953        resetStreamId();
1954        clearIqCallbacks();
1955        synchronized (this.mStanzaQueue) {
1956            this.stanzasSent = 0;
1957            this.mStanzaQueue.clear();
1958        }
1959        this.redirectionUrl = null;
1960        synchronized (this.disco) {
1961            disco.clear();
1962        }
1963        synchronized (this.commands) {
1964            this.commands.clear();
1965        }
1966        this.loginInfo = null;
1967    }
1968
1969    private void sendBindRequest() {
1970        try {
1971            mXmppConnectionService.restoredFromDatabaseLatch.await();
1972        } catch (InterruptedException e) {
1973            Log.d(
1974                    Config.LOGTAG,
1975                    account.getJid().asBareJid()
1976                            + ": interrupted while waiting for DB restore during bind");
1977            return;
1978        }
1979        clearIqCallbacks();
1980        if (account.getJid().isBareJid()) {
1981            account.setResource(createNewResource());
1982        } else {
1983            fixResource(mXmppConnectionService, account);
1984        }
1985        final Iq iq = new Iq(Iq.Type.SET);
1986        final String resource =
1987                Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND
1988                        ? CryptoHelper.random(9)
1989                        : account.getResource();
1990        iq.addExtension(new im.conversations.android.xmpp.model.bind.Bind()).setResource(resource);
1991        this.sendUnmodifiedIqPacket(
1992                iq,
1993                (packet) -> {
1994                    if (packet.getType() == Iq.Type.TIMEOUT) {
1995                        return;
1996                    }
1997                    final var bind =
1998                            packet.getExtension(
1999                                    im.conversations.android.xmpp.model.bind.Bind.class);
2000                    if (bind != null && packet.getType() == Iq.Type.RESULT) {
2001                        isBound = true;
2002                        final Jid assignedJid = bind.getJid();
2003                        checkAssignedDomain(assignedJid);
2004                        if (account.setJid(assignedJid)) {
2005                            Log.d(
2006                                    Config.LOGTAG,
2007                                    account.getJid().asBareJid()
2008                                            + ": jid changed during bind. updating database");
2009                            mXmppConnectionService.databaseBackend.updateAccount(account);
2010                        }
2011                        if (streamFeatures.hasChild("session")
2012                                && !streamFeatures.findChild("session").hasChild("optional")) {
2013                            sendStartSession();
2014                        } else {
2015                            final boolean waitForDisco = enableStreamManagement();
2016                            sendPostBindInitialization(waitForDisco, false);
2017                        }
2018                    } else {
2019                        Log.d(
2020                                Config.LOGTAG,
2021                                account.getJid()
2022                                        + ": disconnecting because of bind failure ("
2023                                        + packet);
2024                        final var error = packet.getError();
2025                        // TODO error.is(Condition)
2026                        if (packet.getType() == Iq.Type.ERROR
2027                                && error != null
2028                                && error.hasChild("conflict")) {
2029                            account.setResource(createNewResource());
2030                        }
2031                        throw new StateChangingError(Account.State.BIND_FAILURE);
2032                    }
2033                },
2034                true);
2035    }
2036
2037    private void clearIqCallbacks() {
2038        final Iq failurePacket = new Iq(Iq.Type.TIMEOUT);
2039        final ArrayList<Consumer<Iq>> callbacks = new ArrayList<>();
2040        synchronized (this.packetCallbacks) {
2041            if (this.packetCallbacks.isEmpty()) {
2042                return;
2043            }
2044            Log.d(
2045                    Config.LOGTAG,
2046                    account.getJid().asBareJid()
2047                            + ": clearing "
2048                            + this.packetCallbacks.size()
2049                            + " iq callbacks");
2050            final var iterator = this.packetCallbacks.values().iterator();
2051            while (iterator.hasNext()) {
2052                final var entry = iterator.next();
2053                callbacks.add(entry.second);
2054                iterator.remove();
2055            }
2056        }
2057        for (final var callback : callbacks) {
2058            try {
2059                callback.accept(failurePacket);
2060            } catch (StateChangingError error) {
2061                Log.d(
2062                        Config.LOGTAG,
2063                        account.getJid().asBareJid()
2064                                + ": caught StateChangingError("
2065                                + error.state.toString()
2066                                + ") while clearing callbacks");
2067                // ignore
2068            }
2069        }
2070        Log.d(
2071                Config.LOGTAG,
2072                account.getJid().asBareJid()
2073                        + ": done clearing iq callbacks. "
2074                        + this.packetCallbacks.size()
2075                        + " left");
2076    }
2077
2078    public void sendDiscoTimeout() {
2079        if (mWaitForDisco.compareAndSet(true, false)) {
2080            Log.d(
2081                    Config.LOGTAG,
2082                    account.getJid().asBareJid() + ": finalizing bind after disco timeout");
2083            finalizeBind();
2084        }
2085    }
2086
2087    private void sendStartSession() {
2088        Log.d(
2089                Config.LOGTAG,
2090                account.getJid().asBareJid() + ": sending legacy session to outdated server");
2091        final Iq startSession = new Iq(Iq.Type.SET);
2092        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
2093        this.sendUnmodifiedIqPacket(
2094                startSession,
2095                (packet) -> {
2096                    if (packet.getType() == Iq.Type.RESULT) {
2097                        final boolean waitForDisco = enableStreamManagement();
2098                        sendPostBindInitialization(waitForDisco, false);
2099                    } else if (packet.getType() != Iq.Type.TIMEOUT) {
2100                        throw new StateChangingError(Account.State.SESSION_FAILURE);
2101                    }
2102                },
2103                true);
2104    }
2105
2106    private boolean enableStreamManagement() {
2107        final boolean streamManagement = this.streamFeatures.streamManagement();
2108        if (streamManagement) {
2109            synchronized (this.mStanzaQueue) {
2110                final var enable = new Enable();
2111                tagWriter.writeStanzaAsync(enable);
2112                stanzasSent = 0;
2113                mStanzaQueue.clear();
2114            }
2115            return true;
2116        } else {
2117            return false;
2118        }
2119    }
2120
2121    private void sendPostBindInitialization(
2122            final boolean waitForDisco, final boolean carbonsEnabled) {
2123        features.carbonsEnabled = carbonsEnabled;
2124        features.blockListRequested = false;
2125        synchronized (this.disco) {
2126            this.disco.clear();
2127        }
2128        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
2129        mPendingServiceDiscoveries.set(0);
2130        mWaitForDisco.set(waitForDisco);
2131        this.lastDiscoStarted = SystemClock.elapsedRealtime();
2132        mXmppConnectionService.scheduleWakeUpCall(
2133                Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2134        final Element caps = streamFeatures.findChild("c");
2135        final String hash = caps == null ? null : caps.getAttribute("hash");
2136        final String ver = caps == null ? null : caps.getAttribute("ver");
2137        ServiceDiscoveryResult discoveryResult = null;
2138        if (hash != null && ver != null) {
2139            discoveryResult =
2140                    mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
2141        }
2142        final boolean requestDiscoItemsFirst =
2143                !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
2144        if (requestDiscoItemsFirst) {
2145            sendServiceDiscoveryItems(account.getDomain());
2146        }
2147        if (discoveryResult == null) {
2148            sendServiceDiscoveryInfo(account.getDomain());
2149        } else {
2150            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
2151            disco.put(account.getDomain(), discoveryResult);
2152        }
2153        final var features = getFeatures();
2154        if (!features.bind2()) {
2155            discoverMamPreferences();
2156        }
2157        sendServiceDiscoveryInfo(account.getJid().asBareJid());
2158        if (!requestDiscoItemsFirst) {
2159            sendServiceDiscoveryItems(account.getDomain());
2160        }
2161
2162        if (!mWaitForDisco.get()) {
2163            finalizeBind();
2164        }
2165        this.lastSessionStarted = SystemClock.elapsedRealtime();
2166    }
2167
2168    private void sendServiceDiscoveryInfo(final Jid jid) {
2169        mPendingServiceDiscoveries.incrementAndGet();
2170        final Iq iq = new Iq(Iq.Type.GET);
2171        iq.setTo(jid);
2172        iq.query("http://jabber.org/protocol/disco#info");
2173        this.sendIqPacket(
2174                iq,
2175                (packet) -> {
2176                    if (packet.getType() == Iq.Type.RESULT) {
2177                        boolean advancedStreamFeaturesLoaded;
2178                        synchronized (XmppConnection.this.disco) {
2179                            ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
2180                            if (jid.equals(account.getDomain())) {
2181                                mXmppConnectionService.databaseBackend.insertDiscoveryResult(
2182                                        result);
2183                            }
2184                            disco.put(jid, result);
2185                            advancedStreamFeaturesLoaded =
2186                                    disco.containsKey(account.getDomain())
2187                                            && disco.containsKey(account.getJid().asBareJid());
2188                        }
2189                        if (advancedStreamFeaturesLoaded
2190                                && (jid.equals(account.getDomain())
2191                                        || jid.equals(account.getJid().asBareJid()))) {
2192                            enableAdvancedStreamFeatures();
2193                        }
2194                    } else if (packet.getType() == Iq.Type.ERROR) {
2195                        Log.d(
2196                                Config.LOGTAG,
2197                                account.getJid().asBareJid()
2198                                        + ": could not query disco info for "
2199                                        + jid.toString());
2200                        final boolean serverOrAccount =
2201                                jid.equals(account.getDomain())
2202                                        || jid.equals(account.getJid().asBareJid());
2203                        final boolean advancedStreamFeaturesLoaded;
2204                        if (serverOrAccount) {
2205                            synchronized (XmppConnection.this.disco) {
2206                                disco.put(jid, ServiceDiscoveryResult.empty());
2207                                advancedStreamFeaturesLoaded =
2208                                        disco.containsKey(account.getDomain())
2209                                                && disco.containsKey(account.getJid().asBareJid());
2210                            }
2211                        } else {
2212                            advancedStreamFeaturesLoaded = false;
2213                        }
2214                        if (advancedStreamFeaturesLoaded) {
2215                            enableAdvancedStreamFeatures();
2216                        }
2217                    }
2218                    if (packet.getType() != Iq.Type.TIMEOUT) {
2219                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2220                                && mWaitForDisco.compareAndSet(true, false)) {
2221                            finalizeBind();
2222                        }
2223                    }
2224                });
2225    }
2226
2227    private void discoverMamPreferences() {
2228        final Iq request = new Iq(Iq.Type.GET);
2229        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
2230        sendIqPacket(
2231                request,
2232                (response) -> {
2233                    if (response.getType() == Iq.Type.RESULT) {
2234                        Element prefs =
2235                                response.findChild(
2236                                        "prefs", MessageArchiveService.Version.MAM_2.namespace);
2237                        isMamPreferenceAlways =
2238                                "always"
2239                                        .equals(
2240                                                prefs == null
2241                                                        ? null
2242                                                        : prefs.getAttribute("default"));
2243                    }
2244                });
2245    }
2246
2247    private void discoverCommands() {
2248        final Iq request = new Iq(Iq.Type.GET);
2249        request.setTo(account.getDomain());
2250        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
2251        sendIqPacket(
2252                request,
2253                (response) -> {
2254                    if (response.getType() == Iq.Type.RESULT) {
2255                        final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
2256                        if (query == null) {
2257                            return;
2258                        }
2259                        final HashMap<String, Jid> commands = new HashMap<>();
2260                        for (final Element child : query.getChildren()) {
2261                            if ("item".equals(child.getName())) {
2262                                final String node = child.getAttribute("node");
2263                                final Jid jid = child.getAttributeAsJid("jid");
2264                                if (node != null && jid != null) {
2265                                    commands.put(node, jid);
2266                                }
2267                            }
2268                        }
2269                        synchronized (this.commands) {
2270                            this.commands.clear();
2271                            this.commands.putAll(commands);
2272                        }
2273                    }
2274                });
2275    }
2276
2277    public boolean isMamPreferenceAlways() {
2278        return isMamPreferenceAlways;
2279    }
2280
2281    private void finalizeBind() {
2282        this.offlineMessagesRetrieved = false;
2283        this.bindListener.run();
2284        this.changeStatusToOnline();
2285    }
2286
2287    private void enableAdvancedStreamFeatures() {
2288        if (getFeatures().blocking() && !features.blockListRequested) {
2289            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
2290            this.sendIqPacket(getIqGenerator().generateGetBlockList(), unregisteredIqListener);
2291        }
2292        for (final OnAdvancedStreamFeaturesLoaded listener :
2293                advancedStreamFeaturesLoadedListeners) {
2294            listener.onAdvancedStreamFeaturesAvailable(account);
2295        }
2296        if (getFeatures().carbons() && !features.carbonsEnabled) {
2297            sendEnableCarbons();
2298        }
2299        if (getFeatures().commands()) {
2300            discoverCommands();
2301        }
2302    }
2303
2304    private void sendServiceDiscoveryItems(final Jid server) {
2305        mPendingServiceDiscoveries.incrementAndGet();
2306        final Iq iq = new Iq(Iq.Type.GET);
2307        iq.setTo(server.getDomain());
2308        iq.query("http://jabber.org/protocol/disco#items");
2309        this.sendIqPacket(
2310                iq,
2311                (packet) -> {
2312                    if (packet.getType() == Iq.Type.RESULT) {
2313                        final HashSet<Jid> items = new HashSet<>();
2314                        final List<Element> elements = packet.query().getChildren();
2315                        for (final Element element : elements) {
2316                            if (element.getName().equals("item")) {
2317                                final Jid jid =
2318                                        InvalidJid.getNullForInvalid(
2319                                                element.getAttributeAsJid("jid"));
2320                                if (jid != null && !jid.equals(account.getDomain())) {
2321                                    items.add(jid);
2322                                }
2323                            }
2324                        }
2325                        for (Jid jid : items) {
2326                            sendServiceDiscoveryInfo(jid);
2327                        }
2328                    } else {
2329                        Log.d(
2330                                Config.LOGTAG,
2331                                account.getJid().asBareJid()
2332                                        + ": could not query disco items of "
2333                                        + server);
2334                    }
2335                    if (packet.getType() != Iq.Type.TIMEOUT) {
2336                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2337                                && mWaitForDisco.compareAndSet(true, false)) {
2338                            finalizeBind();
2339                        }
2340                    }
2341                });
2342    }
2343
2344    private void sendEnableCarbons() {
2345        final Iq iq = new Iq(Iq.Type.SET);
2346        iq.addChild("enable", Namespace.CARBONS);
2347        this.sendIqPacket(
2348                iq,
2349                (packet) -> {
2350                    if (packet.getType() == Iq.Type.RESULT) {
2351                        Log.d(
2352                                Config.LOGTAG,
2353                                account.getJid().asBareJid() + ": successfully enabled carbons");
2354                        features.carbonsEnabled = true;
2355                    } else {
2356                        Log.d(
2357                                Config.LOGTAG,
2358                                account.getJid().asBareJid()
2359                                        + ": could not enable carbons "
2360                                        + packet);
2361                    }
2362                });
2363    }
2364
2365    private void processStreamError(final StreamError streamError) throws IOException {
2366        final var loginInfo = this.loginInfo;
2367        final var isSecureLoggedIn = isSecure() && LoginInfo.isSuccess(loginInfo);
2368        if (isSecureLoggedIn && streamError.hasChild("conflict")) {
2369            if (loginInfo.saslVersion == SaslMechanism.Version.SASL_2) {
2370                this.appSettings.resetInstallationId();
2371            }
2372            account.setResource(createNewResource());
2373            Log.d(
2374                    Config.LOGTAG,
2375                    account.getJid().asBareJid()
2376                            + ": switching resource due to conflict ("
2377                            + account.getResource()
2378                            + ")");
2379            throw new IOException("Closed stream due to resource conflict");
2380        } else if (streamError.hasChild("host-unknown")) {
2381            throw new StateChangingException(Account.State.HOST_UNKNOWN);
2382        } else if (streamError.hasChild("policy-violation")) {
2383            this.lastConnect = SystemClock.elapsedRealtime();
2384            final String text = streamError.findChildContent("text");
2385            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2386            if (isSecureLoggedIn) {
2387                failPendingMessages(text);
2388            }
2389            throw new StateChangingException(Account.State.POLICY_VIOLATION);
2390        } else if (streamError.hasChild("see-other-host")) {
2391            final String seeOtherHost = streamError.findChildContent("see-other-host");
2392            final Resolver.Result currentResolverResult = this.currentResolverResult;
2393            if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2394                Log.d(
2395                        Config.LOGTAG,
2396                        account.getJid().asBareJid() + ": stream error " + streamError);
2397                throw new StateChangingException(Account.State.STREAM_ERROR);
2398            }
2399            Log.d(
2400                    Config.LOGTAG,
2401                    account.getJid().asBareJid()
2402                            + ": see other host: "
2403                            + seeOtherHost
2404                            + " "
2405                            + currentResolverResult);
2406            final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2407            if (seeOtherResult != null) {
2408                this.seeOtherHostResolverResult = seeOtherResult;
2409                throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2410            } else {
2411                throw new StateChangingException(Account.State.STREAM_ERROR);
2412            }
2413        } else {
2414            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2415            throw new StateChangingException(Account.State.STREAM_ERROR);
2416        }
2417    }
2418
2419    private void failPendingMessages(final String error) {
2420        synchronized (this.mStanzaQueue) {
2421            for (int i = 0; i < mStanzaQueue.size(); ++i) {
2422                final Stanza stanza = mStanzaQueue.valueAt(i);
2423                if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message packet) {
2424                    final String id = packet.getId();
2425                    final Jid to = packet.getTo();
2426                    mXmppConnectionService.markMessage(
2427                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2428                }
2429            }
2430        }
2431    }
2432
2433    private boolean establishStream(final SSLSockets.Version sslVersion)
2434            throws IOException, InterruptedException {
2435        final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2436        final SaslMechanism quickStartMechanism;
2437        if (secureConnection) {
2438            quickStartMechanism =
2439                    SaslMechanism.ensureAvailable(
2440                            account.getQuickStartMechanism(),
2441                            sslVersion,
2442                            appSettings.isRequireChannelBinding());
2443        } else {
2444            quickStartMechanism = null;
2445        }
2446        if (secureConnection
2447                && Config.QUICKSTART_ENABLED
2448                && quickStartMechanism != null
2449                && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2450            mXmppConnectionService.restoredFromDatabaseLatch.await();
2451            this.loginInfo =
2452                    new LoginInfo(
2453                            quickStartMechanism,
2454                            SaslMechanism.Version.SASL_2,
2455                            Bind2.QUICKSTART_FEATURES);
2456            final boolean usingFast = quickStartMechanism instanceof HashedToken;
2457            final AuthenticationRequest authenticate =
2458                    generateAuthenticationRequest(
2459                            quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)),
2460                            usingFast);
2461            authenticate.setMechanism(quickStartMechanism);
2462            sendStartStream(true, false);
2463            synchronized (this.mStanzaQueue) {
2464                this.stanzasSentBeforeAuthentication = this.stanzasSent;
2465                tagWriter.writeElement(authenticate);
2466            }
2467            Log.d(
2468                    Config.LOGTAG,
2469                    account.getJid().toString()
2470                            + ": quick start with "
2471                            + quickStartMechanism.getMechanism());
2472            return true;
2473        } else {
2474            sendStartStream(secureConnection, true);
2475            return false;
2476        }
2477    }
2478
2479    private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2480        final Tag stream = Tag.start("stream:stream");
2481        stream.setAttribute("to", account.getServer());
2482        if (from) {
2483            stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2484        }
2485        stream.setAttribute("version", "1.0");
2486        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2487        stream.setAttribute("xmlns", Namespace.JABBER_CLIENT);
2488        stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2489        tagWriter.writeTag(stream, flush);
2490    }
2491
2492    private static String createNewResource() {
2493        return String.format("%s.%s", BuildConfig.APP_NAME, CryptoHelper.random(3));
2494    }
2495
2496    public String sendIqPacket(final Iq packet, final Consumer<Iq> callback) {
2497        packet.setFrom(account.getJid());
2498        return this.sendUnmodifiedIqPacket(packet, callback, false);
2499    }
2500
2501    public synchronized String sendUnmodifiedIqPacket(
2502            final Iq packet, final Consumer<Iq> callback, boolean force) {
2503        // TODO if callback != null verify that type is get or set
2504        if (packet.getId() == null) {
2505            packet.setId(CryptoHelper.random(9));
2506        }
2507        if (callback != null) {
2508            synchronized (this.packetCallbacks) {
2509                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2510            }
2511        }
2512        this.sendPacket(packet, force);
2513        return packet.getId();
2514    }
2515
2516    public void sendMessagePacket(final im.conversations.android.xmpp.model.stanza.Message packet) {
2517        this.sendPacket(packet);
2518    }
2519
2520    public void sendPresencePacket(final Presence packet) {
2521        this.sendPacket(packet);
2522    }
2523
2524    private synchronized void sendPacket(final StreamElement packet) {
2525        sendPacket(packet, false);
2526    }
2527
2528    private synchronized void sendPacket(final StreamElement packet, final boolean force) {
2529        if (stanzasSent == Integer.MAX_VALUE) {
2530            resetStreamId();
2531            disconnect(true);
2532            return;
2533        }
2534        synchronized (this.mStanzaQueue) {
2535            if (force || isBound) {
2536                tagWriter.writeStanzaAsync(packet);
2537            } else {
2538                Log.d(
2539                        Config.LOGTAG,
2540                        account.getJid().asBareJid()
2541                                + " do not write stanza to unbound stream "
2542                                + packet.toString());
2543            }
2544            if (packet instanceof Stanza stanza) {
2545                if (this.mStanzaQueue.size() != 0) {
2546                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2547                    if (currentHighestKey != stanzasSent) {
2548                        throw new AssertionError("Stanza count messed up");
2549                    }
2550                }
2551
2552                ++stanzasSent;
2553                if (Config.EXTENDED_SM_LOGGING) {
2554                    Log.d(
2555                            Config.LOGTAG,
2556                            account.getJid().asBareJid()
2557                                    + ": counting outbound "
2558                                    + packet.getName()
2559                                    + " as #"
2560                                    + stanzasSent);
2561                }
2562                this.mStanzaQueue.append(stanzasSent, stanza);
2563                if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message
2564                        && stanza.getId() != null
2565                        && inSmacksSession) {
2566                    if (Config.EXTENDED_SM_LOGGING) {
2567                        Log.d(
2568                                Config.LOGTAG,
2569                                account.getJid().asBareJid()
2570                                        + ": requesting ack for message stanza #"
2571                                        + stanzasSent);
2572                    }
2573                    tagWriter.writeStanzaAsync(new Request());
2574                }
2575            }
2576        }
2577    }
2578
2579    public void sendPing() {
2580        if (!r()) {
2581            final Iq iq = new Iq(Iq.Type.GET);
2582            iq.setFrom(account.getJid());
2583            iq.addChild("ping", Namespace.PING);
2584            this.sendIqPacket(iq, null);
2585        }
2586        this.lastPingSent = SystemClock.elapsedRealtime();
2587    }
2588
2589    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2590        this.jingleListener = listener;
2591    }
2592
2593    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2594        this.statusListener = listener;
2595    }
2596
2597    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2598        this.acknowledgedListener = listener;
2599    }
2600
2601    public void addOnAdvancedStreamFeaturesAvailableListener(
2602            final OnAdvancedStreamFeaturesLoaded listener) {
2603        this.advancedStreamFeaturesLoadedListeners.add(listener);
2604    }
2605
2606    private void forceCloseSocket() {
2607        FileBackend.close(this.socket);
2608        FileBackend.close(this.tagReader);
2609    }
2610
2611    public void interrupt() {
2612        if (this.mThread != null) {
2613            this.mThread.interrupt();
2614        }
2615    }
2616
2617    public void disconnect(final boolean force) {
2618        interrupt();
2619        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2620        if (force) {
2621            forceCloseSocket();
2622        } else {
2623            final TagWriter currentTagWriter = this.tagWriter;
2624            if (currentTagWriter.isActive()) {
2625                currentTagWriter.finish();
2626                final Socket currentSocket = this.socket;
2627                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2628                try {
2629                    currentTagWriter.await(1, TimeUnit.SECONDS);
2630                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2631                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2632                    if (streamCountDownLatch != null) {
2633                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2634                            Log.d(
2635                                    Config.LOGTAG,
2636                                    account.getJid().asBareJid() + ": remote ended stream");
2637                        } else {
2638                            Log.d(
2639                                    Config.LOGTAG,
2640                                    account.getJid().asBareJid()
2641                                            + ": remote has not closed socket. force closing");
2642                        }
2643                    }
2644                } catch (InterruptedException e) {
2645                    Log.d(
2646                            Config.LOGTAG,
2647                            account.getJid().asBareJid()
2648                                    + ": interrupted while gracefully closing stream");
2649                } catch (final IOException e) {
2650                    Log.d(
2651                            Config.LOGTAG,
2652                            account.getJid().asBareJid()
2653                                    + ": io exception during disconnect ("
2654                                    + e.getMessage()
2655                                    + ")");
2656                } finally {
2657                    FileBackend.close(currentSocket);
2658                }
2659            } else {
2660                forceCloseSocket();
2661            }
2662        }
2663    }
2664
2665    private void resetStreamId() {
2666        this.pendingResumeId.clear();
2667        this.streamId = null;
2668        this.boundStreamFeatures = null;
2669    }
2670
2671    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2672        synchronized (this.disco) {
2673            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2674            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2675                if (cursor.getValue().getFeatures().contains(feature)) {
2676                    items.add(cursor);
2677                }
2678            }
2679            return items;
2680        }
2681    }
2682
2683    public Jid findDiscoItemByFeature(final String feature) {
2684        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2685        if (items.size() >= 1) {
2686            return items.get(0).getKey();
2687        }
2688        return null;
2689    }
2690
2691    public boolean r() {
2692        if (getFeatures().sm()) {
2693            this.tagWriter.writeStanzaAsync(new Request());
2694            return true;
2695        } else {
2696            return false;
2697        }
2698    }
2699
2700    public List<String> getMucServersWithholdAccount() {
2701        final List<String> servers = getMucServers();
2702        servers.remove(account.getDomain().toEscapedString());
2703        return servers;
2704    }
2705
2706    public List<String> getMucServers() {
2707        List<String> servers = new ArrayList<>();
2708        synchronized (this.disco) {
2709            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2710                final ServiceDiscoveryResult value = cursor.getValue();
2711                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2712                        && value.hasIdentity("conference", "text")
2713                        && !value.getFeatures().contains("jabber:iq:gateway")
2714                        && !value.hasIdentity("conference", "irc")) {
2715                    servers.add(cursor.getKey().toString());
2716                }
2717            }
2718        }
2719        return servers;
2720    }
2721
2722    public String getMucServer() {
2723        List<String> servers = getMucServers();
2724        return servers.size() > 0 ? servers.get(0) : null;
2725    }
2726
2727    public int getTimeToNextAttempt(final boolean aggressive) {
2728        final int interval;
2729        if (aggressive) {
2730            interval = Math.min((int) (3 * Math.pow(1.3, attempt)), 60);
2731        } else {
2732            final int additionalTime =
2733                    account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2734            interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2735        }
2736        final int secondsSinceLast =
2737                (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2738        return interval - secondsSinceLast;
2739    }
2740
2741    public int getAttempt() {
2742        return this.attempt;
2743    }
2744
2745    public Features getFeatures() {
2746        return this.features;
2747    }
2748
2749    public long getLastSessionEstablished() {
2750        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2751        return System.currentTimeMillis() - diff;
2752    }
2753
2754    public long getLastConnect() {
2755        return this.lastConnect;
2756    }
2757
2758    public long getLastPingSent() {
2759        return this.lastPingSent;
2760    }
2761
2762    public long getLastDiscoStarted() {
2763        return this.lastDiscoStarted;
2764    }
2765
2766    public long getLastPacketReceived() {
2767        return this.lastPacketReceived;
2768    }
2769
2770    public void sendActive() {
2771        this.sendPacket(new Active());
2772    }
2773
2774    public void sendInactive() {
2775        this.sendPacket(new Inactive());
2776    }
2777
2778    public void resetAttemptCount(boolean resetConnectTime) {
2779        this.attempt = 0;
2780        if (resetConnectTime) {
2781            this.lastConnect = 0;
2782        }
2783    }
2784
2785    public void setInteractive(boolean interactive) {
2786        this.mInteractive = interactive;
2787    }
2788
2789    private IqGenerator getIqGenerator() {
2790        return mXmppConnectionService.getIqGenerator();
2791    }
2792
2793    public void trackOfflineMessageRetrieval(boolean trackOfflineMessageRetrieval) {
2794        if (trackOfflineMessageRetrieval) {
2795            final Iq iqPing = new Iq(Iq.Type.GET);
2796            iqPing.addChild("ping", Namespace.PING);
2797            this.sendIqPacket(
2798                    iqPing,
2799                    (response) -> {
2800                        Log.d(
2801                                Config.LOGTAG,
2802                                account.getJid().asBareJid()
2803                                        + ": got ping response after sending initial presence");
2804                        XmppConnection.this.offlineMessagesRetrieved = true;
2805                    });
2806        } else {
2807            this.offlineMessagesRetrieved = true;
2808        }
2809    }
2810
2811    public boolean isOfflineMessagesRetrieved() {
2812        return this.offlineMessagesRetrieved;
2813    }
2814
2815    public void fetchRoster() {
2816        final Iq iqPacket = new Iq(Iq.Type.GET);
2817        final var version = account.getRosterVersion();
2818        if (Strings.isNullOrEmpty(account.getRosterVersion())) {
2819            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
2820        } else {
2821            Log.d(
2822                    Config.LOGTAG,
2823                    account.getJid().asBareJid() + ": fetching roster version " + version);
2824        }
2825        iqPacket.query(Namespace.ROSTER).setAttribute("ver", version);
2826        sendIqPacket(iqPacket, unregisteredIqListener);
2827    }
2828
2829    private class MyKeyManager implements X509KeyManager {
2830        @Override
2831        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2832            return account.getPrivateKeyAlias();
2833        }
2834
2835        @Override
2836        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2837            return null;
2838        }
2839
2840        @Override
2841        public X509Certificate[] getCertificateChain(String alias) {
2842            Log.d(Config.LOGTAG, "getting certificate chain");
2843            try {
2844                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2845            } catch (final Exception e) {
2846                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2847                return new X509Certificate[0];
2848            }
2849        }
2850
2851        @Override
2852        public String[] getClientAliases(String s, Principal[] principals) {
2853            final String alias = account.getPrivateKeyAlias();
2854            return alias != null ? new String[] {alias} : new String[0];
2855        }
2856
2857        @Override
2858        public String[] getServerAliases(String s, Principal[] principals) {
2859            return new String[0];
2860        }
2861
2862        @Override
2863        public PrivateKey getPrivateKey(String alias) {
2864            try {
2865                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2866            } catch (Exception e) {
2867                return null;
2868            }
2869        }
2870    }
2871
2872    private static class LoginInfo {
2873        public final SaslMechanism saslMechanism;
2874        public final SaslMechanism.Version saslVersion;
2875        public final List<String> inlineBindFeatures;
2876        public final AtomicBoolean success = new AtomicBoolean(false);
2877
2878        private LoginInfo(
2879                final SaslMechanism saslMechanism,
2880                final SaslMechanism.Version saslVersion,
2881                final Collection<String> inlineBindFeatures) {
2882            Preconditions.checkNotNull(saslMechanism, "SASL Mechanism must not be null");
2883            Preconditions.checkNotNull(saslVersion, "SASL version must not be null");
2884            this.saslMechanism = saslMechanism;
2885            this.saslVersion = saslVersion;
2886            this.inlineBindFeatures =
2887                    inlineBindFeatures == null
2888                            ? Collections.emptyList()
2889                            : ImmutableList.copyOf(inlineBindFeatures);
2890        }
2891
2892        public static SaslMechanism mechanism(final LoginInfo loginInfo) {
2893            return loginInfo == null ? null : loginInfo.saslMechanism;
2894        }
2895
2896        public void success(final String challenge, final SSLSocket sslSocket)
2897                throws SaslMechanism.AuthenticationException {
2898            final var response = this.saslMechanism.getResponse(challenge, sslSocket);
2899            if (!Strings.isNullOrEmpty(response)) {
2900                throw new SaslMechanism.AuthenticationException(
2901                        "processing success yielded another response");
2902            }
2903            if (this.success.compareAndSet(false, true)) {
2904                return;
2905            }
2906            throw new SaslMechanism.AuthenticationException("Process 'success' twice");
2907        }
2908
2909        public static boolean isSuccess(final LoginInfo loginInfo) {
2910            return loginInfo != null && loginInfo.success.get();
2911        }
2912    }
2913
2914    private static class StreamId {
2915        public final String id;
2916        public final Resolver.Result location;
2917
2918        private StreamId(String id, Resolver.Result location) {
2919            this.id = id;
2920            this.location = location;
2921        }
2922
2923        @NonNull
2924        @Override
2925        public String toString() {
2926            return MoreObjects.toStringHelper(this)
2927                    .add("id", id)
2928                    .add("location", location)
2929                    .toString();
2930        }
2931    }
2932
2933    private static class StateChangingError extends Error {
2934        private final Account.State state;
2935
2936        public StateChangingError(Account.State state) {
2937            this.state = state;
2938        }
2939    }
2940
2941    private static class StateChangingException extends IOException {
2942        private final Account.State state;
2943
2944        public StateChangingException(Account.State state) {
2945            this.state = state;
2946        }
2947    }
2948
2949    public class Features {
2950        XmppConnection connection;
2951        private boolean carbonsEnabled = false;
2952        private boolean encryptionEnabled = false;
2953        private boolean blockListRequested = false;
2954
2955        public Features(final XmppConnection connection) {
2956            this.connection = connection;
2957        }
2958
2959        private boolean hasDiscoFeature(final Jid server, final String feature) {
2960            synchronized (XmppConnection.this.disco) {
2961                final ServiceDiscoveryResult sdr = connection.disco.get(server);
2962                return sdr != null && sdr.getFeatures().contains(feature);
2963            }
2964        }
2965
2966        public boolean carbons() {
2967            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2968        }
2969
2970        public boolean commands() {
2971            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2972        }
2973
2974        public boolean easyOnboardingInvites() {
2975            synchronized (commands) {
2976                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2977            }
2978        }
2979
2980        public boolean bookmarksConversion() {
2981            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2982                    && pepPublishOptions();
2983        }
2984
2985        public boolean blocking() {
2986            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2987        }
2988
2989        public boolean spamReporting() {
2990            return hasDiscoFeature(account.getDomain(), Namespace.REPORTING);
2991        }
2992
2993        public boolean flexibleOfflineMessageRetrieval() {
2994            return hasDiscoFeature(
2995                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2996        }
2997
2998        public boolean register() {
2999            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
3000        }
3001
3002        public boolean invite() {
3003            return connection.streamFeatures != null
3004                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
3005        }
3006
3007        public boolean sm() {
3008            return streamId != null
3009                    || (connection.streamFeatures != null
3010                            && connection.streamFeatures.streamManagement());
3011        }
3012
3013        public boolean csi() {
3014            return connection.streamFeatures != null
3015                    && connection.streamFeatures.clientStateIndication();
3016        }
3017
3018        public boolean pep() {
3019            synchronized (XmppConnection.this.disco) {
3020                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
3021                return info != null && info.hasIdentity("pubsub", "pep");
3022            }
3023        }
3024
3025        public boolean pepPersistent() {
3026            synchronized (XmppConnection.this.disco) {
3027                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
3028                return info != null
3029                        && info.getFeatures()
3030                                .contains("http://jabber.org/protocol/pubsub#persistent-items");
3031            }
3032        }
3033
3034        public boolean bind2() {
3035            final var loginInfo = XmppConnection.this.loginInfo;
3036            return loginInfo != null && !loginInfo.inlineBindFeatures.isEmpty();
3037        }
3038
3039        public boolean sasl2() {
3040            final var loginInfo = XmppConnection.this.loginInfo;
3041            return loginInfo != null && loginInfo.saslVersion == SaslMechanism.Version.SASL_2;
3042        }
3043
3044        public String loginMechanism() {
3045            final var loginInfo = XmppConnection.this.loginInfo;
3046            return loginInfo == null ? null : loginInfo.saslMechanism.getMechanism();
3047        }
3048
3049        public boolean pepPublishOptions() {
3050            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
3051        }
3052
3053        public boolean pepConfigNodeMax() {
3054            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_CONFIG_NODE_MAX);
3055        }
3056
3057        public boolean pepOmemoWhitelisted() {
3058            return hasDiscoFeature(
3059                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
3060        }
3061
3062        public boolean mam() {
3063            return MessageArchiveService.Version.has(getAccountFeatures());
3064        }
3065
3066        public List<String> getAccountFeatures() {
3067            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
3068            return result == null ? Collections.emptyList() : result.getFeatures();
3069        }
3070
3071        public boolean push() {
3072            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
3073                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
3074        }
3075
3076        public boolean rosterVersioning() {
3077            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
3078        }
3079
3080        public void setBlockListRequested(boolean value) {
3081            this.blockListRequested = value;
3082        }
3083
3084        public boolean httpUpload(long filesize) {
3085            if (Config.DISABLE_HTTP_UPLOAD) {
3086                return false;
3087            } else {
3088                for (String namespace :
3089                        new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3090                    List<Entry<Jid, ServiceDiscoveryResult>> items =
3091                            findDiscoItemsByFeature(namespace);
3092                    if (items.size() > 0) {
3093                        try {
3094                            long maxsize =
3095                                    Long.parseLong(
3096                                            items.get(0)
3097                                                    .getValue()
3098                                                    .getExtendedDiscoInformation(
3099                                                            namespace, "max-file-size"));
3100                            if (filesize <= maxsize) {
3101                                return true;
3102                            } else {
3103                                Log.d(
3104                                        Config.LOGTAG,
3105                                        account.getJid().asBareJid()
3106                                                + ": http upload is not available for files with"
3107                                                + " size "
3108                                                + filesize
3109                                                + " (max is "
3110                                                + maxsize
3111                                                + ")");
3112                                return false;
3113                            }
3114                        } catch (Exception e) {
3115                            return true;
3116                        }
3117                    }
3118                }
3119                return false;
3120            }
3121        }
3122
3123        public boolean useLegacyHttpUpload() {
3124            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
3125                    && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
3126        }
3127
3128        public long getMaxHttpUploadSize() {
3129            for (String namespace :
3130                    new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3131                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
3132                if (items.size() > 0) {
3133                    try {
3134                        return Long.parseLong(
3135                                items.get(0)
3136                                        .getValue()
3137                                        .getExtendedDiscoInformation(namespace, "max-file-size"));
3138                    } catch (Exception e) {
3139                        // ignored
3140                    }
3141                }
3142            }
3143            return -1;
3144        }
3145
3146        public boolean stanzaIds() {
3147            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
3148        }
3149
3150        public boolean bookmarks2() {
3151            return pepPublishOptions()
3152                    && pepConfigNodeMax()
3153                    && hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT);
3154        }
3155
3156        public boolean externalServiceDiscovery() {
3157            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
3158        }
3159
3160        public boolean mds() {
3161            return pepPublishOptions()
3162                    && pepConfigNodeMax()
3163                    && Config.MESSAGE_DISPLAYED_SYNCHRONIZATION;
3164        }
3165
3166        public boolean mdsServerAssist() {
3167            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.MDS_DISPLAYED);
3168        }
3169    }
3170}