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