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