XmppConnection.java

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