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.DiscoManager;
  76import im.conversations.android.xmpp.Entity;
  77import im.conversations.android.xmpp.model.AuthenticationFailure;
  78import im.conversations.android.xmpp.model.AuthenticationRequest;
  79import im.conversations.android.xmpp.model.AuthenticationStreamFeature;
  80import im.conversations.android.xmpp.model.Extension;
  81import im.conversations.android.xmpp.model.StreamElement;
  82import im.conversations.android.xmpp.model.bind2.Bind;
  83import im.conversations.android.xmpp.model.bind2.Bound;
  84import im.conversations.android.xmpp.model.cb.SaslChannelBinding;
  85import im.conversations.android.xmpp.model.csi.Active;
  86import im.conversations.android.xmpp.model.csi.Inactive;
  87import im.conversations.android.xmpp.model.disco.info.InfoQuery;
  88import im.conversations.android.xmpp.model.error.Condition;
  89import im.conversations.android.xmpp.model.fast.Fast;
  90import im.conversations.android.xmpp.model.fast.RequestToken;
  91import im.conversations.android.xmpp.model.jingle.Jingle;
  92import im.conversations.android.xmpp.model.sasl.Auth;
  93import im.conversations.android.xmpp.model.sasl.Failure;
  94import im.conversations.android.xmpp.model.sasl.Mechanisms;
  95import im.conversations.android.xmpp.model.sasl.Response;
  96import im.conversations.android.xmpp.model.sasl.SaslError;
  97import im.conversations.android.xmpp.model.sasl.Success;
  98import im.conversations.android.xmpp.model.sasl2.Authenticate;
  99import im.conversations.android.xmpp.model.sasl2.Authentication;
 100import im.conversations.android.xmpp.model.sasl2.UserAgent;
 101import im.conversations.android.xmpp.model.sm.Ack;
 102import im.conversations.android.xmpp.model.sm.Enable;
 103import im.conversations.android.xmpp.model.sm.Enabled;
 104import im.conversations.android.xmpp.model.sm.Failed;
 105import im.conversations.android.xmpp.model.sm.Request;
 106import im.conversations.android.xmpp.model.sm.Resume;
 107import im.conversations.android.xmpp.model.sm.Resumed;
 108import im.conversations.android.xmpp.model.sm.StreamManagement;
 109import im.conversations.android.xmpp.model.stanza.Iq;
 110import im.conversations.android.xmpp.model.stanza.Presence;
 111import im.conversations.android.xmpp.model.stanza.Stanza;
 112import im.conversations.android.xmpp.model.streams.StreamError;
 113import im.conversations.android.xmpp.model.tls.Proceed;
 114import im.conversations.android.xmpp.model.tls.StartTls;
 115import im.conversations.android.xmpp.processor.BindProcessor;
 116import java.io.ByteArrayInputStream;
 117import java.io.IOException;
 118import java.io.InputStream;
 119import java.net.ConnectException;
 120import java.net.IDN;
 121import java.net.InetAddress;
 122import java.net.InetSocketAddress;
 123import java.net.Socket;
 124import java.net.UnknownHostException;
 125import java.security.KeyManagementException;
 126import java.security.NoSuchAlgorithmException;
 127import java.security.Principal;
 128import java.security.PrivateKey;
 129import java.security.cert.X509Certificate;
 130import java.util.ArrayList;
 131import java.util.Arrays;
 132import java.util.Collection;
 133import java.util.Collections;
 134import java.util.HashMap;
 135import java.util.HashSet;
 136import java.util.Hashtable;
 137import java.util.Iterator;
 138import java.util.List;
 139import java.util.Map;
 140import java.util.Map.Entry;
 141import java.util.Set;
 142import java.util.concurrent.CountDownLatch;
 143import java.util.concurrent.TimeUnit;
 144import java.util.concurrent.TimeoutException;
 145import java.util.concurrent.atomic.AtomicBoolean;
 146import java.util.concurrent.atomic.AtomicInteger;
 147import java.util.function.Consumer;
 148import java.util.regex.Matcher;
 149import javax.net.ssl.KeyManager;
 150import javax.net.ssl.SSLContext;
 151import javax.net.ssl.SSLPeerUnverifiedException;
 152import javax.net.ssl.SSLSocket;
 153import javax.net.ssl.SSLSocketFactory;
 154import javax.net.ssl.X509KeyManager;
 155import javax.net.ssl.X509TrustManager;
 156import okhttp3.HttpUrl;
 157import org.xmlpull.v1.XmlPullParserException;
 158
 159public class XmppConnection implements Runnable {
 160
 161    protected final Account account;
 162    private final Features features = new Features(this);
 163    private final HashMap<String, Jid> commands = new HashMap<>();
 164    private final SparseArray<Stanza> mStanzaQueue = new SparseArray<>();
 165    private final Hashtable<String, Pair<Iq, Consumer<Iq>>> packetCallbacks = new Hashtable<>();
 166    private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners =
 167            new HashSet<>();
 168    private final AppSettings appSettings;
 169    private final XmppConnectionService mXmppConnectionService;
 170    private Socket socket;
 171    private XmlReader tagReader;
 172    private TagWriter tagWriter = new TagWriter();
 173    private boolean shouldAuthenticate = true;
 174    private boolean inSmacksSession = false;
 175    private boolean quickStartInProgress = false;
 176    private boolean isBound = false;
 177    private boolean offlineMessagesRetrieved = false;
 178    private im.conversations.android.xmpp.model.streams.Features streamFeatures;
 179    private im.conversations.android.xmpp.model.streams.Features boundStreamFeatures;
 180    private StreamId streamId = null;
 181    private int stanzasReceived = 0;
 182    private int stanzasSent = 0;
 183    private int stanzasSentBeforeAuthentication;
 184    private long lastPacketReceived = 0;
 185    private long lastPingSent = 0;
 186    private long lastConnectionStarted = 0;
 187    private long lastSessionStarted = 0;
 188    private long lastDiscoStarted = 0;
 189    private boolean isMamPreferenceAlways = false;
 190    private final AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 191    private final AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 192    private final AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 193    private boolean mInteractive = false;
 194    private int attempt = 0;
 195    private OnJinglePacketReceived jingleListener = null;
 196
 197    private final Consumer<Presence> presenceListener;
 198    private final Consumer<Iq> unregisteredIqListener;
 199    private final Consumer<im.conversations.android.xmpp.model.stanza.Message> messageListener;
 200    private OnStatusChanged statusListener = null;
 201    private final Runnable bindListener;
 202    private OnMessageAcknowledged acknowledgedListener = null;
 203    private final PendingItem<String> pendingResumeId = new PendingItem<>();
 204    private LoginInfo loginInfo;
 205    private HashedToken.Mechanism hashTokenRequest;
 206    private HttpUrl redirectionUrl = null;
 207    private String verifiedHostname = null;
 208    private Resolver.Result currentResolverResult;
 209    private Resolver.Result seeOtherHostResolverResult;
 210    private volatile Thread mThread;
 211    private CountDownLatch mStreamCountDownLatch;
 212    private final ClassToInstanceMap<AbstractManager> managers;
 213
 214    public XmppConnection(final Account account, final XmppConnectionService service) {
 215        this.account = account;
 216        this.mXmppConnectionService = service;
 217        this.appSettings = mXmppConnectionService.getAppSettings();
 218        this.presenceListener = new PresenceParser(service, this);
 219        // TODO rename this to Iq request handler (it handles only IQ get and set; throw assert
 220        // error in handler just to be safe)
 221        // TODO requires roster and blocking not to be handled by this
 222        this.unregisteredIqListener = new IqParser(service, this);
 223        this.messageListener = new MessageParser(service, this);
 224        this.bindListener = new BindProcessor(service, this);
 225        this.managers = Managers.get(service.getApplicationContext(), this);
 226    }
 227
 228    private static void fixResource(final Context context, final Account account) {
 229        String resource = account.getResource();
 230        int fixedPartLength =
 231                context.getString(R.string.app_name).length() + 1; // include the trailing dot
 232        int randomPartLength = 4; // 3 bytes
 233        if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
 234            if (validBase64(
 235                    resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
 236                account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
 237            }
 238        }
 239    }
 240
 241    private static boolean validBase64(final String input) {
 242        try {
 243            return Base64.decode(input, Base64.URL_SAFE).length == 3;
 244        } catch (final Throwable throwable) {
 245            return false;
 246        }
 247    }
 248
 249    private void changeStatus(final Account.State nextStatus) {
 250        synchronized (this) {
 251            if (Thread.currentThread().isInterrupted()) {
 252                Log.d(
 253                        Config.LOGTAG,
 254                        account.getJid().asBareJid()
 255                                + ": not changing status to "
 256                                + nextStatus
 257                                + " because thread was interrupted");
 258                return;
 259            }
 260            if (account.getStatus() != nextStatus) {
 261                if (nextStatus == Account.State.OFFLINE
 262                        && account.getStatus() != Account.State.CONNECTING
 263                        && account.getStatus() != Account.State.ONLINE
 264                        && account.getStatus() != Account.State.DISABLED
 265                        && account.getStatus() != Account.State.LOGGED_OUT) {
 266                    return;
 267                }
 268                if (nextStatus == Account.State.ONLINE) {
 269                    this.attempt = 0;
 270                }
 271                account.setStatus(nextStatus);
 272            } else {
 273                return;
 274            }
 275        }
 276        if (statusListener != null) {
 277            statusListener.onStatusChanged(account);
 278        }
 279    }
 280
 281    public Jid getJidForCommand(final String node) {
 282        synchronized (this.commands) {
 283            return this.commands.get(node);
 284        }
 285    }
 286
 287    public void prepareNewConnection() {
 288        this.lastConnectionStarted = SystemClock.elapsedRealtime();
 289        this.lastPingSent = SystemClock.elapsedRealtime();
 290        this.lastDiscoStarted = Long.MAX_VALUE;
 291        this.mWaitingForSmCatchup.set(false);
 292        this.changeStatus(Account.State.CONNECTING);
 293    }
 294
 295    public boolean isWaitingForSmCatchup() {
 296        return mWaitingForSmCatchup.get();
 297    }
 298
 299    public void incrementSmCatchupMessageCounter() {
 300        this.mSmCatchupMessageCounter.incrementAndGet();
 301    }
 302
 303    protected void connect() {
 304        if (mXmppConnectionService.areMessagesInitialized()) {
 305            mXmppConnectionService.resetSendingToWaiting(account);
 306        }
 307        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
 308        this.streamFeatures = null;
 309        this.pendingResumeId.clear();
 310        this.loginInfo = null;
 311        this.features.encryptionEnabled = false;
 312        this.inSmacksSession = false;
 313        this.quickStartInProgress = false;
 314        this.isBound = false;
 315        this.attempt++;
 316        this.currentResolverResult = null;
 317        // will be set if user entered hostname is being used or hostname was verified with dnssec
 318        this.verifiedHostname = null;
 319        try {
 320            Socket localSocket;
 321            shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
 322            this.changeStatus(Account.State.CONNECTING);
 323            final boolean useTorSetting = appSettings.isUseTor();
 324            final boolean extended = appSettings.isExtendedConnectionOptions();
 325            final boolean useTor = useTorSetting || account.isOnion();
 326            // TODO collapse Tor usage into normal connection code path
 327            if (useTor) {
 328                final var seeOtherHost = this.seeOtherHostResolverResult;
 329                final var hostname = account.getHostname().trim();
 330                final var port = account.getPort();
 331                final Resolver.Result resume = streamId == null ? null : streamId.location;
 332                final Resolver.Result viaTor;
 333                if (resume != null) {
 334                    viaTor = resume;
 335                } else if (seeOtherHost != null) {
 336                    viaTor = seeOtherHost;
 337                } else if (hostname.isEmpty() || port < 0) {
 338                    viaTor =
 339                            Iterables.getOnlyElement(
 340                                    Resolver.fromHardCoded(
 341                                            account.getServer(), Resolver.XMPP_PORT_STARTTLS));
 342                } else {
 343                    if (useTorSetting || extended) {
 344                        // if the hostname configuration is showing we can take it
 345                        viaTor = Iterables.getOnlyElement(Resolver.fromHardCoded(hostname, port));
 346                    } else {
 347                        viaTor =
 348                                Iterables.getOnlyElement(
 349                                        Resolver.fromHardCoded(
 350                                                account.getServer(), Resolver.XMPP_PORT_STARTTLS));
 351                    }
 352                    this.verifiedHostname = hostname;
 353                }
 354
 355                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " via Tor: " + viaTor);
 356
 357                localSocket =
 358                        SocksSocketFactory.createSocketOverTor(
 359                                viaTor.asDestination(), viaTor.getPort());
 360
 361                if (viaTor.isDirectTls()) {
 362                    localSocket = upgradeSocketToTls(localSocket);
 363                    features.encryptionEnabled = true;
 364                }
 365
 366                try {
 367                    if (startXmpp(localSocket)) {
 368                        this.currentResolverResult = viaTor;
 369                        this.seeOtherHostResolverResult = null;
 370                    }
 371                } catch (final InterruptedException e) {
 372                    Log.d(
 373                            Config.LOGTAG,
 374                            account.getJid().asBareJid()
 375                                    + ": thread was interrupted before beginning stream");
 376                    return;
 377                } catch (final Exception e) {
 378                    throw new IOException("Could not start stream", e);
 379                }
 380            } else {
 381                final var hostname = account.getHostname().trim();
 382                final String domain = account.getServer();
 383                final List<Resolver.Result> results = new ArrayList<>();
 384                final boolean hardcoded = extended && !hostname.isEmpty();
 385                if (hardcoded) {
 386                    results.addAll(Resolver.fromHardCoded(hostname, account.getPort()));
 387                } else {
 388                    results.addAll(Resolver.resolve(domain));
 389                }
 390                if (Thread.currentThread().isInterrupted()) {
 391                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 392                    return;
 393                }
 394                if (results.isEmpty()) {
 395                    Log.e(
 396                            Config.LOGTAG,
 397                            account.getJid().asBareJid() + ": Resolver results were empty");
 398                    return;
 399                }
 400                final Resolver.Result storedBackupResult;
 401                if (hardcoded) {
 402                    storedBackupResult = null;
 403                } else {
 404                    storedBackupResult =
 405                            mXmppConnectionService.databaseBackend.findResolverResult(domain);
 406                    if (storedBackupResult != null && !results.contains(storedBackupResult)) {
 407                        results.add(storedBackupResult);
 408                        Log.d(
 409                                Config.LOGTAG,
 410                                account.getJid().asBareJid()
 411                                        + ": loaded backup resolver result from db: "
 412                                        + storedBackupResult);
 413                    }
 414                }
 415                final StreamId streamId = this.streamId;
 416                final Resolver.Result resumeLocation = streamId == null ? null : streamId.location;
 417                if (resumeLocation != null) {
 418                    Log.d(
 419                            Config.LOGTAG,
 420                            account.getJid().asBareJid()
 421                                    + ": injected resume location on position 0");
 422                    results.add(0, resumeLocation);
 423                }
 424                final Resolver.Result seeOtherHost = this.seeOtherHostResolverResult;
 425                if (seeOtherHost != null) {
 426                    Log.d(
 427                            Config.LOGTAG,
 428                            account.getJid().asBareJid()
 429                                    + ": injected see-other-host on position 0");
 430                    results.add(0, seeOtherHost);
 431                }
 432                for (final Iterator<Resolver.Result> iterator = results.iterator();
 433                        iterator.hasNext(); ) {
 434                    final Resolver.Result result = iterator.next();
 435                    if (Thread.currentThread().isInterrupted()) {
 436                        Log.d(
 437                                Config.LOGTAG,
 438                                account.getJid().asBareJid() + ": Thread was interrupted");
 439                        return;
 440                    }
 441                    try {
 442                        // if tls is true, encryption is implied and must not be started
 443                        features.encryptionEnabled = result.isDirectTls();
 444                        verifiedHostname =
 445                                result.isAuthenticated() ? result.getHostname().toString() : null;
 446                        final InetSocketAddress addr;
 447                        if (result.getIp() != null) {
 448                            addr = new InetSocketAddress(result.getIp(), result.getPort());
 449                            Log.d(
 450                                    Config.LOGTAG,
 451                                    account.getJid().asBareJid().toString()
 452                                            + ": using values from resolver "
 453                                            + (result.getHostname() == null
 454                                                    ? ""
 455                                                    : result.getHostname().toString() + "/")
 456                                            + result.getIp().getHostAddress()
 457                                            + ":"
 458                                            + result.getPort()
 459                                            + " tls: "
 460                                            + features.encryptionEnabled);
 461                        } else {
 462                            addr =
 463                                    new InetSocketAddress(
 464                                            IDN.toASCII(result.getHostname().toString()),
 465                                            result.getPort());
 466                            Log.d(
 467                                    Config.LOGTAG,
 468                                    account.getJid().asBareJid().toString()
 469                                            + ": using values from resolver "
 470                                            + result.getHostname().toString()
 471                                            + ":"
 472                                            + result.getPort()
 473                                            + " tls: "
 474                                            + features.encryptionEnabled);
 475                        }
 476
 477                        localSocket = new Socket();
 478                        localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 479                        localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
 480                        if (features.encryptionEnabled) {
 481                            localSocket = upgradeSocketToTls(localSocket);
 482                        }
 483                        if (startXmpp(localSocket)) {
 484                            // reset to 0; once the connection is established we don't want this
 485                            localSocket.setSoTimeout(0);
 486                            if (!hardcoded && !result.equals(storedBackupResult)) {
 487                                mXmppConnectionService.databaseBackend.saveResolverResult(
 488                                        domain, result);
 489                            }
 490                            this.currentResolverResult = result;
 491                            this.seeOtherHostResolverResult = null;
 492                            break; // successfully connected to server that speaks xmpp
 493                        } else {
 494                            FileBackend.close(localSocket);
 495                            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 496                        }
 497                    } catch (final StateChangingException e) {
 498                        if (!iterator.hasNext()) {
 499                            throw e;
 500                        }
 501                    } catch (InterruptedException e) {
 502                        Log.d(
 503                                Config.LOGTAG,
 504                                account.getJid().asBareJid()
 505                                        + ": thread was interrupted before beginning stream");
 506                        return;
 507                    } catch (final Throwable e) {
 508                        Log.d(
 509                                Config.LOGTAG,
 510                                account.getJid().asBareJid().toString()
 511                                        + ": "
 512                                        + e.getMessage()
 513                                        + "("
 514                                        + e.getClass().getName()
 515                                        + ")");
 516                        if (!iterator.hasNext()) {
 517                            throw new UnknownHostException();
 518                        }
 519                    }
 520                }
 521            }
 522            processStream();
 523        } catch (final SecurityException e) {
 524            this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 525        } catch (final StateChangingException e) {
 526            this.changeStatus(e.state);
 527        } catch (final UnknownHostException
 528                | ConnectException
 529                | SocksSocketFactory.HostNotFoundException e) {
 530            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 531        } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 532            this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 533        } catch (final IOException | XmlPullParserException e) {
 534            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 535            this.changeStatus(Account.State.OFFLINE);
 536            this.attempt = Math.max(0, this.attempt - 1);
 537        } finally {
 538            if (!Thread.currentThread().isInterrupted()) {
 539                forceCloseSocket();
 540            } else {
 541                Log.d(
 542                        Config.LOGTAG,
 543                        account.getJid().asBareJid()
 544                                + ": not force closing socket because thread was interrupted");
 545            }
 546        }
 547    }
 548
 549    /**
 550     * Starts xmpp protocol, call after connecting to socket
 551     *
 552     * @return true if server returns with valid xmpp, false otherwise
 553     */
 554    private boolean startXmpp(final Socket socket) throws Exception {
 555        if (Thread.currentThread().isInterrupted()) {
 556            throw new InterruptedException();
 557        }
 558        // this means we have at least found a socket to connect to. give the connection another 90s
 559        this.lastConnectionStarted = SystemClock.elapsedRealtime();
 560        this.socket = socket;
 561        this.tagReader = new XmlReader();
 562        if (tagWriter != null) {
 563            tagWriter.forceClose();
 564        }
 565        this.tagWriter = new TagWriter();
 566        this.tagWriter.setOutputStream(socket.getOutputStream());
 567        this.tagReader.setInputStream(socket.getInputStream());
 568        this.tagWriter.beginDocument();
 569        final boolean quickStart;
 570        if (socket instanceof SSLSocket sslSocket) {
 571            SSLSockets.log(account, sslSocket);
 572            quickStart = establishStream(SSLSockets.version(sslSocket));
 573        } else {
 574            quickStart = establishStream(SSLSockets.Version.NONE);
 575        }
 576        final Tag tag = tagReader.readTag();
 577        if (Thread.currentThread().isInterrupted()) {
 578            throw new InterruptedException();
 579        }
 580        if (tag == null) {
 581            return false;
 582        }
 583        final boolean success = tag.isStart("stream", Namespace.STREAMS);
 584        if (success) {
 585            final var from = tag.getAttribute("from");
 586            if (from == null || !from.equals(account.getServer())) {
 587                throw new StateChangingException(Account.State.HOST_UNKNOWN);
 588            }
 589        }
 590        if (success && quickStart) {
 591            this.quickStartInProgress = true;
 592        }
 593        return success;
 594    }
 595
 596    private SSLSocketFactory getSSLSocketFactory()
 597            throws NoSuchAlgorithmException, KeyManagementException {
 598        final SSLContext sc = SSLSockets.getSSLContext();
 599        final MemorizingTrustManager trustManager =
 600                this.mXmppConnectionService.getMemorizingTrustManager();
 601        final KeyManager[] keyManager;
 602        if (account.getPrivateKeyAlias() != null) {
 603            keyManager = new KeyManager[] {new MyKeyManager()};
 604        } else {
 605            keyManager = null;
 606        }
 607        final String domain = account.getServer();
 608        sc.init(
 609                keyManager,
 610                new X509TrustManager[] {
 611                    mInteractive
 612                            ? trustManager.getInteractive(domain)
 613                            : trustManager.getNonInteractive(domain)
 614                },
 615                SECURE_RANDOM);
 616        return sc.getSocketFactory();
 617    }
 618
 619    @Override
 620    public void run() {
 621        synchronized (this) {
 622            this.mThread = Thread.currentThread();
 623            if (this.mThread.isInterrupted()) {
 624                Log.d(
 625                        Config.LOGTAG,
 626                        account.getJid().asBareJid()
 627                                + ": aborting connect because thread was interrupted");
 628                return;
 629            }
 630            forceCloseSocket();
 631        }
 632        connect();
 633    }
 634
 635    private void processStream() throws XmlPullParserException, IOException {
 636        final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 637        this.mStreamCountDownLatch = streamCountDownLatch;
 638        Tag nextTag = tagReader.readTag();
 639        while (nextTag != null && !nextTag.isEnd("stream")) {
 640            if (nextTag.isStart("error", Namespace.STREAMS)) {
 641                processStreamError(tagReader.readElement(nextTag, StreamError.class));
 642            } else if (nextTag.isStart("features", Namespace.STREAMS)) {
 643                processStreamFeatures(nextTag);
 644            } else if (nextTag.isStart("proceed", Namespace.TLS)) {
 645                if (this.socket instanceof SSLSocket) {
 646                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 647                }
 648                switchOverToTls(nextTag);
 649            } else if (nextTag.isStart("failure", Namespace.TLS)) {
 650                throw new StateChangingException(Account.State.TLS_ERROR);
 651            } else if (!isSecure()) {
 652                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 653            } else if (account.isOptionSet(Account.OPTION_REGISTER)
 654                    && nextTag.isStart("iq", Namespace.JABBER_CLIENT)) {
 655                processIq(nextTag);
 656            } else if (this.loginInfo == null) {
 657                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 658            } else if (nextTag.isStart("success", Namespace.SASL)) {
 659                processSuccess(tagReader.readElement(nextTag, Success.class));
 660                break;
 661            } else if (nextTag.isStart("success", Namespace.SASL_2)) {
 662                processSuccess(
 663                        tagReader.readElement(
 664                                nextTag, im.conversations.android.xmpp.model.sasl2.Success.class));
 665            } else if (nextTag.isStart("failure", Namespace.SASL)) {
 666                final var failure = tagReader.readElement(nextTag, Failure.class);
 667                processFailure(failure);
 668            } else if (nextTag.isStart("failure", Namespace.SASL_2)) {
 669                final var failure =
 670                        tagReader.readElement(
 671                                nextTag, im.conversations.android.xmpp.model.sasl2.Failure.class);
 672                processFailure(failure);
 673            } else if (nextTag.isStart("continue", Namespace.SASL_2)) {
 674                // two step sasl2 - we don’t support this yet
 675                throw new StateChangingException(Account.State.INCOMPATIBLE_CLIENT);
 676            } else if (nextTag.isStart("challenge")) {
 677                final Element challenge = tagReader.readElement(nextTag);
 678                processChallenge(challenge);
 679            } else if (!LoginInfo.isSuccess(this.loginInfo)) {
 680                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 681            } else if (this.streamId != null
 682                    && nextTag.isStart("resumed", Namespace.STREAM_MANAGEMENT)) {
 683                final Resumed resumed = tagReader.readElement(nextTag, Resumed.class);
 684                processResumed(resumed);
 685            } else if (nextTag.isStart("failed", Namespace.STREAM_MANAGEMENT)) {
 686                final Failed failed = tagReader.readElement(nextTag, Failed.class);
 687                processFailed(failed, true);
 688            } else if (nextTag.isStart("iq", Namespace.JABBER_CLIENT)) {
 689                processIq(nextTag);
 690            } else if (!isBound) {
 691                Log.d(
 692                        Config.LOGTAG,
 693                        account.getJid().asBareJid()
 694                                + ": server sent unexpected"
 695                                + nextTag.identifier());
 696                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 697            } else if (nextTag.isStart("message", Namespace.JABBER_CLIENT)) {
 698                processMessage(nextTag);
 699            } else if (nextTag.isStart("presence", Namespace.JABBER_CLIENT)) {
 700                processPresence(nextTag);
 701            } else if (nextTag.isStart("enabled", Namespace.STREAM_MANAGEMENT)) {
 702                final var enabled = tagReader.readElement(nextTag, Enabled.class);
 703                processEnabled(enabled);
 704            } else if (nextTag.isStart("r", Namespace.STREAM_MANAGEMENT)) {
 705                tagReader.readElement(nextTag);
 706                if (Config.EXTENDED_SM_LOGGING) {
 707                    Log.d(
 708                            Config.LOGTAG,
 709                            account.getJid().asBareJid()
 710                                    + ": acknowledging stanza #"
 711                                    + this.stanzasReceived);
 712                }
 713                final Ack ack = new Ack(this.stanzasReceived);
 714                tagWriter.writeStanzaAsync(ack);
 715            } else if (nextTag.isStart("a", Namespace.STREAM_MANAGEMENT)) {
 716                boolean accountUiNeedsRefresh = false;
 717                synchronized (NotificationService.CATCHUP_LOCK) {
 718                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 719                        final int messageCount = mSmCatchupMessageCounter.get();
 720                        final int pendingIQs = packetCallbacks.size();
 721                        Log.d(
 722                                Config.LOGTAG,
 723                                account.getJid().asBareJid()
 724                                        + ": SM catchup complete (messages="
 725                                        + messageCount
 726                                        + ", pending IQs="
 727                                        + pendingIQs
 728                                        + ")");
 729                        accountUiNeedsRefresh = true;
 730                        if (messageCount > 0) {
 731                            mXmppConnectionService
 732                                    .getNotificationService()
 733                                    .finishBacklog(true, account);
 734                        }
 735                    }
 736                }
 737                if (accountUiNeedsRefresh) {
 738                    mXmppConnectionService.updateAccountUi();
 739                }
 740                final var ack = tagReader.readElement(nextTag, Ack.class);
 741                lastPacketReceived = SystemClock.elapsedRealtime();
 742                final boolean acknowledgedMessages;
 743                synchronized (this.mStanzaQueue) {
 744                    final Optional<Integer> serverSequence = ack.getHandled();
 745                    if (serverSequence.isPresent()) {
 746                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence.get());
 747                    } else {
 748                        acknowledgedMessages = false;
 749                        Log.d(
 750                                Config.LOGTAG,
 751                                account.getJid().asBareJid()
 752                                        + ": server send ack without sequence number");
 753                    }
 754                }
 755                if (acknowledgedMessages) {
 756                    mXmppConnectionService.updateConversationUi();
 757                }
 758            } else {
 759                Log.e(
 760                        Config.LOGTAG,
 761                        account.getJid().asBareJid()
 762                                + ": Encountered unknown stream element"
 763                                + nextTag.identifier());
 764                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 765            }
 766            nextTag = tagReader.readTag();
 767        }
 768        if (nextTag != null && nextTag.isEnd("stream")) {
 769            streamCountDownLatch.countDown();
 770        }
 771    }
 772
 773    private void processChallenge(final Element challenge) throws IOException {
 774        final SaslMechanism.Version version;
 775        try {
 776            version = SaslMechanism.Version.of(challenge);
 777        } catch (final IllegalArgumentException e) {
 778            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 779        }
 780        final StreamElement response;
 781        if (version == SaslMechanism.Version.SASL) {
 782            response = new Response();
 783        } else if (version == SaslMechanism.Version.SASL_2) {
 784            response = new im.conversations.android.xmpp.model.sasl2.Response();
 785        } else {
 786            throw new AssertionError("Missing implementation for " + version);
 787        }
 788        final LoginInfo currentLoginInfo = this.loginInfo;
 789        if (currentLoginInfo == null || LoginInfo.isSuccess(currentLoginInfo)) {
 790            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 791        }
 792        try {
 793            response.setContent(
 794                    currentLoginInfo.saslMechanism.getResponse(
 795                            challenge.getContent(), sslSocketOrNull(socket)));
 796        } catch (final SaslMechanism.AuthenticationException e) {
 797            // TODO: Send auth abort tag.
 798            Log.e(Config.LOGTAG, e.toString());
 799            throw new StateChangingException(Account.State.UNAUTHORIZED);
 800        }
 801        tagWriter.writeElement(response);
 802    }
 803
 804    private void processSuccess(final StreamElement element)
 805            throws IOException, XmlPullParserException {
 806        final LoginInfo currentLoginInfo = this.loginInfo;
 807        final SaslMechanism currentSaslMechanism = LoginInfo.mechanism(currentLoginInfo);
 808        if (currentLoginInfo == null
 809                || LoginInfo.isSuccess(currentLoginInfo)
 810                || currentSaslMechanism == null) {
 811            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 812        }
 813        final SaslMechanism.Version version;
 814        final String challenge;
 815        if (element instanceof Success success) {
 816            challenge = success.getContent();
 817            version = SaslMechanism.Version.SASL;
 818        } else if (element instanceof im.conversations.android.xmpp.model.sasl2.Success success) {
 819            challenge = success.findChildContent("additional-data");
 820            version = SaslMechanism.Version.SASL_2;
 821        } else {
 822            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 823        }
 824        try {
 825            currentLoginInfo.success(challenge, sslSocketOrNull(socket));
 826        } catch (final SaslMechanism.AuthenticationException e) {
 827            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": authentication failure ", e);
 828            throw new StateChangingException(Account.State.UNAUTHORIZED);
 829        }
 830        Log.d(
 831                Config.LOGTAG,
 832                account.getJid().asBareJid().toString() + ": logged in (using " + version + ")");
 833        if (SaslMechanism.pin(currentSaslMechanism)) {
 834            account.setPinnedMechanism(currentSaslMechanism);
 835        }
 836        if (element instanceof im.conversations.android.xmpp.model.sasl2.Success success) {
 837            final var authorizationJid = success.getAuthorizationIdentifier();
 838            checkAssignedDomainOrThrow(authorizationJid);
 839            Log.d(
 840                    Config.LOGTAG,
 841                    account.getJid().asBareJid()
 842                            + ": SASL 2.0 authorization identifier was "
 843                            + authorizationJid);
 844            // TODO this should only happen when we used Bind 2
 845            if (authorizationJid.isFullJid() && account.setJid(authorizationJid)) {
 846                Log.d(
 847                        Config.LOGTAG,
 848                        account.getJid().asBareJid()
 849                                + ": jid changed during SASL 2.0. updating database");
 850            }
 851            final Bound bound = success.getExtension(Bound.class);
 852            final Resumed resumed = success.getExtension(Resumed.class);
 853            final Failed failed = success.getExtension(Failed.class);
 854            final Element tokenWrapper = success.findChild("token", Namespace.FAST);
 855            final String token = tokenWrapper == null ? null : tokenWrapper.getAttribute("token");
 856            if (bound != null && resumed != null) {
 857                Log.d(
 858                        Config.LOGTAG,
 859                        account.getJid().asBareJid()
 860                                + ": server sent bound and resumed in SASL2 success");
 861                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 862            }
 863            if (resumed != null && streamId != null) {
 864                if (this.boundStreamFeatures != null) {
 865                    this.streamFeatures = this.boundStreamFeatures;
 866                    Log.d(
 867                            Config.LOGTAG,
 868                            "putting previous stream features back in place: "
 869                                    + XmlHelper.printElementNames(this.boundStreamFeatures));
 870                }
 871                processResumed(resumed);
 872            } else if (failed != null) {
 873                processFailed(failed, false); // wait for new stream features
 874            }
 875            if (bound != null) {
 876                clearIqCallbacks();
 877                this.isBound = true;
 878                processNopStreamFeatures();
 879                this.boundStreamFeatures = this.streamFeatures;
 880                final Enabled streamManagementEnabled = bound.getExtension(Enabled.class);
 881                final Element carbonsEnabled = bound.findChild("enabled", Namespace.CARBONS);
 882                final boolean waitForDisco;
 883                if (streamManagementEnabled != null) {
 884                    resetOutboundStanzaQueue();
 885                    processEnabled(streamManagementEnabled);
 886                    waitForDisco = true;
 887                } else {
 888                    // if we did not enable stream management in bind do it now
 889                    waitForDisco = enableStreamManagement();
 890                }
 891                final boolean negotiatedCarbons;
 892                if (carbonsEnabled != null) {
 893                    negotiatedCarbons = true;
 894                    Log.d(
 895                            Config.LOGTAG,
 896                            account.getJid().asBareJid()
 897                                    + ": successfully enabled carbons (via Bind 2.0)");
 898                    features.carbonsEnabled = true;
 899                } else if (currentLoginInfo.inlineBindFeatures != null
 900                        && currentLoginInfo.inlineBindFeatures.contains(Namespace.CARBONS)) {
 901                    negotiatedCarbons = true;
 902                    Log.d(
 903                            Config.LOGTAG,
 904                            account.getJid().asBareJid()
 905                                    + ": successfully enabled carbons (via Bind 2.0/implicit)");
 906                    features.carbonsEnabled = true;
 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        features.carbonsEnabled = 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        if (getFeatures().carbons() && !features.carbonsEnabled) {
2369            sendEnableCarbons();
2370        }
2371        if (getFeatures().commands()) {
2372            discoverCommands();
2373        }
2374    }
2375
2376    private void sendEnableCarbons() {
2377        final Iq iq = new Iq(Iq.Type.SET);
2378        iq.addChild("enable", Namespace.CARBONS);
2379        this.sendIqPacket(
2380                iq,
2381                (packet) -> {
2382                    if (packet.getType() == Iq.Type.RESULT) {
2383                        Log.d(
2384                                Config.LOGTAG,
2385                                account.getJid().asBareJid() + ": successfully enabled carbons");
2386                        features.carbonsEnabled = true;
2387                    } else {
2388                        Log.d(
2389                                Config.LOGTAG,
2390                                account.getJid().asBareJid()
2391                                        + ": could not enable carbons "
2392                                        + packet);
2393                    }
2394                });
2395    }
2396
2397    private void processStreamError(final StreamError streamError) throws IOException {
2398        final var loginInfo = this.loginInfo;
2399        final var isSecureLoggedIn = isSecure() && LoginInfo.isSuccess(loginInfo);
2400        if (isSecureLoggedIn && streamError.hasChild("conflict")) {
2401            if (loginInfo.saslVersion == SaslMechanism.Version.SASL_2) {
2402                this.appSettings.resetInstallationId();
2403            }
2404            account.setResource(createNewResource());
2405            Log.d(
2406                    Config.LOGTAG,
2407                    account.getJid().asBareJid()
2408                            + ": switching resource due to conflict ("
2409                            + account.getResource()
2410                            + ")");
2411            throw new IOException("Closed stream due to resource conflict");
2412        } else if (streamError.hasChild("host-unknown")) {
2413            throw new StateChangingException(Account.State.HOST_UNKNOWN);
2414        } else if (streamError.hasChild("policy-violation")) {
2415            this.lastConnectionStarted = SystemClock.elapsedRealtime();
2416            final String text = streamError.findChildContent("text");
2417            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2418            if (isSecureLoggedIn) {
2419                failPendingMessages(text);
2420            }
2421            throw new StateChangingException(Account.State.POLICY_VIOLATION);
2422        } else if (streamError.hasChild("see-other-host")) {
2423            final String seeOtherHost = streamError.findChildContent("see-other-host");
2424            final Resolver.Result currentResolverResult = this.currentResolverResult;
2425            if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2426                Log.d(
2427                        Config.LOGTAG,
2428                        account.getJid().asBareJid() + ": stream error " + streamError);
2429                throw new StateChangingException(Account.State.STREAM_ERROR);
2430            }
2431            Log.d(
2432                    Config.LOGTAG,
2433                    account.getJid().asBareJid()
2434                            + ": see other host: "
2435                            + seeOtherHost
2436                            + " "
2437                            + currentResolverResult);
2438            final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2439            if (seeOtherResult != null) {
2440                this.seeOtherHostResolverResult = seeOtherResult;
2441                throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2442            } else {
2443                throw new StateChangingException(Account.State.STREAM_ERROR);
2444            }
2445        } else {
2446            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2447            throw new StateChangingException(Account.State.STREAM_ERROR);
2448        }
2449    }
2450
2451    private void failPendingMessages(final String error) {
2452        synchronized (this.mStanzaQueue) {
2453            for (int i = 0; i < mStanzaQueue.size(); ++i) {
2454                final Stanza stanza = mStanzaQueue.valueAt(i);
2455                if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message packet) {
2456                    final String id = packet.getId();
2457                    final Jid to = packet.getTo();
2458                    mXmppConnectionService.markMessage(
2459                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2460                }
2461            }
2462        }
2463    }
2464
2465    private boolean establishStream(final SSLSockets.Version sslVersion)
2466            throws IOException, InterruptedException {
2467        final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2468        final SaslMechanism quickStartMechanism;
2469        if (secureConnection) {
2470            quickStartMechanism =
2471                    SaslMechanism.ensureAvailable(
2472                            account.getQuickStartMechanism(),
2473                            sslVersion,
2474                            appSettings.isRequireChannelBinding());
2475        } else {
2476            quickStartMechanism = null;
2477        }
2478        if (secureConnection
2479                && Config.QUICKSTART_ENABLED
2480                && quickStartMechanism != null
2481                && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2482            mXmppConnectionService.restoredFromDatabaseLatch.await();
2483            this.loginInfo =
2484                    new LoginInfo(
2485                            quickStartMechanism,
2486                            SaslMechanism.Version.SASL_2,
2487                            Bind2.QUICKSTART_FEATURES);
2488            final boolean usingFast = quickStartMechanism instanceof HashedToken;
2489            final AuthenticationRequest authenticate =
2490                    generateAuthenticationRequest(
2491                            quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)),
2492                            usingFast);
2493            authenticate.setMechanism(quickStartMechanism);
2494            sendStartStream(true, false);
2495            synchronized (this.mStanzaQueue) {
2496                this.stanzasSentBeforeAuthentication = this.stanzasSent;
2497                tagWriter.writeElement(authenticate);
2498            }
2499            Log.d(
2500                    Config.LOGTAG,
2501                    account.getJid().toString()
2502                            + ": quick start with "
2503                            + quickStartMechanism.getMechanism());
2504            return true;
2505        } else {
2506            sendStartStream(secureConnection, true);
2507            return false;
2508        }
2509    }
2510
2511    private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2512        final Tag stream = Tag.start("stream:stream");
2513        stream.setAttribute("to", account.getServer());
2514        if (from) {
2515            stream.setAttribute("from", account.getJid().asBareJid().toString());
2516        }
2517        stream.setAttribute("version", "1.0");
2518        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2519        stream.setAttribute("xmlns", Namespace.JABBER_CLIENT);
2520        stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2521        tagWriter.writeTag(stream, flush);
2522    }
2523
2524    private static String createNewResource() {
2525        return String.format("%s.%s", BuildConfig.APP_NAME, CryptoHelper.random(3));
2526    }
2527
2528    public ListenableFuture<Iq> sendIqPacket(final Iq request) {
2529        final SettableFuture<Iq> settable = SettableFuture.create();
2530        this.sendIqPacket(
2531                request,
2532                response -> {
2533                    final var type = response.getType();
2534                    switch (type) {
2535                        case RESULT -> settable.set(response);
2536                        case TIMEOUT -> settable.setException(new TimeoutException());
2537                        default -> settable.setException(new IqErrorResponseException(response));
2538                    }
2539                });
2540        return settable;
2541    }
2542
2543    public String sendIqPacket(final Iq packet, final Consumer<Iq> callback) {
2544        packet.setFrom(account.getJid());
2545        return this.sendUnmodifiedIqPacket(packet, callback, false);
2546    }
2547
2548    public synchronized String sendUnmodifiedIqPacket(
2549            final Iq packet, final Consumer<Iq> callback, boolean force) {
2550        // TODO if callback != null verify that type is get or set
2551        if (packet.getId() == null) {
2552            packet.setId(CryptoHelper.random(9));
2553        }
2554        if (callback != null) {
2555            synchronized (this.packetCallbacks) {
2556                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2557            }
2558        }
2559        this.sendPacket(packet, force);
2560        return packet.getId();
2561    }
2562
2563    public void sendResultFor(final Iq request, final Extension... extensions) {
2564        final var from = request.getFrom();
2565        final var id = request.getId();
2566        final var response = new Iq(Iq.Type.RESULT);
2567        response.setTo(from);
2568        response.setId(id);
2569        for (final Extension extension : extensions) {
2570            response.addExtension(extension);
2571        }
2572        this.sendPacket(response);
2573    }
2574
2575    public void sendErrorFor(
2576            final Iq request,
2577            final im.conversations.android.xmpp.model.error.Error.Type type,
2578            final Condition condition,
2579            final im.conversations.android.xmpp.model.error.Error.Extension... extensions) {
2580        final var from = request.getFrom();
2581        final var id = request.getId();
2582        final var response = new Iq(Iq.Type.ERROR);
2583        response.setTo(from);
2584        response.setId(id);
2585        final var error =
2586                response.addExtension(new im.conversations.android.xmpp.model.error.Error());
2587        error.setType(type);
2588        error.setCondition(condition);
2589        error.addExtensions(extensions);
2590        this.sendPacket(response);
2591    }
2592
2593    public void sendMessagePacket(final im.conversations.android.xmpp.model.stanza.Message packet) {
2594        this.sendPacket(packet);
2595    }
2596
2597    public void sendPresencePacket(final Presence packet) {
2598        this.sendPacket(packet);
2599    }
2600
2601    private synchronized void sendPacket(final StreamElement packet) {
2602        sendPacket(packet, false);
2603    }
2604
2605    private synchronized void sendPacket(final StreamElement packet, final boolean force) {
2606        if (stanzasSent == Integer.MAX_VALUE) {
2607            resetStreamId();
2608            disconnect(true);
2609            return;
2610        }
2611        synchronized (this.mStanzaQueue) {
2612            if (force || isBound) {
2613                tagWriter.writeStanzaAsync(packet);
2614            } else {
2615                Log.d(
2616                        Config.LOGTAG,
2617                        account.getJid().asBareJid()
2618                                + " do not write stanza to unbound stream "
2619                                + packet.toString());
2620            }
2621            if (packet instanceof Stanza stanza) {
2622                if (this.mStanzaQueue.size() != 0) {
2623                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2624                    if (currentHighestKey != stanzasSent) {
2625                        throw new AssertionError("Stanza count messed up");
2626                    }
2627                }
2628
2629                ++stanzasSent;
2630                if (Config.EXTENDED_SM_LOGGING) {
2631                    Log.d(
2632                            Config.LOGTAG,
2633                            account.getJid().asBareJid()
2634                                    + ": counting outbound "
2635                                    + packet.getName()
2636                                    + " as #"
2637                                    + stanzasSent);
2638                }
2639                this.mStanzaQueue.append(stanzasSent, stanza);
2640                if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message
2641                        && stanza.getId() != null
2642                        && inSmacksSession) {
2643                    if (Config.EXTENDED_SM_LOGGING) {
2644                        Log.d(
2645                                Config.LOGTAG,
2646                                account.getJid().asBareJid()
2647                                        + ": requesting ack for message stanza #"
2648                                        + stanzasSent);
2649                    }
2650                    tagWriter.writeStanzaAsync(new Request());
2651                }
2652            }
2653        }
2654    }
2655
2656    public void sendPing() {
2657        if (!r()) {
2658            final Iq iq = new Iq(Iq.Type.GET);
2659            iq.setFrom(account.getJid());
2660            iq.addChild("ping", Namespace.PING);
2661            this.sendIqPacket(iq, null);
2662        }
2663        this.lastPingSent = SystemClock.elapsedRealtime();
2664    }
2665
2666    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2667        this.jingleListener = listener;
2668    }
2669
2670    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2671        this.statusListener = listener;
2672    }
2673
2674    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2675        this.acknowledgedListener = listener;
2676    }
2677
2678    public void addOnAdvancedStreamFeaturesAvailableListener(
2679            final OnAdvancedStreamFeaturesLoaded listener) {
2680        this.advancedStreamFeaturesLoadedListeners.add(listener);
2681    }
2682
2683    private void forceCloseSocket() {
2684        FileBackend.close(this.socket);
2685        FileBackend.close(this.tagReader);
2686    }
2687
2688    public void interrupt() {
2689        if (this.mThread != null) {
2690            this.mThread.interrupt();
2691        }
2692    }
2693
2694    public void disconnect(final boolean force) {
2695        interrupt();
2696        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2697        if (force) {
2698            forceCloseSocket();
2699        } else {
2700            final TagWriter currentTagWriter = this.tagWriter;
2701            if (currentTagWriter.isActive()) {
2702                currentTagWriter.finish();
2703                final Socket currentSocket = this.socket;
2704                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2705                try {
2706                    currentTagWriter.await(1, TimeUnit.SECONDS);
2707                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2708                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2709                    if (streamCountDownLatch != null) {
2710                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2711                            Log.d(
2712                                    Config.LOGTAG,
2713                                    account.getJid().asBareJid() + ": remote ended stream");
2714                        } else {
2715                            Log.d(
2716                                    Config.LOGTAG,
2717                                    account.getJid().asBareJid()
2718                                            + ": remote has not closed socket. force closing");
2719                        }
2720                    }
2721                } catch (InterruptedException e) {
2722                    Log.d(
2723                            Config.LOGTAG,
2724                            account.getJid().asBareJid()
2725                                    + ": interrupted while gracefully closing stream");
2726                } catch (final IOException e) {
2727                    Log.d(
2728                            Config.LOGTAG,
2729                            account.getJid().asBareJid()
2730                                    + ": io exception during disconnect ("
2731                                    + e.getMessage()
2732                                    + ")");
2733                } finally {
2734                    FileBackend.close(currentSocket);
2735                }
2736            } else {
2737                forceCloseSocket();
2738            }
2739        }
2740    }
2741
2742    private void resetStreamId() {
2743        this.pendingResumeId.clear();
2744        this.streamId = null;
2745        this.boundStreamFeatures = null;
2746    }
2747
2748    public <M extends AbstractManager> M getManager(final Class<M> clazz) {
2749        return this.managers.getInstance(clazz);
2750    }
2751
2752    private List<Entry<Jid, InfoQuery>> findDiscoItemsByFeature(final String feature) {
2753        final List<Entry<Jid, InfoQuery>> items = new ArrayList<>();
2754        for (final Entry<Jid, InfoQuery> cursor :
2755                getManager(DiscoManager.class).getServerItems().entrySet()) {
2756            if (cursor.getValue().getFeatureStrings().contains(feature)) {
2757                items.add(cursor);
2758            }
2759        }
2760        return items;
2761    }
2762
2763    public Entry<Jid, InfoQuery> getServiceDiscoveryResultByFeature(final String feature) {
2764        return Iterables.getFirst(findDiscoItemsByFeature(feature), null);
2765    }
2766
2767    public Jid findDiscoItemByFeature(final String feature) {
2768        final var items = findDiscoItemsByFeature(feature);
2769        if (items.isEmpty()) {
2770            return null;
2771        }
2772        return Iterables.getFirst(items, null).getKey();
2773    }
2774
2775    public boolean r() {
2776        if (getFeatures().sm()) {
2777            this.tagWriter.writeStanzaAsync(new Request());
2778            return true;
2779        } else {
2780            return false;
2781        }
2782    }
2783
2784    public List<String> getMucServersWithholdAccount() {
2785        final List<String> servers = getMucServers();
2786        servers.remove(account.getDomain().toString());
2787        return servers;
2788    }
2789
2790    public List<String> getMucServers() {
2791        List<String> servers = new ArrayList<>();
2792        for (final Entry<Jid, InfoQuery> entry :
2793                getManager(DiscoManager.class).getServerItems().entrySet()) {
2794            final var value = entry.getValue();
2795            if (value.getFeatureStrings().contains("http://jabber.org/protocol/muc")
2796                    && value.hasIdentityWithCategoryAndType("conference", "text")
2797                    && !value.getFeatureStrings().contains("jabber:iq:gateway")
2798                    && !value.hasIdentityWithCategoryAndType("conference", "irc")) {
2799                servers.add(entry.getKey().toString());
2800            }
2801        }
2802        return servers;
2803    }
2804
2805    public String getMucServer() {
2806        return Iterables.getFirst(getMucServers(), null);
2807    }
2808
2809    public int getTimeToNextAttempt(final boolean aggressive) {
2810        final int interval;
2811        if (aggressive) {
2812            interval = Math.min((int) (3 * Math.pow(1.3, attempt)), 60);
2813        } else {
2814            final int additionalTime =
2815                    account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2816            interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2817        }
2818        final var connectionDuration = Ints.saturatedCast(getConnectionDuration() / 1000);
2819        return interval - connectionDuration;
2820    }
2821
2822    public int getAttempt() {
2823        return this.attempt;
2824    }
2825
2826    public Features getFeatures() {
2827        return this.features;
2828    }
2829
2830    public long getLastSessionEstablished() {
2831        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2832        return System.currentTimeMillis() - diff;
2833    }
2834
2835    public long getConnectionDuration() {
2836        return SystemClock.elapsedRealtime() - this.lastConnectionStarted;
2837    }
2838
2839    public long getDiscoDuration() {
2840        return SystemClock.elapsedRealtime() - this.lastDiscoStarted;
2841    }
2842
2843    public long getLastPingSent() {
2844        return this.lastPingSent;
2845    }
2846
2847    public long getLastPacketReceived() {
2848        return this.lastPacketReceived;
2849    }
2850
2851    public void sendActive() {
2852        this.sendPacket(new Active());
2853    }
2854
2855    public void sendInactive() {
2856        this.sendPacket(new Inactive());
2857    }
2858
2859    public void resetAttemptCount(boolean resetConnectTime) {
2860        this.attempt = 0;
2861        if (resetConnectTime) {
2862            this.lastConnectionStarted = 0;
2863        }
2864    }
2865
2866    public void setInteractive(boolean interactive) {
2867        this.mInteractive = interactive;
2868    }
2869
2870    private IqGenerator getIqGenerator() {
2871        return mXmppConnectionService.getIqGenerator();
2872    }
2873
2874    public void trackOfflineMessageRetrieval(boolean trackOfflineMessageRetrieval) {
2875        if (trackOfflineMessageRetrieval) {
2876            final Iq iqPing = new Iq(Iq.Type.GET);
2877            iqPing.addChild("ping", Namespace.PING);
2878            this.sendIqPacket(
2879                    iqPing,
2880                    (response) -> {
2881                        Log.d(
2882                                Config.LOGTAG,
2883                                account.getJid().asBareJid()
2884                                        + ": got ping response after sending initial presence");
2885                        XmppConnection.this.offlineMessagesRetrieved = true;
2886                    });
2887        } else {
2888            this.offlineMessagesRetrieved = true;
2889        }
2890    }
2891
2892    public boolean isOfflineMessagesRetrieved() {
2893        return this.offlineMessagesRetrieved;
2894    }
2895
2896    public void fetchRoster() {
2897        final Iq iqPacket = new Iq(Iq.Type.GET);
2898        final var version = account.getRosterVersion();
2899        if (Strings.isNullOrEmpty(account.getRosterVersion())) {
2900            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
2901        } else {
2902            Log.d(
2903                    Config.LOGTAG,
2904                    account.getJid().asBareJid() + ": fetching roster version " + version);
2905        }
2906        iqPacket.query(Namespace.ROSTER).setAttribute("ver", version);
2907        sendIqPacket(iqPacket, unregisteredIqListener);
2908    }
2909
2910    public void triggerConnectionTimeout() {
2911        final var duration = getConnectionDuration();
2912        Log.d(
2913                Config.LOGTAG,
2914                account.getJid().asBareJid() + ": connection timeout after " + duration + "ms");
2915
2916        // last connection time gets reset so time to next attempt is calculated correctly
2917        this.lastConnectionStarted = SystemClock.elapsedRealtime();
2918
2919        // interrupt needs to be called before status change; otherwise we interrupt the newly
2920        // created thread
2921        this.interrupt();
2922        this.forceCloseSocket();
2923        this.changeStatus(Account.State.CONNECTION_TIMEOUT);
2924    }
2925
2926    public Account getAccount() {
2927        return this.account;
2928    }
2929
2930    private class MyKeyManager implements X509KeyManager {
2931        @Override
2932        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2933            return account.getPrivateKeyAlias();
2934        }
2935
2936        @Override
2937        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2938            return null;
2939        }
2940
2941        @Override
2942        public X509Certificate[] getCertificateChain(String alias) {
2943            Log.d(Config.LOGTAG, "getting certificate chain");
2944            try {
2945                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2946            } catch (final Exception e) {
2947                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2948                return new X509Certificate[0];
2949            }
2950        }
2951
2952        @Override
2953        public String[] getClientAliases(String s, Principal[] principals) {
2954            final String alias = account.getPrivateKeyAlias();
2955            return alias != null ? new String[] {alias} : new String[0];
2956        }
2957
2958        @Override
2959        public String[] getServerAliases(String s, Principal[] principals) {
2960            return new String[0];
2961        }
2962
2963        @Override
2964        public PrivateKey getPrivateKey(String alias) {
2965            try {
2966                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2967            } catch (Exception e) {
2968                return null;
2969            }
2970        }
2971    }
2972
2973    private static class LoginInfo {
2974        public final SaslMechanism saslMechanism;
2975        public final SaslMechanism.Version saslVersion;
2976        public final List<String> inlineBindFeatures;
2977        public final AtomicBoolean success = new AtomicBoolean(false);
2978
2979        private LoginInfo(
2980                final SaslMechanism saslMechanism,
2981                final SaslMechanism.Version saslVersion,
2982                final Collection<String> inlineBindFeatures) {
2983            Preconditions.checkNotNull(saslMechanism, "SASL Mechanism must not be null");
2984            Preconditions.checkNotNull(saslVersion, "SASL version must not be null");
2985            this.saslMechanism = saslMechanism;
2986            this.saslVersion = saslVersion;
2987            this.inlineBindFeatures =
2988                    inlineBindFeatures == null
2989                            ? Collections.emptyList()
2990                            : ImmutableList.copyOf(inlineBindFeatures);
2991        }
2992
2993        public static SaslMechanism mechanism(final LoginInfo loginInfo) {
2994            return loginInfo == null ? null : loginInfo.saslMechanism;
2995        }
2996
2997        public void success(final String challenge, final SSLSocket sslSocket)
2998                throws SaslMechanism.AuthenticationException {
2999            if (Thread.currentThread().isInterrupted()) {
3000                throw new SaslMechanism.AuthenticationException("Race condition during auth");
3001            }
3002            final var response = this.saslMechanism.getResponse(challenge, sslSocket);
3003            if (!Strings.isNullOrEmpty(response)) {
3004                throw new SaslMechanism.AuthenticationException(
3005                        "processing success yielded another response");
3006            }
3007            if (this.success.compareAndSet(false, true)) {
3008                return;
3009            }
3010            throw new SaslMechanism.AuthenticationException("Process 'success' twice");
3011        }
3012
3013        public static boolean isSuccess(final LoginInfo loginInfo) {
3014            return loginInfo != null && loginInfo.success.get();
3015        }
3016    }
3017
3018    private static class StreamId {
3019        public final String id;
3020        public final Resolver.Result location;
3021
3022        private StreamId(String id, Resolver.Result location) {
3023            this.id = id;
3024            this.location = location;
3025        }
3026
3027        @NonNull
3028        @Override
3029        public String toString() {
3030            return MoreObjects.toStringHelper(this)
3031                    .add("id", id)
3032                    .add("location", location)
3033                    .toString();
3034        }
3035    }
3036
3037    private static class StateChangingError extends Error {
3038        private final Account.State state;
3039
3040        public StateChangingError(Account.State state) {
3041            this.state = state;
3042        }
3043    }
3044
3045    private static class StateChangingException extends IOException {
3046        private final Account.State state;
3047
3048        public StateChangingException(Account.State state) {
3049            this.state = state;
3050        }
3051    }
3052
3053    public abstract static class Delegate {
3054
3055        protected final Context context;
3056        protected final XmppConnection connection;
3057
3058        protected Delegate(final Context context, final XmppConnection connection) {
3059            this.context = context;
3060            this.connection = connection;
3061        }
3062
3063        protected Account getAccount() {
3064            return connection.account;
3065        }
3066
3067        protected DatabaseBackend getDatabase() {
3068            return DatabaseBackend.getInstance(context);
3069        }
3070
3071        protected <T extends AbstractManager> T getManager(final Class<T> type) {
3072            return connection.getManager(type);
3073        }
3074    }
3075
3076    public class Features {
3077        XmppConnection connection;
3078        private boolean carbonsEnabled = false;
3079        private boolean encryptionEnabled = false;
3080        private boolean blockListRequested = false;
3081
3082        public Features(final XmppConnection connection) {
3083            this.connection = connection;
3084        }
3085
3086        private boolean hasDiscoFeature(final Jid server, final String feature) {
3087            final var infoQuery = getManager(DiscoManager.class).get(server);
3088            return infoQuery != null && infoQuery.getFeatureStrings().contains(feature);
3089        }
3090
3091        public boolean carbons() {
3092            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
3093        }
3094
3095        public boolean commands() {
3096            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
3097        }
3098
3099        public boolean easyOnboardingInvites() {
3100            synchronized (commands) {
3101                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
3102            }
3103        }
3104
3105        public boolean bookmarksConversion() {
3106            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
3107                    && pepPublishOptions();
3108        }
3109
3110        public boolean blocking() {
3111            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
3112        }
3113
3114        public boolean spamReporting() {
3115            return hasDiscoFeature(account.getDomain(), Namespace.REPORTING);
3116        }
3117
3118        public boolean flexibleOfflineMessageRetrieval() {
3119            return hasDiscoFeature(
3120                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
3121        }
3122
3123        public boolean register() {
3124            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
3125        }
3126
3127        public boolean invite() {
3128            return connection.streamFeatures != null
3129                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
3130        }
3131
3132        public boolean sm() {
3133            return streamId != null
3134                    || (connection.streamFeatures != null
3135                            && connection.streamFeatures.streamManagement());
3136        }
3137
3138        public boolean csi() {
3139            return connection.streamFeatures != null
3140                    && connection.streamFeatures.clientStateIndication();
3141        }
3142
3143        public boolean pep() {
3144            final var infoQuery = getManager(DiscoManager.class).get(account.getJid().asBareJid());
3145            return infoQuery != null && infoQuery.hasIdentityWithCategoryAndType("pubsub", "pep");
3146        }
3147
3148        public boolean pepPersistent() {
3149            final var infoQuery = getManager(DiscoManager.class).get(account.getJid().asBareJid());
3150            return infoQuery != null
3151                    && infoQuery
3152                            .getFeatureStrings()
3153                            .contains("http://jabber.org/protocol/pubsub#persistent-items");
3154        }
3155
3156        public boolean bind2() {
3157            final var loginInfo = XmppConnection.this.loginInfo;
3158            return loginInfo != null && !loginInfo.inlineBindFeatures.isEmpty();
3159        }
3160
3161        public boolean sasl2() {
3162            final var loginInfo = XmppConnection.this.loginInfo;
3163            return loginInfo != null && loginInfo.saslVersion == SaslMechanism.Version.SASL_2;
3164        }
3165
3166        public String loginMechanism() {
3167            final var loginInfo = XmppConnection.this.loginInfo;
3168            return loginInfo == null ? null : loginInfo.saslMechanism.getMechanism();
3169        }
3170
3171        public boolean pepPublishOptions() {
3172            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
3173        }
3174
3175        public boolean pepConfigNodeMax() {
3176            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_CONFIG_NODE_MAX);
3177        }
3178
3179        public boolean pepOmemoWhitelisted() {
3180            return hasDiscoFeature(
3181                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
3182        }
3183
3184        public boolean mam() {
3185            return MessageArchiveService.Version.has(getAccountFeatures());
3186        }
3187
3188        public Collection<String> getAccountFeatures() {
3189            final var infoQuery = getManager(DiscoManager.class).get(account.getJid().asBareJid());
3190            return infoQuery == null ? Collections.emptyList() : infoQuery.getFeatureStrings();
3191        }
3192
3193        public boolean push() {
3194            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
3195                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
3196        }
3197
3198        public boolean rosterVersioning() {
3199            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
3200        }
3201
3202        public void setBlockListRequested(boolean value) {
3203            this.blockListRequested = value;
3204        }
3205
3206        public HttpUrl getServiceOutageStatus() {
3207            final var disco = getManager(DiscoManager.class).get(account.getDomain());
3208            if (disco == null) {
3209                return null;
3210            }
3211            final var address =
3212                    disco.getServiceDiscoveryExtension(
3213                            Namespace.SERVICE_OUTAGE_STATUS, "external-status-addresses");
3214            if (Strings.isNullOrEmpty(address)) {
3215                return null;
3216            }
3217            return HttpUrl.parse(address);
3218        }
3219
3220        public boolean httpUpload(long fileSize) {
3221            if (Config.DISABLE_HTTP_UPLOAD) {
3222                return false;
3223            }
3224            final var result = getServiceDiscoveryResultByFeature(Namespace.HTTP_UPLOAD);
3225            if (result == null) {
3226                return false;
3227            }
3228            final long maxSize;
3229            try {
3230                maxSize =
3231                        Long.parseLong(
3232                                result.getValue()
3233                                        .getServiceDiscoveryExtension(
3234                                                Namespace.HTTP_UPLOAD, "max-file-size"));
3235            } catch (final Exception e) {
3236                return true;
3237            }
3238            if (fileSize <= maxSize) {
3239                return true;
3240            } else {
3241                Log.d(
3242                        Config.LOGTAG,
3243                        account.getJid().asBareJid()
3244                                + ": http upload is not available for files with"
3245                                + " size "
3246                                + fileSize
3247                                + " (max is "
3248                                + maxSize
3249                                + ")");
3250                return false;
3251            }
3252        }
3253
3254        public long getMaxHttpUploadSize() {
3255            final var result = getServiceDiscoveryResultByFeature(Namespace.HTTP_UPLOAD);
3256            if (result == null) {
3257                return -1;
3258            }
3259            try {
3260                return Long.parseLong(
3261                        result.getValue()
3262                                .getServiceDiscoveryExtension(
3263                                        Namespace.HTTP_UPLOAD, "max-file-size"));
3264            } catch (final Exception e) {
3265                return -1;
3266                // ignored
3267            }
3268        }
3269
3270        public boolean stanzaIds() {
3271            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
3272        }
3273
3274        public boolean bookmarks2() {
3275            return pepPublishOptions()
3276                    && pepConfigNodeMax()
3277                    && hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT);
3278        }
3279
3280        public boolean externalServiceDiscovery() {
3281            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
3282        }
3283
3284        public boolean mds() {
3285            return pepPublishOptions()
3286                    && pepConfigNodeMax()
3287                    && Config.MESSAGE_DISPLAYED_SYNCHRONIZATION;
3288        }
3289
3290        public boolean mdsServerAssist() {
3291            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.MDS_DISPLAYED);
3292        }
3293    }
3294}