XmppConnection.java

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