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