XmppConnection.java

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