XmppConnection.java

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