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