XmppConnection.java

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