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