XmppConnection.java

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