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        final var features = getFeatures();
2180        if (!features.bind2()) {
2181            discoverMamPreferences();
2182        }
2183        sendServiceDiscoveryInfo(account.getJid().asBareJid());
2184        if (!requestDiscoItemsFirst) {
2185            sendServiceDiscoveryItems(account.getDomain());
2186        }
2187
2188        if (!mWaitForDisco.get()) {
2189            finalizeBind();
2190        }
2191        this.lastSessionStarted = SystemClock.elapsedRealtime();
2192    }
2193
2194    private void sendServiceDiscoveryInfo(final Jid jid) {
2195        mPendingServiceDiscoveries.incrementAndGet();
2196        final Iq iq = new Iq(Iq.Type.GET);
2197        iq.setTo(jid);
2198        iq.query("http://jabber.org/protocol/disco#info");
2199        this.sendIqPacket(
2200                iq,
2201                (packet) -> {
2202                    if (packet.getType() == Iq.Type.RESULT) {
2203                        boolean advancedStreamFeaturesLoaded;
2204                        synchronized (XmppConnection.this.disco) {
2205                            ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
2206                            if (jid.equals(account.getDomain())) {
2207                                mXmppConnectionService.databaseBackend.insertDiscoveryResult(
2208                                        result);
2209                            }
2210                            disco.put(jid, result);
2211                            advancedStreamFeaturesLoaded =
2212                                    disco.containsKey(account.getDomain())
2213                                            && disco.containsKey(account.getJid().asBareJid());
2214                        }
2215                        if (advancedStreamFeaturesLoaded
2216                                && (jid.equals(account.getDomain())
2217                                        || jid.equals(account.getJid().asBareJid()))) {
2218                            enableAdvancedStreamFeatures();
2219                        }
2220                    } else if (packet.getType() == Iq.Type.ERROR) {
2221                        Log.d(
2222                                Config.LOGTAG,
2223                                account.getJid().asBareJid()
2224                                        + ": could not query disco info for "
2225                                        + jid.toString());
2226                        final boolean serverOrAccount =
2227                                jid.equals(account.getDomain())
2228                                        || jid.equals(account.getJid().asBareJid());
2229                        final boolean advancedStreamFeaturesLoaded;
2230                        if (serverOrAccount) {
2231                            synchronized (XmppConnection.this.disco) {
2232                                disco.put(jid, ServiceDiscoveryResult.empty());
2233                                advancedStreamFeaturesLoaded =
2234                                        disco.containsKey(account.getDomain())
2235                                                && disco.containsKey(account.getJid().asBareJid());
2236                            }
2237                        } else {
2238                            advancedStreamFeaturesLoaded = false;
2239                        }
2240                        if (advancedStreamFeaturesLoaded) {
2241                            enableAdvancedStreamFeatures();
2242                        }
2243                    }
2244                    if (packet.getType() != Iq.Type.TIMEOUT) {
2245                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2246                                && mWaitForDisco.compareAndSet(true, false)) {
2247                            finalizeBind();
2248                        }
2249                    }
2250                });
2251    }
2252
2253    private void discoverMamPreferences() {
2254        final Iq request = new Iq(Iq.Type.GET);
2255        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
2256        sendIqPacket(
2257                request,
2258                (response) -> {
2259                    if (response.getType() == Iq.Type.RESULT) {
2260                        Element prefs =
2261                                response.findChild(
2262                                        "prefs", MessageArchiveService.Version.MAM_2.namespace);
2263                        isMamPreferenceAlways =
2264                                "always"
2265                                        .equals(
2266                                                prefs == null
2267                                                        ? null
2268                                                        : prefs.getAttribute("default"));
2269                    }
2270                });
2271    }
2272
2273    private void discoverCommands() {
2274        final Iq request = new Iq(Iq.Type.GET);
2275        request.setTo(account.getDomain());
2276        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
2277        sendIqPacket(
2278                request,
2279                (response) -> {
2280                    if (response.getType() == Iq.Type.RESULT) {
2281                        final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
2282                        if (query == null) {
2283                            return;
2284                        }
2285                        final HashMap<String, Jid> commands = new HashMap<>();
2286                        for (final Element child : query.getChildren()) {
2287                            if ("item".equals(child.getName())) {
2288                                final String node = child.getAttribute("node");
2289                                final Jid jid = child.getAttributeAsJid("jid");
2290                                if (node != null && jid != null) {
2291                                    commands.put(node, jid);
2292                                }
2293                            }
2294                        }
2295                        synchronized (this.commands) {
2296                            this.commands.clear();
2297                            this.commands.putAll(commands);
2298                        }
2299                    }
2300                });
2301    }
2302
2303    public boolean isMamPreferenceAlways() {
2304        return isMamPreferenceAlways;
2305    }
2306
2307    private void finalizeBind() {
2308        this.offlineMessagesRetrieved = false;
2309        this.bindListener.run();
2310        this.changeStatusToOnline();
2311    }
2312
2313    private void enableAdvancedStreamFeatures() {
2314        if (getFeatures().blocking() && !features.blockListRequested) {
2315            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
2316            this.sendIqPacket(getIqGenerator().generateGetBlockList(), unregisteredIqListener);
2317        }
2318        for (final OnAdvancedStreamFeaturesLoaded listener :
2319                advancedStreamFeaturesLoadedListeners) {
2320            listener.onAdvancedStreamFeaturesAvailable(account);
2321        }
2322        if (getFeatures().carbons() && !features.carbonsEnabled) {
2323            sendEnableCarbons();
2324        }
2325        if (getFeatures().commands()) {
2326            discoverCommands();
2327        }
2328    }
2329
2330    private void sendServiceDiscoveryItems(final Jid server) {
2331        mPendingServiceDiscoveries.incrementAndGet();
2332        final Iq iq = new Iq(Iq.Type.GET);
2333        iq.setTo(server.getDomain());
2334        iq.query("http://jabber.org/protocol/disco#items");
2335        this.sendIqPacket(
2336                iq,
2337                (packet) -> {
2338                    if (packet.getType() == Iq.Type.RESULT) {
2339                        final HashSet<Jid> items = new HashSet<>();
2340                        final List<Element> elements = packet.query().getChildren();
2341                        for (final Element element : elements) {
2342                            if (element.getName().equals("item")) {
2343                                final Jid jid =
2344                                        InvalidJid.getNullForInvalid(
2345                                                element.getAttributeAsJid("jid"));
2346                                if (jid != null && !jid.equals(account.getDomain())) {
2347                                    items.add(jid);
2348                                }
2349                            }
2350                        }
2351                        for (Jid jid : items) {
2352                            sendServiceDiscoveryInfo(jid);
2353                        }
2354                    } else {
2355                        Log.d(
2356                                Config.LOGTAG,
2357                                account.getJid().asBareJid()
2358                                        + ": could not query disco items of "
2359                                        + server);
2360                    }
2361                    if (packet.getType() != Iq.Type.TIMEOUT) {
2362                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2363                                && mWaitForDisco.compareAndSet(true, false)) {
2364                            finalizeBind();
2365                        }
2366                    }
2367                });
2368    }
2369
2370    private void sendEnableCarbons() {
2371        final Iq iq = new Iq(Iq.Type.SET);
2372        iq.addChild("enable", Namespace.CARBONS);
2373        this.sendIqPacket(
2374                iq,
2375                (packet) -> {
2376                    if (packet.getType() == Iq.Type.RESULT) {
2377                        Log.d(
2378                                Config.LOGTAG,
2379                                account.getJid().asBareJid() + ": successfully enabled carbons");
2380                        features.carbonsEnabled = true;
2381                    } else {
2382                        Log.d(
2383                                Config.LOGTAG,
2384                                account.getJid().asBareJid()
2385                                        + ": could not enable carbons "
2386                                        + packet);
2387                    }
2388                });
2389    }
2390
2391    private void processStreamError(final Tag currentTag) throws IOException {
2392        final Element streamError = tagReader.readElement(currentTag);
2393        if (streamError == null) {
2394            return;
2395        }
2396        if (streamError.hasChild("conflict")) {
2397            final var loginInfo = this.loginInfo;
2398            if (loginInfo != null && loginInfo.saslVersion == SaslMechanism.Version.SASL_2) {
2399                this.appSettings.resetInstallationId();
2400            }
2401            account.setResource(createNewResource());
2402            Log.d(
2403                    Config.LOGTAG,
2404                    account.getJid().asBareJid()
2405                            + ": switching resource due to conflict ("
2406                            + account.getResource()
2407                            + ")");
2408            throw new IOException("Closed stream due to resource conflict");
2409        } else if (streamError.hasChild("host-unknown")) {
2410            throw new StateChangingException(Account.State.HOST_UNKNOWN);
2411        } else if (streamError.hasChild("policy-violation")) {
2412            this.lastConnect = SystemClock.elapsedRealtime();
2413            final String text = streamError.findChildContent("text");
2414            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2415            failPendingMessages(text);
2416            throw new StateChangingException(Account.State.POLICY_VIOLATION);
2417        } else if (streamError.hasChild("see-other-host")) {
2418            final String seeOtherHost = streamError.findChildContent("see-other-host");
2419            final Resolver.Result currentResolverResult = this.currentResolverResult;
2420            if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2421                Log.d(
2422                        Config.LOGTAG,
2423                        account.getJid().asBareJid() + ": stream error " + streamError);
2424                throw new StateChangingException(Account.State.STREAM_ERROR);
2425            }
2426            Log.d(
2427                    Config.LOGTAG,
2428                    account.getJid().asBareJid()
2429                            + ": see other host: "
2430                            + seeOtherHost
2431                            + " "
2432                            + currentResolverResult);
2433            final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2434            if (seeOtherResult != null) {
2435                this.seeOtherHostResolverResult = seeOtherResult;
2436                throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2437            } else {
2438                throw new StateChangingException(Account.State.STREAM_ERROR);
2439            }
2440        } else {
2441            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2442            throw new StateChangingException(Account.State.STREAM_ERROR);
2443        }
2444    }
2445
2446    private void failPendingMessages(final String error) {
2447        synchronized (this.mStanzaQueue) {
2448            for (int i = 0; i < mStanzaQueue.size(); ++i) {
2449                final Stanza stanza = mStanzaQueue.valueAt(i);
2450                if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message packet) {
2451                    final String id = packet.getId();
2452                    final Jid to = packet.getTo();
2453                    mXmppConnectionService.markMessage(
2454                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2455                }
2456            }
2457        }
2458    }
2459
2460    private boolean establishStream(final SSLSockets.Version sslVersion)
2461            throws IOException, InterruptedException {
2462        final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2463        final SaslMechanism quickStartMechanism;
2464        if (secureConnection) {
2465            quickStartMechanism =
2466                    SaslMechanism.ensureAvailable(
2467                            account.getQuickStartMechanism(),
2468                            sslVersion,
2469                            appSettings.isRequireChannelBinding());
2470        } else {
2471            quickStartMechanism = null;
2472        }
2473        if (secureConnection
2474                && Config.QUICKSTART_ENABLED
2475                && quickStartMechanism != null
2476                && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2477            mXmppConnectionService.restoredFromDatabaseLatch.await();
2478            this.loginInfo =
2479                    new LoginInfo(
2480                            quickStartMechanism,
2481                            SaslMechanism.Version.SASL_2,
2482                            Bind2.QUICKSTART_FEATURES);
2483            final boolean usingFast = quickStartMechanism instanceof HashedToken;
2484            final AuthenticationRequest authenticate =
2485                    generateAuthenticationRequest(
2486                            quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)),
2487                            usingFast);
2488            authenticate.setMechanism(quickStartMechanism);
2489            sendStartStream(true, false);
2490            synchronized (this.mStanzaQueue) {
2491                this.stanzasSentBeforeAuthentication = this.stanzasSent;
2492                tagWriter.writeElement(authenticate);
2493            }
2494            Log.d(
2495                    Config.LOGTAG,
2496                    account.getJid().toString()
2497                            + ": quick start with "
2498                            + quickStartMechanism.getMechanism());
2499            return true;
2500        } else {
2501            sendStartStream(secureConnection, true);
2502            return false;
2503        }
2504    }
2505
2506    private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2507        final Tag stream = Tag.start("stream:stream");
2508        stream.setAttribute("to", account.getServer());
2509        if (from) {
2510            stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2511        }
2512        stream.setAttribute("version", "1.0");
2513        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2514        stream.setAttribute("xmlns", Namespace.JABBER_CLIENT);
2515        stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2516        tagWriter.writeTag(stream, flush);
2517    }
2518
2519    private static String createNewResource() {
2520        return String.format("%s.%s", BuildConfig.APP_NAME, CryptoHelper.random(3));
2521    }
2522
2523    public String sendIqPacket(final Iq packet, final Consumer<Iq> callback) {
2524        return sendIqPacket(packet, callback, null);
2525    }
2526
2527    public String sendIqPacket(final Iq packet, final Consumer<Iq> callback, Long timeout) {
2528        packet.setFrom(account.getJid());
2529        return this.sendUnmodifiedIqPacket(packet, callback, false, timeout);
2530    }
2531
2532    public String sendUnmodifiedIqPacket(final Iq packet, final Consumer<Iq> callback, boolean force) {
2533        return sendUnmodifiedIqPacket(packet, callback, force, null);
2534    }
2535
2536    public synchronized String sendUnmodifiedIqPacket(
2537            final Iq packet, final Consumer<Iq> callback, boolean force, Long timeout) {
2538        // TODO if callback != null verify that type is get or set
2539        if (packet.getId() == null) {
2540            packet.setId(CryptoHelper.random(9));
2541        }
2542        if (callback != null) {
2543            synchronized (this.packetCallbacks) {
2544                ScheduledFuture timeoutFuture = null;
2545                if (timeout != null) {
2546                    timeoutFuture = SCHEDULER.schedule(() -> {
2547                        synchronized (this.packetCallbacks) {
2548                            final var failurePacket = new Iq(Iq.Type.TIMEOUT);
2549                            final var removedCallback = packetCallbacks.remove(packet.getId());
2550                            if (removedCallback != null) removedCallback.second.first.accept(failurePacket);
2551                        }
2552                    }, timeout, TimeUnit.SECONDS);
2553                }
2554                packetCallbacks.put(packet.getId(), new Pair<>(packet, new Pair<>(callback, timeoutFuture)));
2555            }
2556        }
2557        this.sendPacket(packet, force);
2558        return packet.getId();
2559    }
2560
2561    public void sendMessagePacket(final im.conversations.android.xmpp.model.stanza.Message packet) {
2562        this.sendPacket(packet);
2563    }
2564
2565    public void sendPresencePacket(final Presence packet) {
2566        this.sendPacket(packet);
2567    }
2568
2569    private synchronized void sendPacket(final StreamElement packet) {
2570        sendPacket(packet, false);
2571    }
2572
2573    private synchronized void sendPacket(final StreamElement packet, final boolean force) {
2574        if (stanzasSent == Integer.MAX_VALUE) {
2575            resetStreamId();
2576            disconnect(true);
2577            return;
2578        }
2579        synchronized (this.mStanzaQueue) {
2580            if (force || isBound) {
2581                tagWriter.writeStanzaAsync(packet);
2582            } else {
2583                Log.d(
2584                        Config.LOGTAG,
2585                        account.getJid().asBareJid()
2586                                + " do not write stanza to unbound stream "
2587                                + packet.toString());
2588            }
2589            if (packet instanceof Stanza stanza) {
2590                if (this.mStanzaQueue.size() != 0) {
2591                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2592                    if (currentHighestKey != stanzasSent) {
2593                        throw new AssertionError("Stanza count messed up");
2594                    }
2595                }
2596
2597                ++stanzasSent;
2598                if (Config.EXTENDED_SM_LOGGING) {
2599                    Log.d(
2600                            Config.LOGTAG,
2601                            account.getJid().asBareJid()
2602                                    + ": counting outbound "
2603                                    + packet.getName()
2604                                    + " as #"
2605                                    + stanzasSent);
2606                }
2607                this.mStanzaQueue.append(stanzasSent, stanza);
2608                if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message
2609                        && stanza.getId() != null
2610                        && inSmacksSession) {
2611                    if (Config.EXTENDED_SM_LOGGING) {
2612                        Log.d(
2613                                Config.LOGTAG,
2614                                account.getJid().asBareJid()
2615                                        + ": requesting ack for message stanza #"
2616                                        + stanzasSent);
2617                    }
2618                    tagWriter.writeStanzaAsync(new Request());
2619                }
2620            }
2621        }
2622    }
2623
2624    public void sendPing() {
2625        if (!r()) {
2626            final Iq iq = new Iq(Iq.Type.GET);
2627            iq.setFrom(account.getJid());
2628            iq.addChild("ping", Namespace.PING);
2629            this.sendIqPacket(iq, null);
2630        }
2631        this.lastPingSent = SystemClock.elapsedRealtime();
2632    }
2633
2634    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2635        this.jingleListener = listener;
2636    }
2637
2638    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2639        this.statusListener = listener;
2640    }
2641
2642    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2643        this.acknowledgedListener = listener;
2644    }
2645
2646    public void addOnAdvancedStreamFeaturesAvailableListener(
2647            final OnAdvancedStreamFeaturesLoaded listener) {
2648        this.advancedStreamFeaturesLoadedListeners.add(listener);
2649    }
2650
2651    private void forceCloseSocket() {
2652        FileBackend.close(this.socket);
2653        FileBackend.close(this.tagReader);
2654    }
2655
2656    public void interrupt() {
2657        if (this.mThread != null) {
2658            this.mThread.interrupt();
2659        }
2660    }
2661
2662    public void disconnect(final boolean force) {
2663        interrupt();
2664        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2665        if (force) {
2666            forceCloseSocket();
2667        } else {
2668            final TagWriter currentTagWriter = this.tagWriter;
2669            if (currentTagWriter.isActive()) {
2670                currentTagWriter.finish();
2671                final Socket currentSocket = this.socket;
2672                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2673                try {
2674                    currentTagWriter.await(1, TimeUnit.SECONDS);
2675                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2676                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2677                    if (streamCountDownLatch != null) {
2678                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2679                            Log.d(
2680                                    Config.LOGTAG,
2681                                    account.getJid().asBareJid() + ": remote ended stream");
2682                        } else {
2683                            Log.d(
2684                                    Config.LOGTAG,
2685                                    account.getJid().asBareJid()
2686                                            + ": remote has not closed socket. force closing");
2687                        }
2688                    }
2689                } catch (InterruptedException e) {
2690                    Log.d(
2691                            Config.LOGTAG,
2692                            account.getJid().asBareJid()
2693                                    + ": interrupted while gracefully closing stream");
2694                } catch (final IOException e) {
2695                    Log.d(
2696                            Config.LOGTAG,
2697                            account.getJid().asBareJid()
2698                                    + ": io exception during disconnect ("
2699                                    + e.getMessage()
2700                                    + ")");
2701                } finally {
2702                    FileBackend.close(currentSocket);
2703                }
2704            } else {
2705                forceCloseSocket();
2706            }
2707        }
2708    }
2709
2710    private void resetStreamId() {
2711        this.streamId = null;
2712        this.boundStreamFeatures = null;
2713    }
2714
2715    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2716        synchronized (this.disco) {
2717            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2718            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2719                if (cursor.getValue().getFeatures().contains(feature)) {
2720                    items.add(cursor);
2721                }
2722            }
2723            return items;
2724        }
2725    }
2726
2727    public Jid findDiscoItemByFeature(final String feature) {
2728        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2729        if (items.size() >= 1) {
2730            return items.get(0).getKey();
2731        }
2732        return null;
2733    }
2734
2735    public boolean r() {
2736        if (getFeatures().sm()) {
2737            this.tagWriter.writeStanzaAsync(new Request());
2738            return true;
2739        } else {
2740            return false;
2741        }
2742    }
2743
2744    public List<String> getMucServersWithholdAccount() {
2745        final List<String> servers = getMucServers();
2746        servers.remove(account.getDomain().toEscapedString());
2747        return servers;
2748    }
2749
2750    public List<String> getMucServers() {
2751        List<String> servers = new ArrayList<>();
2752        synchronized (this.disco) {
2753            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2754                final ServiceDiscoveryResult value = cursor.getValue();
2755                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2756                        && value.hasIdentity("conference", "text")
2757                        && !value.getFeatures().contains("jabber:iq:gateway")
2758                        && !value.hasIdentity("conference", "irc")) {
2759                    servers.add(cursor.getKey().toString());
2760                }
2761            }
2762        }
2763        return servers;
2764    }
2765
2766    public String getMucServer() {
2767        List<String> servers = getMucServers();
2768        return servers.size() > 0 ? servers.get(0) : null;
2769    }
2770
2771    public int getTimeToNextAttempt(final boolean aggressive) {
2772        final int interval;
2773        if (aggressive) {
2774            interval = Math.min((int) (3 * Math.pow(1.3, attempt)), 60);
2775        } else {
2776            final int additionalTime =
2777                    account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2778            interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2779        }
2780        final int secondsSinceLast =
2781                (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2782        return interval - secondsSinceLast;
2783    }
2784
2785    public int getAttempt() {
2786        return this.attempt;
2787    }
2788
2789    public Features getFeatures() {
2790        return this.features;
2791    }
2792
2793    public long getLastSessionEstablished() {
2794        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2795        return System.currentTimeMillis() - diff;
2796    }
2797
2798    public long getLastConnect() {
2799        return this.lastConnect;
2800    }
2801
2802    public long getLastPingSent() {
2803        return this.lastPingSent;
2804    }
2805
2806    public long getLastDiscoStarted() {
2807        return this.lastDiscoStarted;
2808    }
2809
2810    public long getLastPacketReceived() {
2811        return this.lastPacketReceived;
2812    }
2813
2814    public void sendActive() {
2815        this.sendPacket(new Active());
2816    }
2817
2818    public void sendInactive() {
2819        this.sendPacket(new Inactive());
2820    }
2821
2822    public void resetAttemptCount(boolean resetConnectTime) {
2823        this.attempt = 0;
2824        if (resetConnectTime) {
2825            this.lastConnect = 0;
2826        }
2827    }
2828
2829    public void setInteractive(boolean interactive) {
2830        this.mInteractive = interactive;
2831    }
2832
2833    private IqGenerator getIqGenerator() {
2834        return mXmppConnectionService.getIqGenerator();
2835    }
2836
2837    public void trackOfflineMessageRetrieval(boolean trackOfflineMessageRetrieval) {
2838        if (trackOfflineMessageRetrieval) {
2839            final Iq iqPing = new Iq(Iq.Type.GET);
2840            iqPing.addChild("ping", Namespace.PING);
2841            this.sendIqPacket(
2842                    iqPing,
2843                    (response) -> {
2844                        Log.d(
2845                                Config.LOGTAG,
2846                                account.getJid().asBareJid()
2847                                        + ": got ping response after sending initial presence");
2848                        XmppConnection.this.offlineMessagesRetrieved = true;
2849                    });
2850        } else {
2851            this.offlineMessagesRetrieved = true;
2852        }
2853    }
2854
2855    public boolean isOfflineMessagesRetrieved() {
2856        return this.offlineMessagesRetrieved;
2857    }
2858
2859    public void fetchRoster() {
2860        final Iq iqPacket = new Iq(Iq.Type.GET);
2861        final var version = account.getRosterVersion();
2862        if (Strings.isNullOrEmpty(account.getRosterVersion())) {
2863            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
2864        } else {
2865            Log.d(
2866                    Config.LOGTAG,
2867                    account.getJid().asBareJid() + ": fetching roster version " + version);
2868        }
2869        iqPacket.query(Namespace.ROSTER).setAttribute("ver", version);
2870        sendIqPacket(iqPacket, unregisteredIqListener);
2871    }
2872
2873    private class MyKeyManager implements X509KeyManager {
2874        @Override
2875        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2876            return account.getPrivateKeyAlias();
2877        }
2878
2879        @Override
2880        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2881            return null;
2882        }
2883
2884        @Override
2885        public X509Certificate[] getCertificateChain(String alias) {
2886            Log.d(Config.LOGTAG, "getting certificate chain");
2887            try {
2888                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2889            } catch (final Exception e) {
2890                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2891                return new X509Certificate[0];
2892            }
2893        }
2894
2895        @Override
2896        public String[] getClientAliases(String s, Principal[] principals) {
2897            final String alias = account.getPrivateKeyAlias();
2898            return alias != null ? new String[] {alias} : new String[0];
2899        }
2900
2901        @Override
2902        public String[] getServerAliases(String s, Principal[] principals) {
2903            return new String[0];
2904        }
2905
2906        @Override
2907        public PrivateKey getPrivateKey(String alias) {
2908            try {
2909                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2910            } catch (Exception e) {
2911                return null;
2912            }
2913        }
2914    }
2915
2916    private static class LoginInfo {
2917        public final SaslMechanism saslMechanism;
2918        public final SaslMechanism.Version saslVersion;
2919        public final List<String> inlineBindFeatures;
2920        public final AtomicBoolean success = new AtomicBoolean(false);
2921
2922        private LoginInfo(
2923                final SaslMechanism saslMechanism,
2924                final SaslMechanism.Version saslVersion,
2925                final Collection<String> inlineBindFeatures) {
2926            Preconditions.checkNotNull(saslMechanism, "SASL Mechanism must not be null");
2927            Preconditions.checkNotNull(saslVersion, "SASL version must not be null");
2928            this.saslMechanism = saslMechanism;
2929            this.saslVersion = saslVersion;
2930            this.inlineBindFeatures =
2931                    inlineBindFeatures == null
2932                            ? Collections.emptyList()
2933                            : ImmutableList.copyOf(inlineBindFeatures);
2934        }
2935
2936        public static SaslMechanism mechanism(final LoginInfo loginInfo) {
2937            return loginInfo == null ? null : loginInfo.saslMechanism;
2938        }
2939
2940        public void success(final String challenge, final SSLSocket sslSocket)
2941                throws SaslMechanism.AuthenticationException {
2942            final var response = this.saslMechanism.getResponse(challenge, sslSocket);
2943            if (!Strings.isNullOrEmpty(response)) {
2944                throw new SaslMechanism.AuthenticationException(
2945                        "processing success yielded another response");
2946            }
2947            if (this.success.compareAndSet(false, true)) {
2948                return;
2949            }
2950            throw new SaslMechanism.AuthenticationException("Process 'success' twice");
2951        }
2952
2953        public static boolean isSuccess(final LoginInfo loginInfo) {
2954            return loginInfo != null && loginInfo.success.get();
2955        }
2956    }
2957
2958    private static class StreamId {
2959        public final String id;
2960        public final Resolver.Result location;
2961
2962        private StreamId(String id, Resolver.Result location) {
2963            this.id = id;
2964            this.location = location;
2965        }
2966
2967        @NonNull
2968        @Override
2969        public String toString() {
2970            return MoreObjects.toStringHelper(this)
2971                    .add("id", id)
2972                    .add("location", location)
2973                    .toString();
2974        }
2975    }
2976
2977    private static class StateChangingError extends Error {
2978        private final Account.State state;
2979
2980        public StateChangingError(Account.State state) {
2981            this.state = state;
2982        }
2983    }
2984
2985    private static class StateChangingException extends IOException {
2986        private final Account.State state;
2987
2988        public StateChangingException(Account.State state) {
2989            this.state = state;
2990        }
2991    }
2992
2993    public class Features {
2994        XmppConnection connection;
2995        private boolean carbonsEnabled = false;
2996        private boolean encryptionEnabled = false;
2997        private boolean blockListRequested = false;
2998
2999        public Features(final XmppConnection connection) {
3000            this.connection = connection;
3001        }
3002
3003        private boolean hasDiscoFeature(final Jid server, final String feature) {
3004            synchronized (XmppConnection.this.disco) {
3005                final ServiceDiscoveryResult sdr = connection.disco.get(server);
3006                return sdr != null && sdr.getFeatures().contains(feature);
3007            }
3008        }
3009
3010        public boolean carbons() {
3011            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
3012        }
3013
3014        public boolean commands() {
3015            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
3016        }
3017
3018        public boolean easyOnboardingInvites() {
3019            synchronized (commands) {
3020                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
3021            }
3022        }
3023
3024        public boolean bookmarksConversion() {
3025            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
3026                    && pepPublishOptions();
3027        }
3028
3029        public boolean blocking() {
3030            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
3031        }
3032
3033        public boolean spamReporting() {
3034            return hasDiscoFeature(account.getDomain(), Namespace.REPORTING);
3035        }
3036
3037        public boolean flexibleOfflineMessageRetrieval() {
3038            return hasDiscoFeature(
3039                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
3040        }
3041
3042        public boolean register() {
3043            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
3044        }
3045
3046        public boolean invite() {
3047            return connection.streamFeatures != null
3048                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
3049        }
3050
3051        public boolean sm() {
3052            return streamId != null
3053                    || (connection.streamFeatures != null
3054                            && connection.streamFeatures.streamManagement());
3055        }
3056
3057        public boolean csi() {
3058            return connection.streamFeatures != null
3059                    && connection.streamFeatures.clientStateIndication();
3060        }
3061
3062        public boolean pep() {
3063            synchronized (XmppConnection.this.disco) {
3064                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
3065                return info != null && info.hasIdentity("pubsub", "pep");
3066            }
3067        }
3068
3069        public boolean pepPersistent() {
3070            synchronized (XmppConnection.this.disco) {
3071                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
3072                return info != null
3073                        && info.getFeatures()
3074                                .contains("http://jabber.org/protocol/pubsub#persistent-items");
3075            }
3076        }
3077
3078        public boolean bind2() {
3079            final var loginInfo = XmppConnection.this.loginInfo;
3080            return loginInfo != null && !loginInfo.inlineBindFeatures.isEmpty();
3081        }
3082
3083        public boolean sasl2() {
3084            final var loginInfo = XmppConnection.this.loginInfo;
3085            return loginInfo != null && loginInfo.saslVersion == SaslMechanism.Version.SASL_2;
3086        }
3087
3088        public String loginMechanism() {
3089            final var loginInfo = XmppConnection.this.loginInfo;
3090            return loginInfo == null ? null : loginInfo.saslMechanism.getMechanism();
3091        }
3092
3093        public boolean pepPublishOptions() {
3094            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
3095        }
3096
3097        public boolean pepConfigNodeMax() {
3098            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_CONFIG_NODE_MAX);
3099        }
3100
3101        public boolean pepOmemoWhitelisted() {
3102            return hasDiscoFeature(
3103                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
3104        }
3105
3106        public boolean mam() {
3107            return MessageArchiveService.Version.has(getAccountFeatures());
3108        }
3109
3110        public List<String> getAccountFeatures() {
3111            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
3112            return result == null ? Collections.emptyList() : result.getFeatures();
3113        }
3114
3115        public boolean push() {
3116            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
3117                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
3118        }
3119
3120        public boolean rosterVersioning() {
3121            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
3122        }
3123
3124        public void setBlockListRequested(boolean value) {
3125            this.blockListRequested = value;
3126        }
3127
3128        public boolean httpUpload(long filesize) {
3129            if (Config.DISABLE_HTTP_UPLOAD) {
3130                return false;
3131            } else {
3132                for (String namespace :
3133                        new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3134                    List<Entry<Jid, ServiceDiscoveryResult>> items =
3135                            findDiscoItemsByFeature(namespace);
3136                    if (items.size() > 0) {
3137                        try {
3138                            long maxsize =
3139                                    Long.parseLong(
3140                                            items.get(0)
3141                                                    .getValue()
3142                                                    .getExtendedDiscoInformation(
3143                                                            namespace, "max-file-size"));
3144                            if (filesize <= maxsize) {
3145                                return true;
3146                            } else {
3147                                Log.d(
3148                                        Config.LOGTAG,
3149                                        account.getJid().asBareJid()
3150                                                + ": http upload is not available for files with size "
3151                                                + filesize
3152                                                + " (max is "
3153                                                + maxsize
3154                                                + ")");
3155                                return false;
3156                            }
3157                        } catch (Exception e) {
3158                            return true;
3159                        }
3160                    }
3161                }
3162                return false;
3163            }
3164        }
3165
3166        public boolean useLegacyHttpUpload() {
3167            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
3168                    && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
3169        }
3170
3171        public long getMaxHttpUploadSize() {
3172            for (String namespace :
3173                    new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3174                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
3175                if (items.size() > 0) {
3176                    try {
3177                        return Long.parseLong(
3178                                items.get(0)
3179                                        .getValue()
3180                                        .getExtendedDiscoInformation(namespace, "max-file-size"));
3181                    } catch (Exception e) {
3182                        // ignored
3183                    }
3184                }
3185            }
3186            return -1;
3187        }
3188
3189        public boolean stanzaIds() {
3190            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
3191        }
3192
3193        public boolean bookmarks2() {
3194            return pepPublishOptions()
3195                    && hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT);
3196        }
3197
3198        public boolean externalServiceDiscovery() {
3199            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
3200        }
3201
3202        public boolean mds() {
3203            return pepPublishOptions()
3204                    && pepConfigNodeMax()
3205                    && Config.MESSAGE_DISPLAYED_SYNCHRONIZATION;
3206        }
3207
3208        public boolean mdsServerAssist() {
3209            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.MDS_DISPLAYED);
3210        }
3211    }
3212}