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