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